@ar.io/sdk 3.11.0-alpha.9 → 3.11.0-beta.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.
Files changed (77) hide show
  1. package/bundles/web.bundle.min.js +106 -106
  2. package/lib/cjs/cli/utils.js +4 -1
  3. package/lib/cjs/common/contracts/ao-process.js +2 -1
  4. package/lib/cjs/common/wayfinder/{gateways.js → gateways/network.js} +3 -41
  5. package/lib/cjs/common/wayfinder/gateways/simple-cache.js +35 -0
  6. package/lib/cjs/common/wayfinder/gateways/static.js +13 -0
  7. package/lib/cjs/common/wayfinder/index.js +11 -8
  8. package/lib/cjs/common/wayfinder/routing/strategies/ping.js +72 -0
  9. package/lib/cjs/common/wayfinder/routing/strategies/ping.test.js +156 -0
  10. package/lib/cjs/common/wayfinder/routing/strategies/random.js +13 -0
  11. package/lib/cjs/common/wayfinder/routing/strategies/random.test.js +68 -0
  12. package/lib/cjs/common/wayfinder/routing/strategies/round-robin.js +42 -0
  13. package/lib/cjs/common/wayfinder/routing/strategies/round-robin.test.js +78 -0
  14. package/lib/cjs/common/wayfinder/routing/strategies/static.js +29 -0
  15. package/lib/cjs/common/wayfinder/routing/strategies/static.test.js +40 -0
  16. package/lib/cjs/common/wayfinder/verification/{data-root-verifier.js → strategies/data-root-verifier.js} +4 -4
  17. package/lib/cjs/common/wayfinder/verification/{hash-verifier.js → strategies/hash-verifier.js} +4 -4
  18. package/lib/cjs/common/wayfinder/{gateways/trusted-gateways.js → verification/trusted.js} +1 -1
  19. package/lib/cjs/common/wayfinder/wayfinder.js +397 -257
  20. package/lib/cjs/common/wayfinder/wayfinder.test.js +227 -208
  21. package/lib/cjs/version.js +1 -1
  22. package/lib/esm/cli/utils.js +4 -1
  23. package/lib/esm/common/contracts/ao-process.js +2 -1
  24. package/lib/esm/common/wayfinder/{gateways.js → gateways/network.js} +2 -38
  25. package/lib/esm/common/wayfinder/gateways/simple-cache.js +31 -0
  26. package/lib/esm/common/wayfinder/gateways/static.js +9 -0
  27. package/lib/esm/common/wayfinder/index.js +11 -8
  28. package/lib/esm/common/wayfinder/routing/strategies/ping.js +68 -0
  29. package/lib/esm/common/wayfinder/routing/strategies/ping.test.js +151 -0
  30. package/lib/esm/common/wayfinder/routing/strategies/random.js +9 -0
  31. package/lib/esm/common/wayfinder/routing/strategies/random.test.js +63 -0
  32. package/lib/esm/common/wayfinder/routing/strategies/round-robin.js +38 -0
  33. package/lib/esm/common/wayfinder/routing/strategies/round-robin.test.js +73 -0
  34. package/lib/esm/common/wayfinder/routing/strategies/static.js +25 -0
  35. package/lib/esm/common/wayfinder/routing/strategies/static.test.js +35 -0
  36. package/lib/esm/common/wayfinder/verification/{data-root-verifier.js → strategies/data-root-verifier.js} +2 -2
  37. package/lib/esm/common/wayfinder/verification/{hash-verifier.js → strategies/hash-verifier.js} +2 -2
  38. package/lib/esm/common/wayfinder/{gateways/trusted-gateways.js → verification/trusted.js} +1 -1
  39. package/lib/esm/common/wayfinder/wayfinder.js +395 -255
  40. package/lib/esm/common/wayfinder/wayfinder.test.js +227 -208
  41. package/lib/esm/version.js +1 -1
  42. package/lib/types/common/wayfinder/{gateways.d.ts → gateways/network.d.ts} +3 -23
  43. package/lib/types/common/wayfinder/{routers/random.d.ts → gateways/simple-cache.d.ts} +12 -8
  44. package/lib/types/common/wayfinder/{routers → gateways}/static.d.ts +6 -7
  45. package/lib/types/common/wayfinder/index.d.ts +10 -7
  46. package/lib/types/common/wayfinder/{routers/simple-cache.d.ts → routing/strategies/ping.d.ts} +10 -11
  47. package/lib/types/common/wayfinder/routing/strategies/random.d.ts +21 -0
  48. package/lib/types/common/wayfinder/routing/strategies/round-robin.d.ts +29 -0
  49. package/lib/types/common/wayfinder/routing/strategies/static.d.ts +29 -0
  50. package/lib/types/common/wayfinder/verification/{data-root-verifier.d.ts → strategies/data-root-verifier.d.ts} +2 -2
  51. package/lib/types/common/wayfinder/verification/{hash-verifier.d.ts → strategies/hash-verifier.d.ts} +2 -2
  52. package/lib/types/common/wayfinder/{gateways/trusted-gateways.d.ts → verification/trusted.d.ts} +1 -1
  53. package/lib/types/common/wayfinder/wayfinder.d.ts +111 -77
  54. package/lib/types/types/wayfinder.d.ts +8 -4
  55. package/lib/types/version.d.ts +1 -1
  56. package/package.json +1 -1
  57. package/lib/cjs/common/wayfinder/routers/priority.js +0 -29
  58. package/lib/cjs/common/wayfinder/routers/priority.test.js +0 -155
  59. package/lib/cjs/common/wayfinder/routers/random.js +0 -23
  60. package/lib/cjs/common/wayfinder/routers/random.test.js +0 -25
  61. package/lib/cjs/common/wayfinder/routers/simple-cache.js +0 -25
  62. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +0 -41
  63. package/lib/cjs/common/wayfinder/routers/static.js +0 -14
  64. package/lib/cjs/common/wayfinder/routers/static.test.js +0 -14
  65. package/lib/esm/common/wayfinder/routers/priority.js +0 -25
  66. package/lib/esm/common/wayfinder/routers/priority.test.js +0 -153
  67. package/lib/esm/common/wayfinder/routers/random.js +0 -19
  68. package/lib/esm/common/wayfinder/routers/random.test.js +0 -23
  69. package/lib/esm/common/wayfinder/routers/simple-cache.js +0 -21
  70. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +0 -39
  71. package/lib/esm/common/wayfinder/routers/static.js +0 -10
  72. package/lib/esm/common/wayfinder/routers/static.test.js +0 -12
  73. package/lib/types/common/wayfinder/routers/priority.d.ts +0 -29
  74. /package/lib/types/common/wayfinder/{routers/priority.test.d.ts → routing/strategies/ping.test.d.ts} +0 -0
  75. /package/lib/types/common/wayfinder/{routers → routing/strategies}/random.test.d.ts +0 -0
  76. /package/lib/types/common/wayfinder/{routers/simple-cache.test.d.ts → routing/strategies/round-robin.test.d.ts} +0 -0
  77. /package/lib/types/common/wayfinder/{routers → routing/strategies}/static.test.d.ts +0 -0
@@ -165,7 +165,10 @@ function aoProcessFromOptions(options) {
165
165
  function readARIOFromOptions(options) {
166
166
  setLoggerIfDebug(options);
167
167
  return index_js_1.ARIO.init({
168
- process: aoProcessFromOptions(options),
168
+ process: aoProcessFromOptions({
169
+ cuUrl: 'https://cu.ardrive.io', // default to ardrive cu for ARIO process
170
+ ...options,
171
+ }),
169
172
  paymentUrl: options.paymentUrl,
170
173
  });
171
174
  }
@@ -98,7 +98,8 @@ class AOProcess {
98
98
  tags,
99
99
  processId: this.processId,
100
100
  });
101
- throw new Error(`Process ${this.processId} does not support provided action.`);
101
+ throw new Error(result.message ||
102
+ `Process ${this.processId} did not return a valid response. Response: ${JSON.stringify(result)}`);
102
103
  }
103
104
  const messageData = result.Messages?.[0]?.Data;
104
105
  // return undefined if no data is returned
@@ -1,13 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SimpleCacheGatewaysProvider = exports.StaticGatewaysProvider = exports.NetworkGatewaysProvider = void 0;
3
+ exports.NetworkGatewaysProvider = void 0;
4
+ const io_js_1 = require("../../io.js");
4
5
  class NetworkGatewaysProvider {
5
6
  ario;
6
7
  sortBy;
7
8
  sortOrder;
8
9
  limit;
9
10
  filter;
10
- constructor({ ario, sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
11
+ constructor({ ario = io_js_1.ARIO.mainnet(), sortBy = 'operatorStake', sortOrder = 'desc', limit = 1000, filter = (g) => g.status === 'joined', }) {
11
12
  this.ario = ario;
12
13
  this.sortBy = sortBy;
13
14
  this.sortOrder = sortOrder;
@@ -45,42 +46,3 @@ class NetworkGatewaysProvider {
45
46
  }
46
47
  }
47
48
  exports.NetworkGatewaysProvider = NetworkGatewaysProvider;
48
- class StaticGatewaysProvider {
49
- gateways;
50
- constructor({ gateways }) {
51
- this.gateways = gateways.map((g) => new URL(g));
52
- }
53
- async getGateways() {
54
- return this.gateways;
55
- }
56
- }
57
- exports.StaticGatewaysProvider = StaticGatewaysProvider;
58
- class SimpleCacheGatewaysProvider {
59
- gatewaysProvider;
60
- ttlSeconds;
61
- lastUpdated;
62
- gatewaysCache;
63
- constructor({ gatewaysProvider, ttlSeconds = 5 * 60, // 5 minutes
64
- }) {
65
- this.gatewaysCache = [];
66
- this.gatewaysProvider = gatewaysProvider;
67
- this.ttlSeconds = ttlSeconds;
68
- }
69
- async getGateways() {
70
- const now = Date.now();
71
- if (this.gatewaysCache.length === 0 ||
72
- now - this.lastUpdated > this.ttlSeconds * 1000) {
73
- try {
74
- // preserve the cache if the fetch fails
75
- const allGateways = await this.gatewaysProvider.getGateways();
76
- this.gatewaysCache = allGateways;
77
- this.lastUpdated = now;
78
- }
79
- catch (error) {
80
- console.error('Error fetching gateways', error);
81
- }
82
- }
83
- return this.gatewaysCache;
84
- }
85
- }
86
- exports.SimpleCacheGatewaysProvider = SimpleCacheGatewaysProvider;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleCacheGatewaysProvider = void 0;
4
+ const index_js_1 = require("../../../web/index.js");
5
+ class SimpleCacheGatewaysProvider {
6
+ gatewaysProvider;
7
+ ttlSeconds;
8
+ lastUpdated;
9
+ gatewaysCache;
10
+ logger;
11
+ constructor({ gatewaysProvider, ttlSeconds = 60 * 60, // 1 hour
12
+ logger = index_js_1.Logger.default, }) {
13
+ this.gatewaysCache = [];
14
+ this.gatewaysProvider = gatewaysProvider;
15
+ this.ttlSeconds = ttlSeconds;
16
+ this.logger = logger;
17
+ }
18
+ async getGateways() {
19
+ const now = Date.now();
20
+ if (this.gatewaysCache.length === 0 ||
21
+ now - this.lastUpdated > this.ttlSeconds * 1000) {
22
+ try {
23
+ // preserve the cache if the fetch fails
24
+ const allGateways = await this.gatewaysProvider.getGateways();
25
+ this.gatewaysCache = allGateways;
26
+ this.lastUpdated = now;
27
+ }
28
+ catch (error) {
29
+ this.logger.error('Error fetching gateways', error);
30
+ }
31
+ }
32
+ return this.gatewaysCache;
33
+ }
34
+ }
35
+ exports.SimpleCacheGatewaysProvider = SimpleCacheGatewaysProvider;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StaticGatewaysProvider = void 0;
4
+ class StaticGatewaysProvider {
5
+ gateways;
6
+ constructor({ gateways }) {
7
+ this.gateways = gateways.map((g) => new URL(g));
8
+ }
9
+ async getGateways() {
10
+ return this.gateways;
11
+ }
12
+ }
13
+ exports.StaticGatewaysProvider = StaticGatewaysProvider;
@@ -30,15 +30,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
30
30
  * limitations under the License.
31
31
  */
32
32
  __exportStar(require("./wayfinder.js"), exports);
33
- // routers
34
- __exportStar(require("./routers/random.js"), exports);
35
- __exportStar(require("./routers/priority.js"), exports);
36
- __exportStar(require("./routers/static.js"), exports);
33
+ // routing strategies
34
+ __exportStar(require("./routing/strategies/random.js"), exports);
35
+ __exportStar(require("./routing/strategies/static.js"), exports);
36
+ __exportStar(require("./routing/strategies/ping.js"), exports);
37
+ __exportStar(require("./routing/strategies/round-robin.js"), exports);
37
38
  // gateways providers
38
- __exportStar(require("./gateways.js"), exports);
39
+ __exportStar(require("./gateways/network.js"), exports);
40
+ __exportStar(require("./gateways/simple-cache.js"), exports);
41
+ __exportStar(require("./gateways/static.js"), exports);
39
42
  // trusted gateways
40
- __exportStar(require("./gateways/trusted-gateways.js"), exports);
43
+ __exportStar(require("./verification/trusted.js"), exports);
41
44
  // hash providers
42
- __exportStar(require("./verification/data-root-verifier.js"), exports);
43
- __exportStar(require("./verification/hash-verifier.js"), exports);
45
+ __exportStar(require("./verification/strategies/data-root-verifier.js"), exports);
46
+ __exportStar(require("./verification/strategies/hash-verifier.js"), exports);
44
47
  // TODO: signature verification
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FastestPingRoutingStrategy = void 0;
4
+ class FastestPingRoutingStrategy {
5
+ timeoutMs;
6
+ probePath;
7
+ constructor({ timeoutMs = 500, probePath = '/ar-io/info', // TODO: limit to allowed /ar-io and arweave node endpoints
8
+ } = {}) {
9
+ this.timeoutMs = timeoutMs;
10
+ this.probePath = probePath;
11
+ }
12
+ async selectGateway({ gateways }) {
13
+ if (gateways.length === 0) {
14
+ throw new Error('No gateways provided');
15
+ }
16
+ try {
17
+ const results = await Promise.allSettled(gateways.map(async (gateway) => {
18
+ try {
19
+ const startTime = Date.now();
20
+ const response = await fetch(`${gateway.toString().replace(/\/$/, '')}${this.probePath}`, {
21
+ method: 'HEAD',
22
+ signal: AbortSignal.timeout(this.timeoutMs),
23
+ });
24
+ const endTime = Date.now();
25
+ const durationMs = endTime - startTime;
26
+ return {
27
+ gateway,
28
+ status: response.status,
29
+ durationMs,
30
+ error: null,
31
+ };
32
+ }
33
+ catch (error) {
34
+ // Handle network errors
35
+ return {
36
+ gateway,
37
+ status: 'rejected',
38
+ durationMs: Infinity,
39
+ error,
40
+ };
41
+ }
42
+ }));
43
+ // Process results
44
+ const processedResults = results.map((result, index) => {
45
+ if (result.status === 'fulfilled') {
46
+ return result.value;
47
+ }
48
+ else {
49
+ return {
50
+ gateway: gateways[index],
51
+ status: 'rejected',
52
+ durationMs: Infinity,
53
+ error: result.reason,
54
+ };
55
+ }
56
+ });
57
+ // Filter healthy gateways and sort by latency
58
+ const healthyGateways = processedResults
59
+ .filter((result) => result.status === 200)
60
+ .sort((a, b) => a.durationMs - b.durationMs);
61
+ if (healthyGateways.length > 0) {
62
+ return healthyGateways[0].gateway;
63
+ }
64
+ throw new Error('No healthy gateways found');
65
+ }
66
+ catch (error) {
67
+ throw new Error('Failed to ping gateways: ' +
68
+ (error instanceof Error ? error.message : String(error)));
69
+ }
70
+ }
71
+ }
72
+ exports.FastestPingRoutingStrategy = FastestPingRoutingStrategy;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const strict_1 = __importDefault(require("node:assert/strict"));
22
+ const node_test_1 = require("node:test");
23
+ const ping_js_1 = require("./ping.js");
24
+ (0, node_test_1.describe)('FastestPingRoutingStrategy', () => {
25
+ // Original fetch function
26
+ const originalFetch = global.fetch;
27
+ // Mock response options for each gateway
28
+ const mockResponses = new Map();
29
+ (0, node_test_1.beforeEach)(() => {
30
+ // reset mock responses
31
+ mockResponses.clear();
32
+ // mock fetch to simulate network latency and response status
33
+ global.fetch = async (url) => {
34
+ const urlString = url.toString();
35
+ // find the matching gateway
36
+ let matchingGateway = '';
37
+ for (const gateway of mockResponses.keys()) {
38
+ if (urlString.startsWith(gateway)) {
39
+ matchingGateway = gateway;
40
+ break;
41
+ }
42
+ }
43
+ if (!matchingGateway) {
44
+ return Promise.reject(new Error(`No mock response for URL: ${urlString}`));
45
+ }
46
+ const { status, delayMs } = mockResponses.get(matchingGateway);
47
+ // simulate network delay
48
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
49
+ return new Response(null, { status });
50
+ };
51
+ // mock AbortSignal.timeout
52
+ if (!AbortSignal.timeout) {
53
+ AbortSignal.timeout = (ms) => {
54
+ const controller = new AbortController();
55
+ setTimeout(() => controller.abort(), ms);
56
+ return controller.signal;
57
+ };
58
+ }
59
+ });
60
+ // restore original fetch after tests
61
+ (0, node_test_1.afterEach)(() => {
62
+ global.fetch = originalFetch;
63
+ });
64
+ (0, node_test_1.it)('selects the gateway with the lowest latency', async () => {
65
+ const gateways = [
66
+ new URL('https://slow.com'),
67
+ new URL('https://fast.com'),
68
+ new URL('https://medium.com'),
69
+ ];
70
+ // configure mock responses
71
+ mockResponses.set('https://slow.com', { status: 200, delayMs: 300 });
72
+ mockResponses.set('https://fast.com', { status: 200, delayMs: 50 });
73
+ mockResponses.set('https://medium.com', { status: 200, delayMs: 150 });
74
+ const strategy = new ping_js_1.FastestPingRoutingStrategy({ timeoutMs: 500 });
75
+ // select the gateway with the lowest latency
76
+ const selectedGateway = await strategy.selectGateway({
77
+ gateways,
78
+ });
79
+ strict_1.default.equal(selectedGateway.toString(), 'https://fast.com/', 'Should select the gateway with the lowest latency');
80
+ });
81
+ (0, node_test_1.it)('ignores gateways that return non-200 status codes', async () => {
82
+ const gateways = [
83
+ new URL('https://error.com'),
84
+ new URL('https://success.com'),
85
+ new URL('https://another-error.com'),
86
+ ];
87
+ // configure mock responses
88
+ mockResponses.set('https://error.com', { status: 404, delayMs: 50 });
89
+ mockResponses.set('https://success.com', { status: 200, delayMs: 100 });
90
+ mockResponses.set('https://another-error.com', {
91
+ status: 500,
92
+ delayMs: 75,
93
+ });
94
+ const strategy = new ping_js_1.FastestPingRoutingStrategy({ timeoutMs: 500 });
95
+ // select the gateway with the lowest latency
96
+ const selectedGateway = await strategy.selectGateway({
97
+ gateways,
98
+ });
99
+ strict_1.default.equal(selectedGateway.toString(), 'https://success.com/', 'Should select the gateway that returns a 200 status code');
100
+ });
101
+ (0, node_test_1.it)('throws an error when all gateways fail', async () => {
102
+ const gateways = [
103
+ new URL('https://error1.com'),
104
+ new URL('https://error2.com'),
105
+ ];
106
+ // configure mock responses
107
+ mockResponses.set('https://error1.com', { status: 404, delayMs: 50 });
108
+ mockResponses.set('https://error2.com', { status: 500, delayMs: 75 });
109
+ const strategy = new ping_js_1.FastestPingRoutingStrategy({ timeoutMs: 500 });
110
+ // select the gateway with the lowest latency
111
+ await strict_1.default.rejects(async () => await strategy.selectGateway({ gateways }), /No healthy gateways found/, 'Should throw an error when all gateways fail');
112
+ });
113
+ (0, node_test_1.it)('handles network errors gracefully', async () => {
114
+ const gateways = [
115
+ new URL('https://network-error.com'),
116
+ new URL('https://success.com'),
117
+ ];
118
+ // configure mock responses
119
+ mockResponses.set('https://success.com', { status: 200, delayMs: 100 });
120
+ // override fetch for the network error case
121
+ const originalFetchMock = global.fetch;
122
+ global.fetch = async (url) => {
123
+ if (url.toString().includes('network-error')) {
124
+ throw new Error('Network error');
125
+ }
126
+ return originalFetchMock(url);
127
+ };
128
+ const strategy = new ping_js_1.FastestPingRoutingStrategy({ timeoutMs: 500 });
129
+ // select the gateway with the lowest latency
130
+ const selectedGateway = await strategy.selectGateway({
131
+ gateways,
132
+ });
133
+ strict_1.default.equal(selectedGateway.toString(), 'https://success.com/', 'Should handle network errors and select the working gateway');
134
+ });
135
+ (0, node_test_1.it)('respects the timeout parameter', async () => {
136
+ const gateways = [
137
+ new URL('https://timeout.com'),
138
+ new URL('https://fast.com'),
139
+ ];
140
+ // configure mock responses
141
+ mockResponses.set('https://timeout.com', { status: 200, delayMs: 300 });
142
+ mockResponses.set('https://fast.com', { status: 200, delayMs: 50 });
143
+ // set a short timeout
144
+ const strategy = new ping_js_1.FastestPingRoutingStrategy({ timeoutMs: 100 });
145
+ const selectedGateway = await strategy.selectGateway({
146
+ gateways,
147
+ });
148
+ strict_1.default.equal(selectedGateway.toString(), 'https://fast.com/', 'Should respect the timeout and select only gateways that respond within the timeout');
149
+ });
150
+ (0, node_test_1.it)('throws an error when no gateways are provided', async () => {
151
+ const gateways = [];
152
+ const strategy = new ping_js_1.FastestPingRoutingStrategy();
153
+ // select the gateway with the lowest latency
154
+ await strict_1.default.rejects(async () => await strategy.selectGateway({ gateways }), /No gateways provided/, 'Should throw an error when no gateways are provided');
155
+ });
156
+ });
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RandomRoutingStrategy = void 0;
4
+ const random_js_1 = require("../../../../utils/random.js");
5
+ class RandomRoutingStrategy {
6
+ async selectGateway({ gateways }) {
7
+ if (gateways.length === 0) {
8
+ throw new Error('No gateways available');
9
+ }
10
+ return gateways[(0, random_js_1.randomInt)(0, gateways.length)];
11
+ }
12
+ }
13
+ exports.RandomRoutingStrategy = RandomRoutingStrategy;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const strict_1 = __importDefault(require("node:assert/strict"));
22
+ const node_test_1 = require("node:test");
23
+ const random_js_1 = require("./random.js");
24
+ (0, node_test_1.describe)('RandomRoutingStrategy', () => {
25
+ (0, node_test_1.it)('selects a gateway from the provided list', async () => {
26
+ // Arrange
27
+ const gateways = [
28
+ new URL('https://example1.com'),
29
+ new URL('https://example2.com'),
30
+ new URL('https://example3.com'),
31
+ ];
32
+ const strategy = new random_js_1.RandomRoutingStrategy();
33
+ const selectedGateway = await strategy.selectGateway({ gateways });
34
+ strict_1.default.ok(gateways.includes(selectedGateway), 'The selected gateway should be one of the gateways provided');
35
+ });
36
+ (0, node_test_1.it)('throws error when no gateways are provided', async () => {
37
+ const gateways = [];
38
+ const strategy = new random_js_1.RandomRoutingStrategy();
39
+ await strict_1.default.rejects(async () => await strategy.selectGateway({ gateways }), /No gateways available/, 'Should throw an error when no gateways are provided');
40
+ });
41
+ (0, node_test_1.it)('should distribute gateway selection somewhat randomly', async () => {
42
+ const gateways = [
43
+ new URL('https://example1.com'),
44
+ new URL('https://example2.com'),
45
+ new URL('https://example3.com'),
46
+ new URL('https://example4.com'),
47
+ new URL('https://example5.com'),
48
+ ];
49
+ const strategy = new random_js_1.RandomRoutingStrategy();
50
+ const selections = new Map();
51
+ // select gateways multiple times
52
+ const iterations = 100;
53
+ for (let i = 0; i < iterations; i++) {
54
+ const gateway = await strategy.selectGateway({ gateways });
55
+ const key = gateway.toString();
56
+ selections.set(key, (selections.get(key) || 0) + 1);
57
+ }
58
+ // each gateway should be selected at least once
59
+ for (const gateway of gateways) {
60
+ const key = gateway.toString();
61
+ strict_1.default.ok(selections.has(key), `Gateway ${key} should be selected at least once`);
62
+ }
63
+ // no gateway should be selected more than 50% of the time
64
+ for (const [key, count] of selections.entries()) {
65
+ strict_1.default.ok(count < iterations * 0.5, `Gateway ${key} was selected ${count} times, which is more than 50% of iterations`);
66
+ }
67
+ });
68
+ });
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RoundRobinRoutingStrategy = void 0;
4
+ /**
5
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ const logger_js_1 = require("../../../../common/logger.js");
20
+ class RoundRobinRoutingStrategy {
21
+ gateways;
22
+ currentIndex;
23
+ logger;
24
+ constructor({ gateways, logger = logger_js_1.Logger.default, }) {
25
+ this.gateways = gateways;
26
+ this.currentIndex = 0;
27
+ this.logger = logger;
28
+ }
29
+ // provided gateways are ignored
30
+ async selectGateway({ gateways = [], } = {}) {
31
+ if (gateways.length > 0) {
32
+ this.logger.warn('RoundRobinRoutingStrategy does not accept provided gateways. Ignoring provided gateways...', {
33
+ providedGateways: gateways.length,
34
+ internalGateways: this.gateways,
35
+ });
36
+ }
37
+ const gateway = this.gateways[this.currentIndex];
38
+ this.currentIndex = (this.currentIndex + 1) % this.gateways.length;
39
+ return gateway;
40
+ }
41
+ }
42
+ exports.RoundRobinRoutingStrategy = RoundRobinRoutingStrategy;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const strict_1 = __importDefault(require("node:assert/strict"));
22
+ const node_test_1 = require("node:test");
23
+ const logger_js_1 = require("../../../../common/logger.js");
24
+ const round_robin_js_1 = require("./round-robin.js");
25
+ logger_js_1.Logger.default.setLogLevel('none');
26
+ (0, node_test_1.describe)('RoundRobinRoutingStrategy', () => {
27
+ (0, node_test_1.it)('selects gateways in order and cycles back to the beginning', async () => {
28
+ const gateways = [
29
+ new URL('https://example1.com'),
30
+ new URL('https://example2.com'),
31
+ new URL('https://example3.com'),
32
+ ];
33
+ const strategy = new round_robin_js_1.RoundRobinRoutingStrategy({ gateways });
34
+ const selection1 = await strategy.selectGateway();
35
+ strict_1.default.equal(selection1.toString(), gateways[0].toString(), 'Should select the first gateway first');
36
+ const selection2 = await strategy.selectGateway();
37
+ strict_1.default.equal(selection2.toString(), gateways[1].toString(), 'Should select the second gateway second');
38
+ const selection3 = await strategy.selectGateway();
39
+ strict_1.default.equal(selection3.toString(), gateways[2].toString(), 'Should select the third gateway third');
40
+ // should cycle back to the first gateway
41
+ const selection4 = await strategy.selectGateway();
42
+ strict_1.default.equal(selection4.toString(), gateways[0].toString(), 'Should cycle back to the first gateway');
43
+ });
44
+ (0, node_test_1.it)('uses the internal list even when a different list is provided', async () => {
45
+ const initialGateways = [
46
+ new URL('https://example1.com'),
47
+ new URL('https://example2.com'),
48
+ ];
49
+ const newGateways = [
50
+ new URL('https://example3.com'),
51
+ new URL('https://example4.com'),
52
+ ];
53
+ const strategy = new round_robin_js_1.RoundRobinRoutingStrategy({
54
+ gateways: initialGateways,
55
+ });
56
+ const selection1 = await strategy.selectGateway({
57
+ gateways: newGateways,
58
+ });
59
+ strict_1.default.equal(selection1.toString(), initialGateways[0].toString(), 'Should use the internal list even when a different list is provided');
60
+ const selection2 = await strategy.selectGateway({
61
+ // @ts-ignore
62
+ gateways: newGateways,
63
+ });
64
+ strict_1.default.equal(selection2.toString(), initialGateways[1].toString(), 'Should use the internal list even when a different list is provided');
65
+ });
66
+ (0, node_test_1.it)('handles a single gateway by returning it repeatedly', async () => {
67
+ const gateways = [new URL('https://example1.com')];
68
+ const strategy = new round_robin_js_1.RoundRobinRoutingStrategy({ gateways });
69
+ const selection1 = await strategy.selectGateway({
70
+ gateways: [new URL('https://example2.com')],
71
+ });
72
+ strict_1.default.equal(selection1.toString(), gateways[0].toString(), 'Should return the single gateway');
73
+ const selection2 = await strategy.selectGateway({
74
+ gateways: [new URL('https://example2.com')],
75
+ });
76
+ strict_1.default.equal(selection2.toString(), gateways[0].toString(), 'Should return the single gateway again');
77
+ });
78
+ });
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StaticRoutingStrategy = void 0;
4
+ const logger_js_1 = require("../../../logger.js");
5
+ class StaticRoutingStrategy {
6
+ name = 'static';
7
+ gateway;
8
+ logger;
9
+ constructor({ gateway, logger = logger_js_1.Logger.default, }) {
10
+ try {
11
+ this.gateway = new URL(gateway);
12
+ }
13
+ catch (error) {
14
+ throw new Error(`Invalid URL provided for static gateway: ${gateway}`);
15
+ }
16
+ this.logger = logger;
17
+ }
18
+ // provided gateways are ignored
19
+ async selectGateway({ gateways = [], } = {}) {
20
+ if (gateways.length > 0) {
21
+ this.logger.warn('StaticRoutingStrategy does not accept provided gateways. Ignoring provided gateways...', {
22
+ providedGateways: gateways.length,
23
+ internalGateway: this.gateway,
24
+ });
25
+ }
26
+ return this.gateway;
27
+ }
28
+ }
29
+ exports.StaticRoutingStrategy = StaticRoutingStrategy;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ const strict_1 = __importDefault(require("node:assert/strict"));
22
+ const node_test_1 = require("node:test");
23
+ const static_js_1 = require("./static.js");
24
+ (0, node_test_1.describe)('StaticRoutingStrategy', () => {
25
+ (0, node_test_1.it)('returns the configured gateway regardless of the gateways parameter', async () => {
26
+ const staticGateway = 'https://static-example.com/';
27
+ const strategy = new static_js_1.StaticRoutingStrategy({
28
+ gateway: staticGateway,
29
+ });
30
+ const result1 = await strategy.selectGateway();
31
+ const result2 = await strategy.selectGateway();
32
+ const result3 = await strategy.selectGateway();
33
+ strict_1.default.equal(result1.toString(), staticGateway, 'Should return the static gateway');
34
+ strict_1.default.equal(result2.toString(), staticGateway, 'Should return the static gateway');
35
+ strict_1.default.equal(result3.toString(), staticGateway, 'Should return the static gateway even when no gateways are provided');
36
+ });
37
+ (0, node_test_1.it)('throws an error when an invalid URL is provided', () => {
38
+ strict_1.default.throws(() => new static_js_1.StaticRoutingStrategy({ gateway: 'not-a-valid-url' }), /Invalid URL provided for static gateway/, 'Should throw an error when an invalid URL is provided');
39
+ });
40
+ });