get worker urls from settings instead of config

This commit is contained in:
mrjvs 2023-11-24 22:16:01 +01:00
parent 1176908129
commit a2b262b4ab
2 changed files with 21 additions and 17 deletions

View File

@ -1,15 +1,6 @@
import { FetchOptions, FetchResponse, ofetch } from "ofetch"; import { FetchOptions, FetchResponse, ofetch } from "ofetch";
import { conf } from "@/setup/config"; import { getLoadbalancedProxyUrl } from "@/utils/providers";
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;
}
type P<T> = Parameters<typeof ofetch<T, any>>; type P<T> = Parameters<typeof ofetch<T, any>>;
type R<T> = ReturnType<typeof ofetch<T, any>>; type R<T> = ReturnType<typeof ofetch<T, any>>;
@ -54,7 +45,7 @@ export function proxiedFetch<T>(url: string, ops: P<T>[1] = {}): R<T> {
parsedUrl.searchParams.set(k, v); parsedUrl.searchParams.set(k, v);
}); });
return baseFetch<T>(getProxyUrl(), { return baseFetch<T>(getLoadbalancedProxyUrl(), {
...ops, ...ops,
baseURL: undefined, baseURL: undefined,
params: { params: {
@ -88,7 +79,7 @@ export function rawProxiedFetch<T>(
parsedUrl.searchParams.set(k, v); parsedUrl.searchParams.set(k, v);
}); });
return baseFetch.raw(getProxyUrl(), { return baseFetch.raw(getLoadbalancedProxyUrl(), {
...ops, ...ops,
baseURL: undefined, baseURL: undefined,
params: { params: {

View File

@ -8,15 +8,28 @@ import {
} from "@movie-web/providers"; } from "@movie-web/providers";
import { conf } from "@/setup/config"; import { conf } from "@/setup/config";
import { useAuthStore } from "@/stores/auth";
const urls = conf().PROXY_URLS; const originalUrls = conf().PROXY_URLS;
const fetchers = urls.map((v) => makeSimpleProxyFetcher(v, fetch)); let fetchersIndex = -1;
let fetchersIndex = Math.floor(Math.random() * fetchers.length);
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() { function makeLoadBalancedSimpleProxyFetcher() {
const fetcher: ProviderBuilderOptions["fetcher"] = (a, b) => { const fetcher: ProviderBuilderOptions["fetcher"] = (a, b) => {
fetchersIndex += 1 % fetchers.length; const currentFetcher = makeSimpleProxyFetcher(
return fetchers[fetchersIndex](a, b); getLoadbalancedProxyUrl(),
fetch
);
return currentFetcher(a, b);
}; };
return fetcher; return fetcher;
} }