feat: do all the backend balancing on the invidious side

This will make invidious easier to maintain and escalate without the need of an overcomplicated reverse proxy configuration and multiple invidious instances with each one with a different configuration (in this case, invidious companion)
This commit is contained in:
Fijxu
2025-03-30 20:08:15 -03:00
parent ddf6802d76
commit d47aa3dd6a
13 changed files with 341 additions and 265 deletions

View File

@@ -63,7 +63,7 @@ struct CompanionConnectionPool
end
end
def client(&)
def client(env : HTTP::Server::Context | Nil, &)
conn = pool.checkout
begin
@@ -71,7 +71,13 @@ struct CompanionConnectionPool
rescue ex
conn.close
companion = CONFIG.invidious_companion.sample
if env.nil?
companion = CONFIG.invidious_companion.sample
else
current_companion = env.get("current_companion").as(Int32)
companion = CONFIG.invidious_companion[current_companion]
end
conn = make_client(companion.private_url, use_http_proxy: false)
response = yield conn

View File

@@ -456,6 +456,7 @@ module YoutubeAPI
*, # Force the following parameters to be passed by name
params : String,
client_config : ClientConfig | Nil = nil,
env : HTTP::Server::Context | Nil = nil,
)
# Playback context, separate because it can be different between clients
playback_ctx = {
@@ -492,7 +493,7 @@ module YoutubeAPI
end
if CONFIG.invidious_companion.present?
return self._post_invidious_companion("/youtubei/v1/player", data)
return self._post_invidious_companion("/youtubei/v1/player", data, env)
else
return self._post_json("/youtubei/v1/player", data, client_config)
end
@@ -673,6 +674,7 @@ module YoutubeAPI
def _post_invidious_companion(
endpoint : String,
data : Hash,
env : HTTP::Server::Context | Nil,
) : Hash(String, JSON::Any)
headers = HTTP::Headers{
"Content-Type" => "application/json; charset=UTF-8",
@@ -686,7 +688,7 @@ module YoutubeAPI
# Send the POST request
begin
response = COMPANION_POOL.client &.post(endpoint, headers: headers, body: data.to_json)
response = COMPANION_POOL.client(env, &.post(endpoint, headers: headers, body: data.to_json))
body = response.body
if (response.status_code != 200)
raise Exception.new(