From 45257fa7a29933b0a3767a678b948d7b35b4a619 Mon Sep 17 00:00:00 2001 From: James Hu Date: Sat, 11 Nov 2023 12:51:15 -0800 Subject: [PATCH] lgtm --- README.md | 2 ++ docker-compose.yml | 1 + lib/middleware/collector.rb | 29 ++++++++++++++++++++--------- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9421738..dd19736 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,8 @@ These environment variables can be passed into the container (defaults are in pa - Plex Media Server token * `PLEX_TIMEOUT` (`10`) - How long to wait for Plex Media Server to respond +* `PLEX_RETRIES_COUNT` (`0`) + - How many times to retry Plex Media Server requests if they fail * `METRICS_PREFIX` (`plex`) - What to prefix metric names with * `METRICS_MEDIA_COLLECTING_INTERVAL_SECONDS` (`300`) diff --git a/docker-compose.yml b/docker-compose.yml index 9fe604b..c78bb69 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,7 @@ services: # Can be set in .env - PLEX_ADDR=${PLEX_ADDR} - PLEX_TOKEN=${PLEX_TOKEN} + - PLEX_RETRIES_COUNT=${PLEX_RETRIES_COUNT} - METRICS_MEDIA_COLLECTING_INTERVAL_SECONDS=300 volumes: - .:/srv:delegated diff --git a/lib/middleware/collector.rb b/lib/middleware/collector.rb index 3dd88aa..6a6a563 100644 --- a/lib/middleware/collector.rb +++ b/lib/middleware/collector.rb @@ -9,7 +9,9 @@ def initialize(app) # Plex configs @plex_addr = ENV["PLEX_ADDR"] || "http://localhost:32400" + @plex_token = ENV["PLEX_TOKEN"] @plex_timeout = ENV["PLEX_TIMEOUT"]&.to_i || 10 + @plex_retries_count = ENV["PLEX_RETRIES_COUNT"]&.to_i || 0 # Metrics configs @metrics_prefix = ENV["METRICS_PREFIX"] || "plex" @@ -203,15 +205,24 @@ def fetch_media_section_count(key:, params: {}, **options) end def send_plex_api_request(method:, endpoint:, **options) - response = HTTP - .timeout(@plex_timeout) - .headers( - "X-Plex-Token" => ENV["PLEX_TOKEN"], - "Accept" => "application/json", - ) - .public_send(method, "#{@plex_addr}#{endpoint}", **options) - - JSON.parse(response) + count = 0 + + # Keep trying request if it fails until number of retries have been exhausted + loop do + count += 1 + response = HTTP + .timeout(@plex_timeout) + .headers( + "X-Plex-Token" => @plex_token, + "Accept" => "application/json", + ) + .public_send(method, "#{@plex_addr}#{endpoint}", **options) + + return JSON.parse(response) + + rescue HTTP::Error => e + raise(e) unless @plex_retries_count <= count + end end # Set metric values and reset all other labels that werenn't passed in