@prosopo/load-balancer 2.9.21 → 2.10.1

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.
@@ -12,309 +12,178 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
 
15
- import { beforeEach, describe, expect, it, vi } from "vitest";
16
- import { type HardcodedProvider, loadBalancer } from "../index.js";
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
17
16
  import {
17
+ _resetPinCache,
18
+ _resetProviderListCache,
19
+ getProviders,
18
20
  getRandomActiveProvider,
19
- selectWeightedProvider,
20
21
  } from "../providers.js";
21
- import { _resetCache } from "../providers.js";
22
22
 
23
- vi.mock("../index.js", () => ({
24
- loadBalancer: vi.fn(),
23
+ // Mock the underlying load balancer so getProviders' caching/failure semantics
24
+ // can be exercised without real network calls. getRandomActiveProvider tests
25
+ // don't use loadBalancer, so this mock leaves them unaffected.
26
+ const loadBalancer = vi.fn();
27
+ vi.mock("../balancer.js", () => ({
28
+ loadBalancer: (...args: unknown[]) => loadBalancer(...args),
25
29
  }));
26
30
 
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");
31
+ const originalFetch = globalThis.fetch;
32
+
33
+ const mockHealthzFetch = (host: string, ok = true, status = 200) => {
34
+ const mocked = vi.fn(async () => ({
35
+ ok,
36
+ status,
37
+ json: async () => ({ ok: true, host }),
38
+ }));
39
+ // biome-ignore lint/suspicious/noExplicitAny: minimal Response stub for the unit test
40
+ globalThis.fetch = mocked as any;
41
+ return mocked;
42
+ };
43
+
44
+ beforeEach(() => {
45
+ _resetPinCache();
46
+ });
57
47
 
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");
48
+ afterEach(() => {
49
+ globalThis.fetch = originalFetch;
50
+ });
62
51
 
63
- // Entropy 4 should select provider3
64
- expect(selectWeightedProvider(providers, 4).address).toBe("address3");
52
+ describe("getRandomActiveProvider (dual stack)", () => {
53
+ it("uses the local URL directly in development (no healthz round-trip)", async () => {
54
+ const mocked = mockHealthzFetch("ignored");
55
+ const result = await getRandomActiveProvider("development");
56
+ expect(result.provider.url).toBe("https://localhost:9229");
57
+ expect(mocked).not.toHaveBeenCalled();
58
+ });
65
59
 
66
- // Entropy wraps around with modulo
67
- expect(selectWeightedProvider(providers, 5).address).toBe("address1");
68
- expect(selectWeightedProvider(providers, 6).address).toBe("address2");
60
+ it("pins to the host returned by /healthz in production", async () => {
61
+ mockHealthzFetch("pronode7.prosopo.io");
62
+ const result = await getRandomActiveProvider("production");
63
+ expect(result.provider.url).toBe("https://pronode7.prosopo.io");
69
64
  });
70
65
 
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
- ];
66
+ it("pins to the host returned by /healthz in staging", async () => {
67
+ mockHealthzFetch("staging-pronode2.prosopo.io");
68
+ const result = await getRandomActiveProvider("staging");
69
+ expect(result.provider.url).toBe("https://staging-pronode2.prosopo.io");
70
+ });
86
71
 
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");
72
+ it("caches the pinned URL for repeat callers in the same env + ipMode", async () => {
73
+ const mocked = mockHealthzFetch("pronode3.prosopo.io");
74
+ await getRandomActiveProvider("production");
75
+ await getRandomActiveProvider("production");
76
+ await getRandomActiveProvider("production");
77
+ expect(mocked).toHaveBeenCalledTimes(1);
92
78
  });
93
79
 
94
- it("handles single provider", () => {
95
- const providers = [
96
- {
97
- address: "address1",
98
- url: "url1",
99
- datasetId: "dataset1",
100
- weight: 10,
101
- },
102
- ];
80
+ it("falls back to the dual-stack base URL when /healthz responds non-OK", async () => {
81
+ mockHealthzFetch("ignored", false, 503);
82
+ const result = await getRandomActiveProvider("production");
83
+ expect(result.provider.url).toBe("https://pronode.prosopo.io");
84
+ });
103
85
 
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");
86
+ it("falls back to the dual-stack base URL when /healthz body is malformed", async () => {
87
+ const mocked = vi.fn(async () => ({
88
+ ok: true,
89
+ status: 200,
90
+ json: async () => ({ ok: true }),
91
+ }));
92
+ // biome-ignore lint/suspicious/noExplicitAny: minimal Response stub for the unit test
93
+ globalThis.fetch = mocked as any;
94
+ const result = await getRandomActiveProvider("production");
95
+ expect(result.provider.url).toBe("https://pronode.prosopo.io");
108
96
  });
97
+ });
109
98
 
110
- it("throws error for empty provider list", () => {
111
- expect(() => selectWeightedProvider([], 0)).toThrow(
112
- "No providers available",
99
+ describe("getRandomActiveProvider (single stack ipMode)", () => {
100
+ it("hits ipv4.pronode.prosopo.io/healthz and pins to ipv4.pronodeN", async () => {
101
+ const mocked = mockHealthzFetch("pronode4.prosopo.io");
102
+ const result = await getRandomActiveProvider("production", "ipv4");
103
+ expect(result.provider.url).toBe("https://ipv4.pronode4.prosopo.io");
104
+ expect(mocked).toHaveBeenCalledWith(
105
+ "https://ipv4.pronode.prosopo.io/healthz",
106
+ expect.any(Object),
113
107
  );
114
108
  });
115
109
 
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);
110
+ it("hits ipv6 staging /healthz and pins to ipv6.staging-pronodeN", async () => {
111
+ const mocked = mockHealthzFetch("staging-pronode2.prosopo.io");
112
+ const result = await getRandomActiveProvider("staging", "ipv6");
113
+ expect(result.provider.url).toBe(
114
+ "https://ipv6.staging-pronode2.prosopo.io",
115
+ );
116
+ expect(mocked).toHaveBeenCalledWith(
117
+ "https://ipv6.staging.pronode.prosopo.io/healthz",
118
+ expect.any(Object),
119
+ );
148
120
  });
149
121
 
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);
122
+ it("falls back to the ipv4-labelled global URL when ipv4 /healthz fails", async () => {
123
+ mockHealthzFetch("ignored", false, 500);
124
+ const result = await getRandomActiveProvider("production", "ipv4");
125
+ expect(result.provider.url).toBe("https://ipv4.pronode.prosopo.io");
180
126
  });
181
127
 
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);
128
+ it("keeps the dual-stack cache and the ipv4 cache separate", async () => {
129
+ const mocked = mockHealthzFetch("pronode9.prosopo.io");
130
+ await getRandomActiveProvider("production");
131
+ await getRandomActiveProvider("production", "ipv4");
132
+ await getRandomActiveProvider("production");
133
+ await getRandomActiveProvider("production", "ipv4");
134
+ // One healthz per (env, ipMode) combination.
135
+ expect(mocked).toHaveBeenCalledTimes(2);
226
136
  });
227
137
  });
228
138
 
229
- describe("getRandomActiveProvider", () => {
139
+ describe("getProviders", () => {
230
140
  beforeEach(() => {
231
- _resetCache();
232
- vi.clearAllMocks();
233
- vi.resetAllMocks();
234
- vi.resetModules();
141
+ _resetProviderListCache();
142
+ loadBalancer.mockReset();
235
143
  });
236
144
 
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 },
145
+ it("loads the provider list once and serves repeat callers from cache", async () => {
146
+ const providers = [
147
+ { address: "5xyz", url: "https://p1", datasetId: "0x0" },
256
148
  ];
257
- (loadBalancer as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(
258
- mockProviders,
259
- );
149
+ loadBalancer.mockResolvedValue(providers);
260
150
 
261
- await getRandomActiveProvider("development", 123);
262
- await getRandomActiveProvider("development", 456);
151
+ const first = await getProviders("production");
152
+ const second = await getProviders("production");
263
153
 
154
+ expect(first).toBe(providers);
155
+ expect(second).toBe(providers);
264
156
  expect(loadBalancer).toHaveBeenCalledTimes(1);
265
157
  });
266
158
 
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 },
159
+ it("dedupes concurrent in-flight loads into a single call", async () => {
160
+ const providers = [
161
+ { address: "5xyz", url: "https://p1", datasetId: "0x0" },
277
162
  ];
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");
163
+ loadBalancer.mockResolvedValue(providers);
288
164
 
289
- _resetCache();
290
- const result1 = await getRandomActiveProvider("development", 1);
291
- expect(result1.providerAccount).toBe("address2");
165
+ const [a, b] = await Promise.all([
166
+ getProviders("production"),
167
+ getProviders("production"),
168
+ ]);
292
169
 
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");
170
+ expect(a).toBe(providers);
171
+ expect(b).toBe(providers);
172
+ expect(loadBalancer).toHaveBeenCalledTimes(1);
300
173
  });
301
174
 
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 },
175
+ it("does not cache failures a rejected load is retried on the next call", async () => {
176
+ const providers = [
177
+ { address: "5xyz", url: "https://p1", datasetId: "0x0" },
307
178
  ];
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");
179
+ loadBalancer
180
+ .mockRejectedValueOnce(new Error("transient"))
181
+ .mockResolvedValueOnce(providers);
182
+
183
+ await expect(getProviders("production")).rejects.toThrow("transient");
184
+ // The failure must have cleared the cache, so the next call retries.
185
+ const retry = await getProviders("production");
186
+ expect(retry).toBe(providers);
187
+ expect(loadBalancer).toHaveBeenCalledTimes(2);
319
188
  });
320
189
  });