From a2b262b4ab7e4b58da9713246dd2130b93543aa9 Mon Sep 17 00:00:00 2001 From: mrjvs Date: Fri, 24 Nov 2023 22:16:01 +0100 Subject: [PATCH] get worker urls from settings instead of config --- src/backend/helpers/fetch.ts | 15 +++------------ src/utils/providers.ts | 23 ++++++++++++++++++----- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/backend/helpers/fetch.ts b/src/backend/helpers/fetch.ts index d798763f..fca9ab89 100644 --- a/src/backend/helpers/fetch.ts +++ b/src/backend/helpers/fetch.ts @@ -1,15 +1,6 @@ import { FetchOptions, FetchResponse, ofetch } from "ofetch"; -import { conf } from "@/setup/config"; - -let proxyUrlIndex = Math.floor(Math.random() * conf().PROXY_URLS.length); - -// round robins all proxy urls -function getProxyUrl(): string { - const url = conf().PROXY_URLS[proxyUrlIndex]; - proxyUrlIndex = (proxyUrlIndex + 1) % conf().PROXY_URLS.length; - return url; -} +import { getLoadbalancedProxyUrl } from "@/utils/providers"; type P = Parameters>; type R = ReturnType>; @@ -54,7 +45,7 @@ export function proxiedFetch(url: string, ops: P[1] = {}): R { parsedUrl.searchParams.set(k, v); }); - return baseFetch(getProxyUrl(), { + return baseFetch(getLoadbalancedProxyUrl(), { ...ops, baseURL: undefined, params: { @@ -88,7 +79,7 @@ export function rawProxiedFetch( parsedUrl.searchParams.set(k, v); }); - return baseFetch.raw(getProxyUrl(), { + return baseFetch.raw(getLoadbalancedProxyUrl(), { ...ops, baseURL: undefined, params: { diff --git a/src/utils/providers.ts b/src/utils/providers.ts index d276326b..07b91bff 100644 --- a/src/utils/providers.ts +++ b/src/utils/providers.ts @@ -8,15 +8,28 @@ import { } from "@movie-web/providers"; import { conf } from "@/setup/config"; +import { useAuthStore } from "@/stores/auth"; -const urls = conf().PROXY_URLS; -const fetchers = urls.map((v) => makeSimpleProxyFetcher(v, fetch)); -let fetchersIndex = Math.floor(Math.random() * fetchers.length); +const originalUrls = conf().PROXY_URLS; +let fetchersIndex = -1; + +export function getLoadbalancedProxyUrl() { + const fetchers = useAuthStore.getState().proxySet ?? originalUrls; + if (fetchersIndex === -1 || fetchersIndex >= fetchers.length) { + fetchersIndex = Math.floor(Math.random() * fetchers.length); + } + const proxyUrl = fetchers[fetchersIndex]; + fetchersIndex = (fetchersIndex + 1) % fetchers.length; + return proxyUrl; +} function makeLoadBalancedSimpleProxyFetcher() { const fetcher: ProviderBuilderOptions["fetcher"] = (a, b) => { - fetchersIndex += 1 % fetchers.length; - return fetchers[fetchersIndex](a, b); + const currentFetcher = makeSimpleProxyFetcher( + getLoadbalancedProxyUrl(), + fetch + ); + return currentFetcher(a, b); }; return fetcher; }