@wopr-network/platform-core 1.18.0 → 1.20.0

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 (68) hide show
  1. package/dist/api/routes/admin-audit-helper.d.ts +1 -1
  2. package/dist/billing/crypto/btc/__tests__/address-gen.test.d.ts +1 -0
  3. package/dist/billing/crypto/btc/__tests__/address-gen.test.js +44 -0
  4. package/dist/billing/crypto/btc/__tests__/config.test.d.ts +1 -0
  5. package/dist/billing/crypto/btc/__tests__/config.test.js +24 -0
  6. package/dist/billing/crypto/btc/__tests__/settler.test.d.ts +1 -0
  7. package/dist/billing/crypto/btc/__tests__/settler.test.js +92 -0
  8. package/dist/billing/crypto/btc/address-gen.d.ts +8 -0
  9. package/dist/billing/crypto/btc/address-gen.js +34 -0
  10. package/dist/billing/crypto/btc/checkout.d.ts +21 -0
  11. package/dist/billing/crypto/btc/checkout.js +42 -0
  12. package/dist/billing/crypto/btc/config.d.ts +12 -0
  13. package/dist/billing/crypto/btc/config.js +28 -0
  14. package/dist/billing/crypto/btc/index.d.ts +9 -0
  15. package/dist/billing/crypto/btc/index.js +5 -0
  16. package/dist/billing/crypto/btc/settler.d.ts +23 -0
  17. package/dist/billing/crypto/btc/settler.js +55 -0
  18. package/dist/billing/crypto/btc/types.d.ts +23 -0
  19. package/dist/billing/crypto/btc/types.js +1 -0
  20. package/dist/billing/crypto/btc/watcher.d.ts +28 -0
  21. package/dist/billing/crypto/btc/watcher.js +83 -0
  22. package/dist/billing/crypto/charge-store.d.ts +3 -3
  23. package/dist/billing/crypto/evm/__tests__/config.test.js +42 -2
  24. package/dist/billing/crypto/evm/__tests__/watcher.test.js +31 -17
  25. package/dist/billing/crypto/evm/checkout.js +4 -2
  26. package/dist/billing/crypto/evm/config.js +73 -0
  27. package/dist/billing/crypto/evm/types.d.ts +1 -1
  28. package/dist/billing/crypto/evm/watcher.js +2 -0
  29. package/dist/billing/crypto/index.d.ts +2 -1
  30. package/dist/billing/crypto/index.js +1 -0
  31. package/dist/db/schema/crypto.js +1 -1
  32. package/dist/fleet/__tests__/rollout-strategy.test.d.ts +1 -0
  33. package/dist/fleet/__tests__/rollout-strategy.test.js +157 -0
  34. package/dist/fleet/__tests__/volume-snapshot-manager.test.d.ts +1 -0
  35. package/dist/fleet/__tests__/volume-snapshot-manager.test.js +171 -0
  36. package/dist/fleet/index.d.ts +2 -0
  37. package/dist/fleet/index.js +2 -0
  38. package/dist/fleet/rollout-strategy.d.ts +52 -0
  39. package/dist/fleet/rollout-strategy.js +91 -0
  40. package/dist/fleet/volume-snapshot-manager.d.ts +35 -0
  41. package/dist/fleet/volume-snapshot-manager.js +185 -0
  42. package/package.json +3 -1
  43. package/src/api/routes/admin-audit-helper.ts +1 -1
  44. package/src/billing/crypto/btc/__tests__/address-gen.test.ts +53 -0
  45. package/src/billing/crypto/btc/__tests__/config.test.ts +28 -0
  46. package/src/billing/crypto/btc/__tests__/settler.test.ts +103 -0
  47. package/src/billing/crypto/btc/address-gen.ts +41 -0
  48. package/src/billing/crypto/btc/checkout.ts +61 -0
  49. package/src/billing/crypto/btc/config.ts +33 -0
  50. package/src/billing/crypto/btc/index.ts +9 -0
  51. package/src/billing/crypto/btc/settler.ts +74 -0
  52. package/src/billing/crypto/btc/types.ts +25 -0
  53. package/src/billing/crypto/btc/watcher.ts +115 -0
  54. package/src/billing/crypto/charge-store.ts +3 -3
  55. package/src/billing/crypto/evm/__tests__/config.test.ts +51 -2
  56. package/src/billing/crypto/evm/__tests__/watcher.test.ts +34 -17
  57. package/src/billing/crypto/evm/checkout.ts +4 -2
  58. package/src/billing/crypto/evm/config.ts +73 -0
  59. package/src/billing/crypto/evm/types.ts +1 -1
  60. package/src/billing/crypto/evm/watcher.ts +2 -0
  61. package/src/billing/crypto/index.ts +2 -1
  62. package/src/db/schema/crypto.ts +1 -1
  63. package/src/fleet/__tests__/rollout-strategy.test.ts +192 -0
  64. package/src/fleet/__tests__/volume-snapshot-manager.test.ts +218 -0
  65. package/src/fleet/index.ts +2 -0
  66. package/src/fleet/rollout-strategy.ts +128 -0
  67. package/src/fleet/volume-snapshot-manager.ts +213 -0
  68. package/src/marketplace/volume-installer.test.ts +8 -2
@@ -0,0 +1,192 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ createRolloutStrategy,
5
+ ImmediateStrategy,
6
+ RollingWaveStrategy,
7
+ SingleBotStrategy,
8
+ } from "../rollout-strategy.js";
9
+ import type { BotProfile } from "../types.js";
10
+
11
+ function makeBots(count: number): BotProfile[] {
12
+ return Array.from({ length: count }, (_, i) => ({
13
+ id: randomUUID(),
14
+ tenantId: "tenant-1",
15
+ name: `bot-${i}`,
16
+ description: "",
17
+ image: "ghcr.io/wopr-network/test:latest",
18
+ env: {},
19
+ restartPolicy: "unless-stopped" as const,
20
+ releaseChannel: "stable" as const,
21
+ updatePolicy: "manual" as const,
22
+ }));
23
+ }
24
+
25
+ describe("RollingWaveStrategy", () => {
26
+ it("returns batchPercent of remaining bots", () => {
27
+ const s = new RollingWaveStrategy({ batchPercent: 25 });
28
+ const bots = makeBots(10);
29
+ const batch = s.nextBatch(bots);
30
+ // 25% of 10 = 2.5, ceil = 3
31
+ expect(batch).toHaveLength(3);
32
+ expect(batch).toEqual(bots.slice(0, 3));
33
+ });
34
+
35
+ it("returns minimum 1 bot even with low percentage", () => {
36
+ const s = new RollingWaveStrategy({ batchPercent: 1 });
37
+ const bots = makeBots(2);
38
+ expect(s.nextBatch(bots)).toHaveLength(1);
39
+ });
40
+
41
+ it("returns empty array for empty remaining", () => {
42
+ const s = new RollingWaveStrategy();
43
+ expect(s.nextBatch([])).toHaveLength(0);
44
+ });
45
+
46
+ it("handles 1 bot remaining", () => {
47
+ const s = new RollingWaveStrategy({ batchPercent: 50 });
48
+ const bots = makeBots(1);
49
+ expect(s.nextBatch(bots)).toHaveLength(1);
50
+ });
51
+
52
+ it("handles batchPercent > 100", () => {
53
+ const s = new RollingWaveStrategy({ batchPercent: 200 });
54
+ const bots = makeBots(5);
55
+ // 200% of 5 = 10, ceil = 10, but slice(0,10) on 5 items = 5
56
+ expect(s.nextBatch(bots)).toHaveLength(5);
57
+ });
58
+
59
+ it("returns correct pause duration", () => {
60
+ expect(new RollingWaveStrategy().pauseDuration()).toBe(60_000);
61
+ expect(new RollingWaveStrategy({ pauseMs: 30_000 }).pauseDuration()).toBe(30_000);
62
+ });
63
+
64
+ it("retries on failure until maxRetries", () => {
65
+ const s = new RollingWaveStrategy({ maxFailures: 2 });
66
+ const err = new Error("fail");
67
+ expect(s.onBotFailure("b1", err, 0)).toBe("retry");
68
+ expect(s.onBotFailure("b1", err, 1)).toBe("retry");
69
+ });
70
+
71
+ it("skips after maxRetries when under maxFailures", () => {
72
+ const s = new RollingWaveStrategy({ maxFailures: 3 });
73
+ const err = new Error("fail");
74
+ // attempt >= maxRetries (2), first total failure
75
+ expect(s.onBotFailure("b1", err, 2)).toBe("skip");
76
+ });
77
+
78
+ it("aborts when total failures reach maxFailures", () => {
79
+ const s = new RollingWaveStrategy({ maxFailures: 2 });
80
+ const err = new Error("fail");
81
+ // exhaust retries for bot1 → skip (totalFailures=1)
82
+ expect(s.onBotFailure("b1", err, 2)).toBe("skip");
83
+ // exhaust retries for bot2 → abort (totalFailures=2 >= maxFailures=2)
84
+ expect(s.onBotFailure("b2", err, 2)).toBe("abort");
85
+ });
86
+
87
+ it("has maxRetries of 2", () => {
88
+ expect(new RollingWaveStrategy().maxRetries()).toBe(2);
89
+ });
90
+
91
+ it("has healthCheckTimeout of 120_000", () => {
92
+ expect(new RollingWaveStrategy().healthCheckTimeout()).toBe(120_000);
93
+ });
94
+ });
95
+
96
+ describe("SingleBotStrategy", () => {
97
+ it("returns exactly 1 bot", () => {
98
+ const s = new SingleBotStrategy();
99
+ const bots = makeBots(10);
100
+ expect(s.nextBatch(bots)).toHaveLength(1);
101
+ expect(s.nextBatch(bots)[0]).toBe(bots[0]);
102
+ });
103
+
104
+ it("returns empty for empty remaining", () => {
105
+ expect(new SingleBotStrategy().nextBatch([])).toHaveLength(0);
106
+ });
107
+
108
+ it("has pauseDuration of 0", () => {
109
+ expect(new SingleBotStrategy().pauseDuration()).toBe(0);
110
+ });
111
+
112
+ it("always retries on failure", () => {
113
+ const s = new SingleBotStrategy();
114
+ const err = new Error("fail");
115
+ expect(s.onBotFailure("b1", err, 0)).toBe("retry");
116
+ expect(s.onBotFailure("b1", err, 1)).toBe("retry");
117
+ expect(s.onBotFailure("b1", err, 2)).toBe("retry");
118
+ // After maxRetries (3), aborts instead of retrying forever
119
+ expect(s.onBotFailure("b1", err, 99)).toBe("abort");
120
+ });
121
+
122
+ it("has maxRetries of 3", () => {
123
+ expect(new SingleBotStrategy().maxRetries()).toBe(3);
124
+ });
125
+
126
+ it("has healthCheckTimeout of 120_000", () => {
127
+ expect(new SingleBotStrategy().healthCheckTimeout()).toBe(120_000);
128
+ });
129
+ });
130
+
131
+ describe("ImmediateStrategy", () => {
132
+ it("returns all remaining bots", () => {
133
+ const s = new ImmediateStrategy();
134
+ const bots = makeBots(10);
135
+ expect(s.nextBatch(bots)).toHaveLength(10);
136
+ expect(s.nextBatch(bots)).toEqual(bots);
137
+ });
138
+
139
+ it("returns empty for empty remaining", () => {
140
+ expect(new ImmediateStrategy().nextBatch([])).toHaveLength(0);
141
+ });
142
+
143
+ it("does not mutate the input array", () => {
144
+ const s = new ImmediateStrategy();
145
+ const bots = makeBots(3);
146
+ const result = s.nextBatch(bots);
147
+ expect(result).not.toBe(bots);
148
+ expect(result).toEqual(bots);
149
+ });
150
+
151
+ it("has pauseDuration of 0", () => {
152
+ expect(new ImmediateStrategy().pauseDuration()).toBe(0);
153
+ });
154
+
155
+ it("always skips on failure", () => {
156
+ const s = new ImmediateStrategy();
157
+ const err = new Error("fail");
158
+ expect(s.onBotFailure("b1", err, 0)).toBe("skip");
159
+ expect(s.onBotFailure("b1", err, 5)).toBe("skip");
160
+ });
161
+
162
+ it("has maxRetries of 1", () => {
163
+ expect(new ImmediateStrategy().maxRetries()).toBe(1);
164
+ });
165
+
166
+ it("has healthCheckTimeout of 60_000", () => {
167
+ expect(new ImmediateStrategy().healthCheckTimeout()).toBe(60_000);
168
+ });
169
+ });
170
+
171
+ describe("createRolloutStrategy", () => {
172
+ it("creates RollingWaveStrategy", () => {
173
+ const s = createRolloutStrategy("rolling-wave");
174
+ expect(s).toBeInstanceOf(RollingWaveStrategy);
175
+ });
176
+
177
+ it("creates RollingWaveStrategy with options", () => {
178
+ const s = createRolloutStrategy("rolling-wave", { batchPercent: 50, pauseMs: 10_000 });
179
+ expect(s).toBeInstanceOf(RollingWaveStrategy);
180
+ expect(s.pauseDuration()).toBe(10_000);
181
+ });
182
+
183
+ it("creates SingleBotStrategy", () => {
184
+ const s = createRolloutStrategy("single-bot");
185
+ expect(s).toBeInstanceOf(SingleBotStrategy);
186
+ });
187
+
188
+ it("creates ImmediateStrategy", () => {
189
+ const s = createRolloutStrategy("immediate");
190
+ expect(s).toBeInstanceOf(ImmediateStrategy);
191
+ });
192
+ });
@@ -0,0 +1,218 @@
1
+ import type Docker from "dockerode";
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { VolumeSnapshotManager } from "../volume-snapshot-manager.js";
4
+
5
+ // Mock fs/promises
6
+ vi.mock("node:fs/promises", () => ({
7
+ mkdir: vi.fn().mockResolvedValue(undefined),
8
+ stat: vi.fn().mockResolvedValue({ size: 1024, mtime: new Date("2026-03-14T10:00:00Z") }),
9
+ readdir: vi.fn().mockResolvedValue([]),
10
+ rm: vi.fn().mockResolvedValue(undefined),
11
+ }));
12
+
13
+ // Mock logger
14
+ vi.mock("../../config/logger.js", () => ({
15
+ logger: {
16
+ info: vi.fn(),
17
+ warn: vi.fn(),
18
+ error: vi.fn(),
19
+ debug: vi.fn(),
20
+ },
21
+ }));
22
+
23
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
24
+
25
+ function mockContainer() {
26
+ return {
27
+ start: vi.fn().mockResolvedValue(undefined),
28
+ wait: vi.fn().mockResolvedValue({ StatusCode: 0 }),
29
+ remove: vi.fn().mockResolvedValue(undefined),
30
+ };
31
+ }
32
+
33
+ function mockDocker(): Docker {
34
+ return {
35
+ createContainer: vi.fn().mockResolvedValue(mockContainer()),
36
+ } as unknown as Docker;
37
+ }
38
+
39
+ describe("VolumeSnapshotManager", () => {
40
+ let docker: Docker;
41
+ let manager: VolumeSnapshotManager;
42
+
43
+ beforeEach(() => {
44
+ vi.clearAllMocks();
45
+ docker = mockDocker();
46
+ manager = new VolumeSnapshotManager(docker, "/data/fleet/snapshots");
47
+ });
48
+
49
+ describe("snapshot()", () => {
50
+ it("creates container with correct binds and runs tar", async () => {
51
+ await manager.snapshot("my-volume");
52
+
53
+ expect(docker.createContainer).toHaveBeenCalledWith(
54
+ expect.objectContaining({
55
+ Image: "alpine:latest",
56
+ Cmd: expect.arrayContaining(["tar", "cf"]),
57
+ HostConfig: expect.objectContaining({
58
+ Binds: expect.arrayContaining(["my-volume:/source:ro", "/data/fleet/snapshots:/backup"]),
59
+ AutoRemove: true,
60
+ }),
61
+ }),
62
+ );
63
+
64
+ const container = await (docker.createContainer as ReturnType<typeof vi.fn>).mock.results[0].value;
65
+ expect(container.start).toHaveBeenCalled();
66
+ expect(container.wait).toHaveBeenCalled();
67
+ });
68
+
69
+ it("returns a VolumeSnapshot with correct fields", async () => {
70
+ const result = await manager.snapshot("my-volume");
71
+
72
+ expect(result.volumeName).toBe("my-volume");
73
+ expect(result.id).toMatch(/^my-volume-\d{4}-\d{2}-\d{2}T/);
74
+ expect(result.archivePath).toMatch(/^\/data\/fleet\/snapshots\/my-volume-.*\.tar$/);
75
+ expect(result.sizeBytes).toBe(1024);
76
+ expect(result.createdAt).toBeInstanceOf(Date);
77
+ });
78
+
79
+ it("ensures backup directory exists", async () => {
80
+ await manager.snapshot("my-volume");
81
+ expect(mkdir).toHaveBeenCalledWith("/data/fleet/snapshots", { recursive: true });
82
+ });
83
+
84
+ it("cleans up container on start failure", async () => {
85
+ const container = mockContainer();
86
+ container.start.mockRejectedValue(new Error("start failed"));
87
+ (docker.createContainer as ReturnType<typeof vi.fn>).mockResolvedValue(container);
88
+
89
+ await expect(manager.snapshot("my-volume")).rejects.toThrow("start failed");
90
+ expect(container.remove).toHaveBeenCalledWith({ force: true });
91
+ });
92
+ });
93
+
94
+ describe("restore()", () => {
95
+ it("creates container with correct binds and runs tar xf", async () => {
96
+ const snapshotId = "my-volume-2026-03-14T10-00-00-000Z";
97
+ await manager.restore(snapshotId);
98
+
99
+ expect(docker.createContainer).toHaveBeenCalledWith(
100
+ expect.objectContaining({
101
+ Image: "alpine:latest",
102
+ Cmd: ["sh", "-c", `cd /target && rm -rf ./* ./.??* && tar xf /backup/${snapshotId}.tar -C /target`],
103
+ HostConfig: expect.objectContaining({
104
+ Binds: expect.arrayContaining(["my-volume:/target", "/data/fleet/snapshots:/backup:ro"]),
105
+ AutoRemove: true,
106
+ }),
107
+ }),
108
+ );
109
+ });
110
+
111
+ it("starts and waits for container", async () => {
112
+ const container = mockContainer();
113
+ (docker.createContainer as ReturnType<typeof vi.fn>).mockResolvedValue(container);
114
+
115
+ await manager.restore("my-volume-2026-03-14T10-00-00-000Z");
116
+
117
+ expect(container.start).toHaveBeenCalled();
118
+ expect(container.wait).toHaveBeenCalled();
119
+ });
120
+
121
+ it("throws if archive does not exist", async () => {
122
+ (stat as ReturnType<typeof vi.fn>).mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
123
+
124
+ await expect(manager.restore("nonexistent-2026-03-14T10-00-00-000Z")).rejects.toThrow("ENOENT");
125
+ });
126
+ });
127
+
128
+ describe("list()", () => {
129
+ it("returns snapshots sorted by date, newest first", async () => {
130
+ (readdir as ReturnType<typeof vi.fn>).mockResolvedValue([
131
+ "my-volume-2026-03-12T08-00-00-000Z.tar",
132
+ "my-volume-2026-03-14T10-00-00-000Z.tar",
133
+ "my-volume-2026-03-13T09-00-00-000Z.tar",
134
+ ]);
135
+
136
+ const oldDate = new Date("2026-03-12T08:00:00Z");
137
+ const midDate = new Date("2026-03-13T09:00:00Z");
138
+ const newDate = new Date("2026-03-14T10:00:00Z");
139
+
140
+ (stat as ReturnType<typeof vi.fn>)
141
+ .mockResolvedValueOnce({ size: 100, mtime: oldDate })
142
+ .mockResolvedValueOnce({ size: 300, mtime: newDate })
143
+ .mockResolvedValueOnce({ size: 200, mtime: midDate });
144
+
145
+ const result = await manager.list("my-volume");
146
+
147
+ expect(result).toHaveLength(3);
148
+ expect(result[0].createdAt).toEqual(newDate);
149
+ expect(result[1].createdAt).toEqual(midDate);
150
+ expect(result[2].createdAt).toEqual(oldDate);
151
+ });
152
+
153
+ it("filters to only matching volume name", async () => {
154
+ (readdir as ReturnType<typeof vi.fn>).mockResolvedValue([
155
+ "my-volume-2026-03-14T10-00-00-000Z.tar",
156
+ "other-volume-2026-03-14T10-00-00-000Z.tar",
157
+ ]);
158
+
159
+ const result = await manager.list("my-volume");
160
+ expect(result).toHaveLength(1);
161
+ expect(result[0].volumeName).toBe("my-volume");
162
+ });
163
+
164
+ it("returns empty array when backup dir does not exist", async () => {
165
+ (readdir as ReturnType<typeof vi.fn>).mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
166
+
167
+ const result = await manager.list("my-volume");
168
+ expect(result).toEqual([]);
169
+ });
170
+ });
171
+
172
+ describe("delete()", () => {
173
+ it("removes the archive file", async () => {
174
+ await manager.delete("my-volume-2026-03-14T10-00-00-000Z");
175
+
176
+ expect(rm).toHaveBeenCalledWith("/data/fleet/snapshots/my-volume-2026-03-14T10-00-00-000Z.tar", { force: true });
177
+ });
178
+ });
179
+
180
+ describe("cleanup()", () => {
181
+ it("removes old snapshots and keeps recent ones", async () => {
182
+ const now = Date.now();
183
+ const oldTime = new Date(now - 2 * 60 * 60 * 1000); // 2 hours ago
184
+ const recentTime = new Date(now - 10 * 60 * 1000); // 10 minutes ago
185
+
186
+ (readdir as ReturnType<typeof vi.fn>).mockResolvedValue([
187
+ "vol-2026-03-14T08-00-00-000Z.tar",
188
+ "vol-2026-03-14T09-50-00-000Z.tar",
189
+ ]);
190
+
191
+ (stat as ReturnType<typeof vi.fn>)
192
+ .mockResolvedValueOnce({ size: 100, mtime: oldTime })
193
+ .mockResolvedValueOnce({ size: 200, mtime: recentTime });
194
+
195
+ const maxAge = 60 * 60 * 1000; // 1 hour
196
+ const deleted = await manager.cleanup(maxAge);
197
+
198
+ expect(deleted).toBe(1);
199
+ expect(rm).toHaveBeenCalledTimes(1);
200
+ expect(rm).toHaveBeenCalledWith("/data/fleet/snapshots/vol-2026-03-14T08-00-00-000Z.tar", { force: true });
201
+ });
202
+
203
+ it("returns 0 when backup dir does not exist", async () => {
204
+ (readdir as ReturnType<typeof vi.fn>).mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
205
+
206
+ const result = await manager.cleanup(60_000);
207
+ expect(result).toBe(0);
208
+ });
209
+
210
+ it("skips non-tar files", async () => {
211
+ (readdir as ReturnType<typeof vi.fn>).mockResolvedValue(["readme.txt", ".gitkeep"]);
212
+
213
+ const result = await manager.cleanup(60_000);
214
+ expect(result).toBe(0);
215
+ expect(stat).not.toHaveBeenCalled();
216
+ });
217
+ });
218
+ });
@@ -1,3 +1,5 @@
1
1
  export * from "./repository-types.js";
2
+ export * from "./rollout-strategy.js";
2
3
  export * from "./services.js";
3
4
  export * from "./types.js";
5
+ export * from "./volume-snapshot-manager.js";
@@ -0,0 +1,128 @@
1
+ import type { BotProfile } from "./types.js";
2
+
3
+ export interface IRolloutStrategy {
4
+ /** Select next batch from remaining bots */
5
+ nextBatch(remaining: BotProfile[]): BotProfile[];
6
+ /** Milliseconds to wait between waves */
7
+ pauseDuration(): number;
8
+ /** What to do when a single bot update fails */
9
+ onBotFailure(botId: string, error: Error, attempt: number): "abort" | "skip" | "retry";
10
+ /** Max retries per bot before skip/abort */
11
+ maxRetries(): number;
12
+ /** Health check timeout per bot (ms) */
13
+ healthCheckTimeout(): number;
14
+ }
15
+
16
+ export interface RollingWaveOptions {
17
+ batchPercent?: number;
18
+ pauseMs?: number;
19
+ maxFailures?: number;
20
+ }
21
+
22
+ /**
23
+ * Rolling wave strategy — processes bots in configurable percentage batches.
24
+ * Create a new instance per rollout; totalFailures accumulates across waves
25
+ * within a single rollout. Call reset() if reusing across rollouts.
26
+ */
27
+ export class RollingWaveStrategy implements IRolloutStrategy {
28
+ private readonly batchPercent: number;
29
+ private readonly pauseMs: number;
30
+ private readonly maxFailures: number;
31
+ private totalFailures = 0;
32
+
33
+ constructor(opts: RollingWaveOptions = {}) {
34
+ this.batchPercent = opts.batchPercent ?? 25;
35
+ this.pauseMs = opts.pauseMs ?? 60_000;
36
+ this.maxFailures = opts.maxFailures ?? 3;
37
+ }
38
+
39
+ nextBatch(remaining: BotProfile[]): BotProfile[] {
40
+ if (remaining.length === 0) return [];
41
+ const count = Math.max(1, Math.ceil((remaining.length * this.batchPercent) / 100));
42
+ return remaining.slice(0, count);
43
+ }
44
+
45
+ pauseDuration(): number {
46
+ return this.pauseMs;
47
+ }
48
+
49
+ onBotFailure(_botId: string, _error: Error, attempt: number): "abort" | "skip" | "retry" {
50
+ if (attempt < this.maxRetries()) return "retry";
51
+ this.totalFailures++;
52
+ if (this.totalFailures >= this.maxFailures) return "abort";
53
+ return "skip";
54
+ }
55
+
56
+ maxRetries(): number {
57
+ return 2;
58
+ }
59
+
60
+ healthCheckTimeout(): number {
61
+ return 120_000;
62
+ }
63
+
64
+ /** Reset failure counters for reuse across rollouts. */
65
+ reset(): void {
66
+ this.totalFailures = 0;
67
+ }
68
+ }
69
+
70
+ export class SingleBotStrategy implements IRolloutStrategy {
71
+ nextBatch(remaining: BotProfile[]): BotProfile[] {
72
+ if (remaining.length === 0) return [];
73
+ return remaining.slice(0, 1);
74
+ }
75
+
76
+ pauseDuration(): number {
77
+ return 0;
78
+ }
79
+
80
+ onBotFailure(_botId: string, _error: Error, attempt: number): "abort" | "skip" | "retry" {
81
+ if (attempt < this.maxRetries()) return "retry";
82
+ return "abort";
83
+ }
84
+
85
+ maxRetries(): number {
86
+ return 3;
87
+ }
88
+
89
+ healthCheckTimeout(): number {
90
+ return 120_000;
91
+ }
92
+ }
93
+
94
+ export class ImmediateStrategy implements IRolloutStrategy {
95
+ nextBatch(remaining: BotProfile[]): BotProfile[] {
96
+ return [...remaining];
97
+ }
98
+
99
+ pauseDuration(): number {
100
+ return 0;
101
+ }
102
+
103
+ onBotFailure(_botId: string, _error: Error, _attempt: number): "abort" | "skip" | "retry" {
104
+ return "skip";
105
+ }
106
+
107
+ maxRetries(): number {
108
+ return 1;
109
+ }
110
+
111
+ healthCheckTimeout(): number {
112
+ return 60_000;
113
+ }
114
+ }
115
+
116
+ export function createRolloutStrategy(
117
+ type: "rolling-wave" | "single-bot" | "immediate",
118
+ options?: RollingWaveOptions,
119
+ ): IRolloutStrategy {
120
+ switch (type) {
121
+ case "rolling-wave":
122
+ return new RollingWaveStrategy(options);
123
+ case "single-bot":
124
+ return new SingleBotStrategy();
125
+ case "immediate":
126
+ return new ImmediateStrategy();
127
+ }
128
+ }