@prosopo/load-balancer 2.8.17 → 2.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,81 @@
1
+ // Copyright 2021-2026 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { ProsopoEnvError } from "@prosopo/common";
15
+ import type { EnvironmentTypes } from "@prosopo/types";
16
+ import { z } from "zod";
17
+
18
+ const HardcodedProviderSchema = z.object({
19
+ address: z.string(),
20
+ url: z.string(),
21
+ datasetId: z.string(),
22
+ weight: z
23
+ .number()
24
+ .optional()
25
+ .default(1)
26
+ .transform((val) => {
27
+ // weight coerced to int 1-100
28
+ const weight = Math.round(val);
29
+ return Math.max(1, Math.min(100, weight));
30
+ }),
31
+ });
32
+
33
+ export type HardcodedProvider = z.infer<typeof HardcodedProviderSchema>;
34
+
35
+ type hostedProviders = Record<string, unknown>;
36
+
37
+ export const convertHostedProvider = (
38
+ provider: hostedProviders,
39
+ ): HardcodedProvider[] => {
40
+ const providers = Object.values(provider).map((p) =>
41
+ HardcodedProviderSchema.parse(p),
42
+ );
43
+ return providers.sort((a, b) => a.url.localeCompare(b.url));
44
+ };
45
+
46
+ export const getLoadBalancerUrl = (environment: EnvironmentTypes): string => {
47
+ if (environment === "production") {
48
+ return "https://provider-list.prosopo.io/";
49
+ }
50
+ if (environment === "staging") {
51
+ return "https://provider-list.prosopo.io/staging.json";
52
+ }
53
+ throw new ProsopoEnvError("CONFIG.UNKNOWN_ENVIRONMENT", {
54
+ context: { environment },
55
+ });
56
+ };
57
+
58
+ export const loadBalancer = async (
59
+ environment: EnvironmentTypes,
60
+ ): Promise<HardcodedProvider[]> => {
61
+ if (environment === "development") {
62
+ return [
63
+ {
64
+ address: "5EjTA28bKSbFPPyMbUjNtArxyqjwq38r1BapVmLZShaqEedV",
65
+ url: "https://localhost:9229",
66
+ datasetId:
67
+ "0x7984714b92d61fd92fd6a7bc9b56b729481470bcc771c19c382ec679acf02e67",
68
+ weight: 1,
69
+ },
70
+ ];
71
+ }
72
+
73
+ const providers: hostedProviders = await fetch(
74
+ getLoadBalancerUrl(environment),
75
+ {
76
+ method: "GET",
77
+ mode: "cors",
78
+ },
79
+ ).then((res) => res.json());
80
+ return convertHostedProvider(providers);
81
+ };
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ // Copyright 2021-2026 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ export * from "./providers.js";
15
+ export * from "./balancer.js";
@@ -0,0 +1,131 @@
1
+ // Copyright 2021-2026 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ import type { EnvironmentTypes, RandomProvider } from "@prosopo/types";
16
+ import { type HardcodedProvider, loadBalancer } from "./index.js";
17
+
18
+ // Keyed by env so a prefetch and a later call with a different env don't share.
19
+ const providerPromiseCache: Map<
20
+ EnvironmentTypes,
21
+ Promise<HardcodedProvider[]>
22
+ > = new Map();
23
+
24
+ /** Optional custom loader for server-side caching (e.g. cacheFile with ETag). */
25
+ let customProviderLoader:
26
+ | ((env: EnvironmentTypes) => Promise<HardcodedProvider[]>)
27
+ | null = null;
28
+
29
+ /**
30
+ * Set a custom provider loader that replaces the default HTTP fetch.
31
+ * Use this on the server side to inject cacheFile-based loading with
32
+ * ETag/Last-Modified support for disk persistence across restarts.
33
+ */
34
+ export function setProviderLoader(
35
+ loader: (env: EnvironmentTypes) => Promise<HardcodedProvider[]>,
36
+ ): void {
37
+ customProviderLoader = loader;
38
+ }
39
+
40
+ export function _resetCache() {
41
+ providerPromiseCache.clear();
42
+ }
43
+
44
+ /**
45
+ * Selects a weighted random provider using the entropy value.
46
+ * Providers with higher weights are more likely to be selected.
47
+ *
48
+ * @param providers - Array of providers with weights
49
+ * @param entropy - Random seed value for deterministic selection
50
+ * @returns Selected provider
51
+ */
52
+ export function selectWeightedProvider(
53
+ providers: HardcodedProvider[],
54
+ entropy: number,
55
+ ): HardcodedProvider {
56
+ if (providers.length === 0) {
57
+ throw new Error("No providers available");
58
+ }
59
+
60
+ const totalWeight = providers.reduce((sum, p) => sum + p.weight, 0);
61
+
62
+ // Use entropy to generate a value between 0 and totalWeight-1
63
+ const randomValue = entropy % totalWeight;
64
+
65
+ // Select provider based on cumulative weight
66
+ let cumulativeWeight = 0;
67
+ for (const provider of providers) {
68
+ cumulativeWeight += provider.weight;
69
+ if (randomValue < cumulativeWeight) {
70
+ return provider;
71
+ }
72
+ }
73
+
74
+ // Fallback (should never reach here)
75
+ const selectedProvider = providers[providers.length - 1];
76
+ if (!selectedProvider) {
77
+ throw new Error("No providers available");
78
+ }
79
+ return selectedProvider;
80
+ }
81
+
82
+ /** Load providers using the custom loader if set, otherwise the default fetch. */
83
+ const loadProviders = async (
84
+ env: EnvironmentTypes,
85
+ ): Promise<HardcodedProvider[]> => {
86
+ if (customProviderLoader) {
87
+ return customProviderLoader(env);
88
+ }
89
+ return loadBalancer(env);
90
+ };
91
+
92
+ // Caches the in-flight Promise (not the resolved array) so concurrent callers
93
+ // share a single network request rather than racing.
94
+ const getProvidersPromise = (
95
+ env: EnvironmentTypes,
96
+ ): Promise<HardcodedProvider[]> => {
97
+ const existing = providerPromiseCache.get(env);
98
+ if (existing) return existing;
99
+ const promise = loadProviders(env).catch((err) => {
100
+ providerPromiseCache.delete(env);
101
+ throw err;
102
+ });
103
+ providerPromiseCache.set(env, promise);
104
+ return promise;
105
+ };
106
+
107
+ /**
108
+ * Pre-warms the provider cache for a given environment without requiring entropy.
109
+ * Call this as early as possible to avoid a cold-cache delay when getRandomActiveProvider is first used.
110
+ */
111
+ export const prefetchProviders = async (
112
+ env: EnvironmentTypes,
113
+ ): Promise<void> => {
114
+ await getProvidersPromise(env);
115
+ };
116
+
117
+ export const getRandomActiveProvider = async (
118
+ env: EnvironmentTypes,
119
+ entropy: number,
120
+ ): Promise<RandomProvider> => {
121
+ const providers = await getProvidersPromise(env);
122
+ const randomProviderObj = selectWeightedProvider(providers, entropy);
123
+
124
+ return {
125
+ providerAccount: randomProviderObj.address,
126
+ provider: {
127
+ url: randomProviderObj.url,
128
+ datasetId: randomProviderObj.datasetId,
129
+ },
130
+ };
131
+ };
@@ -0,0 +1,320 @@
1
+ // Copyright 2021-2026 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ import { beforeEach, describe, expect, it, vi } from "vitest";
16
+ import { type HardcodedProvider, loadBalancer } from "../index.js";
17
+ import {
18
+ getRandomActiveProvider,
19
+ selectWeightedProvider,
20
+ } from "../providers.js";
21
+ import { _resetCache } from "../providers.js";
22
+
23
+ vi.mock("../index.js", () => ({
24
+ loadBalancer: vi.fn(),
25
+ }));
26
+
27
+ describe("selectWeightedProvider", () => {
28
+ it("selects provider based on weight distribution", () => {
29
+ const providers = [
30
+ {
31
+ address: "address1",
32
+ url: "url1",
33
+ datasetId: "dataset1",
34
+ weight: 1,
35
+ },
36
+ {
37
+ address: "address2",
38
+ url: "url2",
39
+ datasetId: "dataset2",
40
+ weight: 3,
41
+ },
42
+ {
43
+ address: "address3",
44
+ url: "url3",
45
+ datasetId: "dataset3",
46
+ weight: 1,
47
+ },
48
+ ];
49
+
50
+ // Total weight = 5
51
+ // Provider 1: weight 1 (covers entropy 0-0)
52
+ // Provider 2: weight 3 (covers entropy 1-3)
53
+ // Provider 3: weight 1 (covers entropy 4-4)
54
+
55
+ // Entropy 0 should select provider1
56
+ expect(selectWeightedProvider(providers, 0).address).toBe("address1");
57
+
58
+ // Entropy 1-3 should select provider2
59
+ expect(selectWeightedProvider(providers, 1).address).toBe("address2");
60
+ expect(selectWeightedProvider(providers, 2).address).toBe("address2");
61
+ expect(selectWeightedProvider(providers, 3).address).toBe("address2");
62
+
63
+ // Entropy 4 should select provider3
64
+ expect(selectWeightedProvider(providers, 4).address).toBe("address3");
65
+
66
+ // Entropy wraps around with modulo
67
+ expect(selectWeightedProvider(providers, 5).address).toBe("address1");
68
+ expect(selectWeightedProvider(providers, 6).address).toBe("address2");
69
+ });
70
+
71
+ it("handles equal weights correctly", () => {
72
+ const providers = [
73
+ {
74
+ address: "address1",
75
+ url: "url1",
76
+ datasetId: "dataset1",
77
+ weight: 1,
78
+ },
79
+ {
80
+ address: "address2",
81
+ url: "url2",
82
+ datasetId: "dataset2",
83
+ weight: 1,
84
+ },
85
+ ];
86
+
87
+ // Total weight = 2
88
+ expect(selectWeightedProvider(providers, 0).address).toBe("address1");
89
+ expect(selectWeightedProvider(providers, 1).address).toBe("address2");
90
+ expect(selectWeightedProvider(providers, 2).address).toBe("address1");
91
+ expect(selectWeightedProvider(providers, 3).address).toBe("address2");
92
+ });
93
+
94
+ it("handles single provider", () => {
95
+ const providers = [
96
+ {
97
+ address: "address1",
98
+ url: "url1",
99
+ datasetId: "dataset1",
100
+ weight: 10,
101
+ },
102
+ ];
103
+
104
+ // All entropy values should select the only provider
105
+ expect(selectWeightedProvider(providers, 0).address).toBe("address1");
106
+ expect(selectWeightedProvider(providers, 5).address).toBe("address1");
107
+ expect(selectWeightedProvider(providers, 100).address).toBe("address1");
108
+ });
109
+
110
+ it("throws error for empty provider list", () => {
111
+ expect(() => selectWeightedProvider([], 0)).toThrow(
112
+ "No providers available",
113
+ );
114
+ });
115
+
116
+ it("heavily weighted provider is selected more often", () => {
117
+ const providers = [
118
+ {
119
+ address: "address1",
120
+ url: "url1",
121
+ datasetId: "dataset1",
122
+ weight: 1,
123
+ },
124
+ {
125
+ address: "address2",
126
+ url: "url2",
127
+ datasetId: "dataset2",
128
+ weight: 99,
129
+ },
130
+ ];
131
+
132
+ // Total weight = 100
133
+ // Provider 1: entropy 0 (1% of the time)
134
+ // Provider 2: entropy 1-99 (99% of the time)
135
+
136
+ const selections = { address1: 0, address2: 0 };
137
+ for (let i = 0; i < 100; i++) {
138
+ const selected = selectWeightedProvider(providers, i);
139
+ if (selected.address === "address1") {
140
+ selections.address1++;
141
+ } else {
142
+ selections.address2++;
143
+ }
144
+ }
145
+
146
+ expect(selections.address1).toBe(1);
147
+ expect(selections.address2).toBe(99);
148
+ });
149
+
150
+ it("handles maximum weight value (100)", () => {
151
+ const providers = [
152
+ {
153
+ address: "address1",
154
+ url: "url1",
155
+ datasetId: "dataset1",
156
+ weight: 100,
157
+ },
158
+ {
159
+ address: "address2",
160
+ url: "url2",
161
+ datasetId: "dataset2",
162
+ weight: 100,
163
+ },
164
+ ];
165
+
166
+ // Total weight = 200
167
+ const selections = { address1: 0, address2: 0 };
168
+ for (let i = 0; i < 200; i++) {
169
+ const selected = selectWeightedProvider(providers, i);
170
+ if (selected.address === "address1") {
171
+ selections.address1++;
172
+ } else {
173
+ selections.address2++;
174
+ }
175
+ }
176
+
177
+ // Each should get selected 100 times (50%)
178
+ expect(selections.address1).toBe(100);
179
+ expect(selections.address2).toBe(100);
180
+ });
181
+
182
+ it("correctly handles providers without values for weight", () => {
183
+ // Providers without weight field should default to weight 1
184
+ const providers = [
185
+ {
186
+ address: "address1",
187
+ url: "url1",
188
+ datasetId: "dataset1",
189
+ // No weight field
190
+ },
191
+ {
192
+ address: "address2",
193
+ url: "url2",
194
+ datasetId: "dataset2",
195
+ weight: 3,
196
+ },
197
+ ];
198
+
199
+ // Mock the providers to simulate what comes from the API
200
+ // The real providers will have weight added by zod schema default
201
+ const providersWithDefaults = [
202
+ { ...providers[0], weight: 1 },
203
+ providers[1],
204
+ ];
205
+
206
+ // Total weight = 4 (1 + 3)
207
+ // address1 (weight 1) should get entropy 0 (25%)
208
+ // address2 (weight 3) should get entropy 1-3 (75%)
209
+
210
+ const selections = { address1: 0, address2: 0 };
211
+ for (let i = 0; i < 100; i++) {
212
+ const selected = selectWeightedProvider(
213
+ providersWithDefaults as HardcodedProvider[],
214
+ i,
215
+ );
216
+ if (selected.address === "address1") {
217
+ selections.address1++;
218
+ } else {
219
+ selections.address2++;
220
+ }
221
+ }
222
+
223
+ // address1 should get ~25% and address2 should get ~75%
224
+ expect(selections.address1).toBe(25);
225
+ expect(selections.address2).toBe(75);
226
+ });
227
+ });
228
+
229
+ describe("getRandomActiveProvider", () => {
230
+ beforeEach(() => {
231
+ _resetCache();
232
+ vi.clearAllMocks();
233
+ vi.resetAllMocks();
234
+ vi.resetModules();
235
+ });
236
+
237
+ it("returns a random provider when providers list is populated", async () => {
238
+ const mockProviders = [
239
+ { address: "address1", url: "url1", datasetId: "dataset1", weight: 1 },
240
+ { address: "address2", url: "url2", datasetId: "dataset2", weight: 1 },
241
+ ];
242
+ (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(
243
+ mockProviders,
244
+ );
245
+
246
+ const result = await getRandomActiveProvider("development", 1);
247
+
248
+ expect(result.providerAccount).toBe("address2");
249
+ expect(result.provider.url).toBe("url2");
250
+ expect(result.provider.datasetId).toBe("dataset2");
251
+ });
252
+
253
+ it("loads providers only once when called multiple times", async () => {
254
+ const mockProviders = [
255
+ { address: "address1", url: "url1", datasetId: "dataset1", weight: 1 },
256
+ ];
257
+ (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(
258
+ mockProviders,
259
+ );
260
+
261
+ await getRandomActiveProvider("development", 123);
262
+ await getRandomActiveProvider("development", 456);
263
+
264
+ expect(loadBalancer).toHaveBeenCalledTimes(1);
265
+ });
266
+
267
+ it("handles empty providers list gracefully", async () => {
268
+ (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue([]);
269
+
270
+ await expect(getRandomActiveProvider("development", 123)).rejects.toThrow();
271
+ });
272
+
273
+ it("respects provider weights when selecting", async () => {
274
+ const mockProviders = [
275
+ { address: "address1", url: "url1", datasetId: "dataset1", weight: 1 },
276
+ { address: "address2", url: "url2", datasetId: "dataset2", weight: 3 },
277
+ ];
278
+ (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(
279
+ mockProviders,
280
+ );
281
+
282
+ // Total weight = 4
283
+ // address1 gets entropy 0 (25%)
284
+ // address2 gets entropy 1-3 (75%)
285
+
286
+ const result0 = await getRandomActiveProvider("development", 0);
287
+ expect(result0.providerAccount).toBe("address1");
288
+
289
+ _resetCache();
290
+ const result1 = await getRandomActiveProvider("development", 1);
291
+ expect(result1.providerAccount).toBe("address2");
292
+
293
+ _resetCache();
294
+ const result2 = await getRandomActiveProvider("development", 2);
295
+ expect(result2.providerAccount).toBe("address2");
296
+
297
+ _resetCache();
298
+ const result3 = await getRandomActiveProvider("development", 3);
299
+ expect(result3.providerAccount).toBe("address2");
300
+ });
301
+
302
+ it("handles providers with missing weight field (defaults to 1)", async () => {
303
+ // Simulate providers returned from loadBalancer where one has weight and one doesn't
304
+ const mockProviders = [
305
+ { address: "address1", url: "url1", datasetId: "dataset1", weight: 1 },
306
+ { address: "address2", url: "url2", datasetId: "dataset2", weight: 1 },
307
+ ];
308
+ (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(
309
+ mockProviders,
310
+ );
311
+
312
+ // With equal weights, distribution should be 50/50
313
+ const result0 = await getRandomActiveProvider("development", 0);
314
+ expect(result0.providerAccount).toBe("address1");
315
+
316
+ _resetCache();
317
+ const result1 = await getRandomActiveProvider("development", 1);
318
+ expect(result1.providerAccount).toBe("address2");
319
+ });
320
+ });
@@ -0,0 +1,24 @@
1
+ {
2
+ "extends": "../../tsconfig.cjs.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist/cjs"
6
+ },
7
+ "include": [
8
+ "./src/**/*.ts",
9
+ "./src/**/*.json",
10
+ "./src/**/*.d.ts",
11
+ "./src/**/*.tsx"
12
+ ],
13
+ "references": [
14
+ {
15
+ "path": "../../dev/config/tsconfig.cjs.json"
16
+ },
17
+ {
18
+ "path": "../common/tsconfig.cjs.json"
19
+ },
20
+ {
21
+ "path": "../types/tsconfig.cjs.json"
22
+ }
23
+ ]
24
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "extends": "../../tsconfig.esm.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist"
6
+ },
7
+ "include": [
8
+ "src",
9
+ "src/**/*.json",
10
+ "src/**/*.ts",
11
+ "src/**/*.tsx",
12
+ "src/**/*.d.ts"
13
+ ],
14
+ "references": [
15
+ {
16
+ "path": "../../dev/config/tsconfig.json"
17
+ },
18
+ {
19
+ "path": "../common"
20
+ },
21
+ {
22
+ "path": "../types"
23
+ }
24
+ ]
25
+ }