@wopr-network/platform-core 1.35.0 → 1.35.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.
- package/dist/email/handlebars-renderer.test.d.ts +1 -0
- package/dist/email/handlebars-renderer.test.js +174 -0
- package/dist/fleet/fleet-notification-listener.test.d.ts +1 -0
- package/dist/fleet/fleet-notification-listener.test.js +244 -0
- package/dist/fleet/init-fleet-updater.d.ts +1 -1
- package/dist/fleet/init-fleet-updater.js +19 -3
- package/dist/fleet/init-fleet-updater.test.d.ts +1 -0
- package/dist/fleet/init-fleet-updater.test.js +186 -0
- package/dist/trpc/admin-fleet-update-router.test.d.ts +1 -0
- package/dist/trpc/admin-fleet-update-router.test.js +164 -0
- package/package.json +1 -1
- package/src/email/handlebars-renderer.test.ts +209 -0
- package/src/fleet/fleet-notification-listener.test.ts +322 -0
- package/src/fleet/init-fleet-updater.test.ts +234 -0
- package/src/fleet/init-fleet-updater.ts +22 -4
- package/src/trpc/admin-fleet-update-router.test.ts +201 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { HandlebarsRenderer } from "./handlebars-renderer.js";
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
// Helpers
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
function makeTemplate(overrides = {}) {
|
|
7
|
+
return {
|
|
8
|
+
id: "tpl-1",
|
|
9
|
+
name: "test-template",
|
|
10
|
+
description: "A test template",
|
|
11
|
+
subject: "Hello {{name}}",
|
|
12
|
+
htmlBody: "<h1>Hello {{name}}</h1>",
|
|
13
|
+
textBody: "Hello {{name}}",
|
|
14
|
+
active: true,
|
|
15
|
+
createdAt: Date.now(),
|
|
16
|
+
updatedAt: Date.now(),
|
|
17
|
+
...overrides,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function makeRepo(templates = {}) {
|
|
21
|
+
return {
|
|
22
|
+
getByName: vi.fn().mockImplementation((name) => Promise.resolve(templates[name] ?? null)),
|
|
23
|
+
list: vi.fn().mockResolvedValue(Object.values(templates).filter(Boolean)),
|
|
24
|
+
upsert: vi.fn().mockResolvedValue(undefined),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Tests
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
describe("HandlebarsRenderer", () => {
|
|
31
|
+
it("returns null for unknown template", async () => {
|
|
32
|
+
const repo = makeRepo({});
|
|
33
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
34
|
+
const result = await renderer.render("nonexistent", { name: "World" });
|
|
35
|
+
expect(result).toBeNull();
|
|
36
|
+
expect(repo.getByName).toHaveBeenCalledWith("nonexistent");
|
|
37
|
+
});
|
|
38
|
+
it("returns null for inactive template", async () => {
|
|
39
|
+
const repo = makeRepo({
|
|
40
|
+
"inactive-tpl": makeTemplate({ name: "inactive-tpl", active: false }),
|
|
41
|
+
});
|
|
42
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
43
|
+
const result = await renderer.render("inactive-tpl", { name: "World" });
|
|
44
|
+
expect(result).toBeNull();
|
|
45
|
+
});
|
|
46
|
+
it("compiles Handlebars and returns subject/html/text", async () => {
|
|
47
|
+
const repo = makeRepo({
|
|
48
|
+
greeting: makeTemplate({
|
|
49
|
+
name: "greeting",
|
|
50
|
+
subject: "Hi {{name}}!",
|
|
51
|
+
htmlBody: "<p>Welcome, {{name}}!</p>",
|
|
52
|
+
textBody: "Welcome, {{name}}!",
|
|
53
|
+
}),
|
|
54
|
+
});
|
|
55
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
56
|
+
const result = await renderer.render("greeting", { name: "Alice" });
|
|
57
|
+
expect(result).not.toBeNull();
|
|
58
|
+
expect(result?.subject).toBe("Hi Alice!");
|
|
59
|
+
expect(result?.html).toBe("<p>Welcome, Alice!</p>");
|
|
60
|
+
expect(result?.text).toBe("Welcome, Alice!");
|
|
61
|
+
});
|
|
62
|
+
it("injects currentYear automatically", async () => {
|
|
63
|
+
const repo = makeRepo({
|
|
64
|
+
footer: makeTemplate({
|
|
65
|
+
name: "footer",
|
|
66
|
+
subject: "Year: {{currentYear}}",
|
|
67
|
+
htmlBody: "<p>© {{currentYear}}</p>",
|
|
68
|
+
textBody: "(c) {{currentYear}}",
|
|
69
|
+
}),
|
|
70
|
+
});
|
|
71
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
72
|
+
const result = await renderer.render("footer", {});
|
|
73
|
+
const year = new Date().getFullYear();
|
|
74
|
+
expect(result?.subject).toBe(`Year: ${year}`);
|
|
75
|
+
expect(result?.html).toBe(`<p>© ${year}</p>`);
|
|
76
|
+
expect(result?.text).toBe(`(c) ${year}`);
|
|
77
|
+
});
|
|
78
|
+
it("does not override explicit currentYear from data", async () => {
|
|
79
|
+
const repo = makeRepo({
|
|
80
|
+
footer: makeTemplate({
|
|
81
|
+
name: "footer",
|
|
82
|
+
subject: "Year: {{currentYear}}",
|
|
83
|
+
htmlBody: "<p>{{currentYear}}</p>",
|
|
84
|
+
textBody: "{{currentYear}}",
|
|
85
|
+
}),
|
|
86
|
+
});
|
|
87
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
88
|
+
const result = await renderer.render("footer", { currentYear: 2099 });
|
|
89
|
+
expect(result?.subject).toBe("Year: 2099");
|
|
90
|
+
});
|
|
91
|
+
describe("helpers", () => {
|
|
92
|
+
it("eq helper returns true for equal values", async () => {
|
|
93
|
+
const repo = makeRepo({
|
|
94
|
+
cond: makeTemplate({
|
|
95
|
+
name: "cond",
|
|
96
|
+
subject: '{{#if (eq status "active")}}Active{{else}}Inactive{{/if}}',
|
|
97
|
+
htmlBody: "ok",
|
|
98
|
+
textBody: "ok",
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
102
|
+
const active = await renderer.render("cond", { status: "active" });
|
|
103
|
+
expect(active?.subject).toBe("Active");
|
|
104
|
+
const inactive = await renderer.render("cond", { status: "disabled" });
|
|
105
|
+
expect(inactive?.subject).toBe("Inactive");
|
|
106
|
+
});
|
|
107
|
+
it("gt helper compares numbers", async () => {
|
|
108
|
+
const repo = makeRepo({
|
|
109
|
+
gt: makeTemplate({
|
|
110
|
+
name: "gt",
|
|
111
|
+
subject: "{{#if (gt count 5)}}Many{{else}}Few{{/if}}",
|
|
112
|
+
htmlBody: "ok",
|
|
113
|
+
textBody: "ok",
|
|
114
|
+
}),
|
|
115
|
+
});
|
|
116
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
117
|
+
const many = await renderer.render("gt", { count: 10 });
|
|
118
|
+
expect(many?.subject).toBe("Many");
|
|
119
|
+
const few = await renderer.render("gt", { count: 3 });
|
|
120
|
+
expect(few?.subject).toBe("Few");
|
|
121
|
+
});
|
|
122
|
+
it("formatDate helper formats timestamps", async () => {
|
|
123
|
+
const repo = makeRepo({
|
|
124
|
+
dated: makeTemplate({
|
|
125
|
+
name: "dated",
|
|
126
|
+
subject: "Date: {{formatDate ts}}",
|
|
127
|
+
htmlBody: "ok",
|
|
128
|
+
textBody: "ok",
|
|
129
|
+
}),
|
|
130
|
+
});
|
|
131
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
132
|
+
// Use noon UTC to avoid timezone date-boundary shifts
|
|
133
|
+
const ts = new Date("2025-01-15T12:00:00Z").getTime();
|
|
134
|
+
const result = await renderer.render("dated", { ts });
|
|
135
|
+
// The formatted string uses en-US locale with year/month/day
|
|
136
|
+
const expected = new Date(ts).toLocaleDateString("en-US", {
|
|
137
|
+
year: "numeric",
|
|
138
|
+
month: "long",
|
|
139
|
+
day: "numeric",
|
|
140
|
+
});
|
|
141
|
+
expect(result?.subject).toBe(`Date: ${expected}`);
|
|
142
|
+
});
|
|
143
|
+
it("formatDate helper passes through non-numeric values", async () => {
|
|
144
|
+
const repo = makeRepo({
|
|
145
|
+
dated: makeTemplate({
|
|
146
|
+
name: "dated",
|
|
147
|
+
subject: "Date: {{formatDate ts}}",
|
|
148
|
+
htmlBody: "ok",
|
|
149
|
+
textBody: "ok",
|
|
150
|
+
}),
|
|
151
|
+
});
|
|
152
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
153
|
+
const result = await renderer.render("dated", { ts: "not-a-number" });
|
|
154
|
+
expect(result?.subject).toBe("Date: not-a-number");
|
|
155
|
+
});
|
|
156
|
+
it("escapeHtml helper escapes special characters", async () => {
|
|
157
|
+
const repo = makeRepo({
|
|
158
|
+
esc: makeTemplate({
|
|
159
|
+
name: "esc",
|
|
160
|
+
subject: "Safe: {{escapeHtml input}}",
|
|
161
|
+
htmlBody: "ok",
|
|
162
|
+
textBody: "ok",
|
|
163
|
+
}),
|
|
164
|
+
});
|
|
165
|
+
const renderer = new HandlebarsRenderer(repo);
|
|
166
|
+
const result = await renderer.render("esc", {
|
|
167
|
+
input: '<script>alert("xss")</script>',
|
|
168
|
+
});
|
|
169
|
+
expect(result?.subject).toContain("<script>");
|
|
170
|
+
expect(result?.subject).toContain(""xss"");
|
|
171
|
+
expect(result?.subject).not.toContain("<script>");
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { FleetEventEmitter } from "./fleet-event-emitter.js";
|
|
3
|
+
import { initFleetNotificationListener } from "./fleet-notification-listener.js";
|
|
4
|
+
vi.mock("../config/logger.js", () => ({
|
|
5
|
+
logger: {
|
|
6
|
+
info: vi.fn(),
|
|
7
|
+
error: vi.fn(),
|
|
8
|
+
warn: vi.fn(),
|
|
9
|
+
debug: vi.fn(),
|
|
10
|
+
},
|
|
11
|
+
}));
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// Helpers
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
const DEBOUNCE_MS = 100;
|
|
16
|
+
function makePrefs(overrides = {}) {
|
|
17
|
+
return {
|
|
18
|
+
billing_low_balance: true,
|
|
19
|
+
billing_receipts: true,
|
|
20
|
+
billing_auto_topup: true,
|
|
21
|
+
agent_channel_disconnect: true,
|
|
22
|
+
agent_status_changes: false,
|
|
23
|
+
account_role_changes: true,
|
|
24
|
+
account_team_invites: true,
|
|
25
|
+
fleet_updates: true,
|
|
26
|
+
...overrides,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function makePrefsRepo(prefs = makePrefs()) {
|
|
30
|
+
return {
|
|
31
|
+
get: vi.fn().mockResolvedValue(prefs),
|
|
32
|
+
update: vi.fn().mockResolvedValue(undefined),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function makeNotificationService() {
|
|
36
|
+
return {
|
|
37
|
+
notifyFleetUpdateComplete: vi.fn(),
|
|
38
|
+
notifyFleetUpdateAvailable: vi.fn(),
|
|
39
|
+
notifyLowBalance: vi.fn(),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function botUpdated(tenantId, version = "v1.2.0") {
|
|
43
|
+
return {
|
|
44
|
+
type: "bot.updated",
|
|
45
|
+
botId: `bot-${Math.random().toString(36).slice(2, 6)}`,
|
|
46
|
+
tenantId,
|
|
47
|
+
timestamp: new Date().toISOString(),
|
|
48
|
+
version,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function botUpdateFailed(tenantId, version = "v1.2.0") {
|
|
52
|
+
return {
|
|
53
|
+
type: "bot.update_failed",
|
|
54
|
+
botId: `bot-${Math.random().toString(36).slice(2, 6)}`,
|
|
55
|
+
tenantId,
|
|
56
|
+
timestamp: new Date().toISOString(),
|
|
57
|
+
version,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Tests
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
describe("initFleetNotificationListener", () => {
|
|
64
|
+
let emitter;
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
vi.useFakeTimers();
|
|
67
|
+
emitter = new FleetEventEmitter();
|
|
68
|
+
});
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
vi.useRealTimers();
|
|
71
|
+
});
|
|
72
|
+
it("ignores non-bot events (node events)", async () => {
|
|
73
|
+
const notificationService = makeNotificationService();
|
|
74
|
+
const preferences = makePrefsRepo();
|
|
75
|
+
initFleetNotificationListener({
|
|
76
|
+
eventEmitter: emitter,
|
|
77
|
+
notificationService,
|
|
78
|
+
preferences,
|
|
79
|
+
resolveEmail: vi.fn().mockResolvedValue("user@example.com"),
|
|
80
|
+
debounceMs: DEBOUNCE_MS,
|
|
81
|
+
});
|
|
82
|
+
emitter.emit({
|
|
83
|
+
type: "node.provisioned",
|
|
84
|
+
nodeId: "node-1",
|
|
85
|
+
timestamp: new Date().toISOString(),
|
|
86
|
+
});
|
|
87
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
88
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
89
|
+
});
|
|
90
|
+
it("ignores non-update bot events (bot.started, bot.stopped)", async () => {
|
|
91
|
+
const notificationService = makeNotificationService();
|
|
92
|
+
const preferences = makePrefsRepo();
|
|
93
|
+
initFleetNotificationListener({
|
|
94
|
+
eventEmitter: emitter,
|
|
95
|
+
notificationService,
|
|
96
|
+
preferences,
|
|
97
|
+
resolveEmail: vi.fn().mockResolvedValue("user@example.com"),
|
|
98
|
+
debounceMs: DEBOUNCE_MS,
|
|
99
|
+
});
|
|
100
|
+
emitter.emit({
|
|
101
|
+
type: "bot.started",
|
|
102
|
+
botId: "bot-1",
|
|
103
|
+
tenantId: "t1",
|
|
104
|
+
timestamp: new Date().toISOString(),
|
|
105
|
+
});
|
|
106
|
+
emitter.emit({
|
|
107
|
+
type: "bot.stopped",
|
|
108
|
+
botId: "bot-2",
|
|
109
|
+
tenantId: "t1",
|
|
110
|
+
timestamp: new Date().toISOString(),
|
|
111
|
+
});
|
|
112
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
113
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
114
|
+
});
|
|
115
|
+
it("aggregates multiple bot.updated events per tenant into one notification", async () => {
|
|
116
|
+
const notificationService = makeNotificationService();
|
|
117
|
+
const preferences = makePrefsRepo();
|
|
118
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
119
|
+
initFleetNotificationListener({
|
|
120
|
+
eventEmitter: emitter,
|
|
121
|
+
notificationService,
|
|
122
|
+
preferences,
|
|
123
|
+
resolveEmail,
|
|
124
|
+
debounceMs: DEBOUNCE_MS,
|
|
125
|
+
});
|
|
126
|
+
// Emit 3 successful updates for the same tenant
|
|
127
|
+
emitter.emit(botUpdated("t1", "v2.0.0"));
|
|
128
|
+
emitter.emit(botUpdated("t1", "v2.0.0"));
|
|
129
|
+
emitter.emit(botUpdated("t1", "v2.0.0"));
|
|
130
|
+
// No notification yet — debounce hasn't fired
|
|
131
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
132
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
133
|
+
expect(notificationService.notifyFleetUpdateComplete).toHaveBeenCalledOnce();
|
|
134
|
+
expect(notificationService.notifyFleetUpdateComplete).toHaveBeenCalledWith("t1", "owner@example.com", "v2.0.0", 3, // succeeded
|
|
135
|
+
0);
|
|
136
|
+
});
|
|
137
|
+
it("sends summary with correct succeeded/failed counts after debounce", async () => {
|
|
138
|
+
const notificationService = makeNotificationService();
|
|
139
|
+
const preferences = makePrefsRepo();
|
|
140
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
141
|
+
initFleetNotificationListener({
|
|
142
|
+
eventEmitter: emitter,
|
|
143
|
+
notificationService,
|
|
144
|
+
preferences,
|
|
145
|
+
resolveEmail,
|
|
146
|
+
debounceMs: DEBOUNCE_MS,
|
|
147
|
+
});
|
|
148
|
+
emitter.emit(botUpdated("t1", "v3.0.0"));
|
|
149
|
+
emitter.emit(botUpdated("t1", "v3.0.0"));
|
|
150
|
+
emitter.emit(botUpdateFailed("t1", "v3.0.0"));
|
|
151
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
152
|
+
expect(notificationService.notifyFleetUpdateComplete).toHaveBeenCalledWith("t1", "owner@example.com", "v3.0.0", 2, // succeeded
|
|
153
|
+
1);
|
|
154
|
+
});
|
|
155
|
+
it("updates version from subsequent events", async () => {
|
|
156
|
+
const notificationService = makeNotificationService();
|
|
157
|
+
const preferences = makePrefsRepo();
|
|
158
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
159
|
+
initFleetNotificationListener({
|
|
160
|
+
eventEmitter: emitter,
|
|
161
|
+
notificationService,
|
|
162
|
+
preferences,
|
|
163
|
+
resolveEmail,
|
|
164
|
+
debounceMs: DEBOUNCE_MS,
|
|
165
|
+
});
|
|
166
|
+
// First event has v1.0.0, subsequent event changes to v1.1.0
|
|
167
|
+
emitter.emit(botUpdated("t1", "v1.0.0"));
|
|
168
|
+
emitter.emit(botUpdated("t1", "v1.1.0"));
|
|
169
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
170
|
+
expect(notificationService.notifyFleetUpdateComplete).toHaveBeenCalledWith("t1", "owner@example.com", "v1.1.0", // updated to latest version
|
|
171
|
+
2, 0);
|
|
172
|
+
});
|
|
173
|
+
it("checks fleet_updates preference — skips if disabled", async () => {
|
|
174
|
+
const notificationService = makeNotificationService();
|
|
175
|
+
const preferences = makePrefsRepo(makePrefs({ fleet_updates: false }));
|
|
176
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
177
|
+
initFleetNotificationListener({
|
|
178
|
+
eventEmitter: emitter,
|
|
179
|
+
notificationService,
|
|
180
|
+
preferences,
|
|
181
|
+
resolveEmail,
|
|
182
|
+
debounceMs: DEBOUNCE_MS,
|
|
183
|
+
});
|
|
184
|
+
emitter.emit(botUpdated("t1"));
|
|
185
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
186
|
+
expect(preferences.get).toHaveBeenCalledWith("t1");
|
|
187
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
188
|
+
});
|
|
189
|
+
it("skips if email resolver returns null", async () => {
|
|
190
|
+
const notificationService = makeNotificationService();
|
|
191
|
+
const preferences = makePrefsRepo();
|
|
192
|
+
const resolveEmail = vi.fn().mockResolvedValue(null);
|
|
193
|
+
initFleetNotificationListener({
|
|
194
|
+
eventEmitter: emitter,
|
|
195
|
+
notificationService,
|
|
196
|
+
preferences,
|
|
197
|
+
resolveEmail,
|
|
198
|
+
debounceMs: DEBOUNCE_MS,
|
|
199
|
+
});
|
|
200
|
+
emitter.emit(botUpdated("t1"));
|
|
201
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
202
|
+
expect(resolveEmail).toHaveBeenCalledWith("t1");
|
|
203
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
204
|
+
});
|
|
205
|
+
it("async shutdown flushes pending notifications", async () => {
|
|
206
|
+
const notificationService = makeNotificationService();
|
|
207
|
+
const preferences = makePrefsRepo();
|
|
208
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
209
|
+
const shutdown = initFleetNotificationListener({
|
|
210
|
+
eventEmitter: emitter,
|
|
211
|
+
notificationService,
|
|
212
|
+
preferences,
|
|
213
|
+
resolveEmail,
|
|
214
|
+
debounceMs: DEBOUNCE_MS,
|
|
215
|
+
});
|
|
216
|
+
emitter.emit(botUpdated("t1", "v5.0.0"));
|
|
217
|
+
emitter.emit(botUpdated("t2", "v5.0.0"));
|
|
218
|
+
// Don't advance timers — flush via shutdown instead
|
|
219
|
+
await shutdown();
|
|
220
|
+
// Both tenants should have been flushed
|
|
221
|
+
expect(notificationService.notifyFleetUpdateComplete).toHaveBeenCalledTimes(2);
|
|
222
|
+
const calls = vi.mocked(notificationService.notifyFleetUpdateComplete).mock.calls;
|
|
223
|
+
const tenantIds = calls.map((c) => c[0]);
|
|
224
|
+
expect(tenantIds).toContain("t1");
|
|
225
|
+
expect(tenantIds).toContain("t2");
|
|
226
|
+
});
|
|
227
|
+
it("no further events after shutdown", async () => {
|
|
228
|
+
const notificationService = makeNotificationService();
|
|
229
|
+
const preferences = makePrefsRepo();
|
|
230
|
+
const resolveEmail = vi.fn().mockResolvedValue("owner@example.com");
|
|
231
|
+
const shutdown = initFleetNotificationListener({
|
|
232
|
+
eventEmitter: emitter,
|
|
233
|
+
notificationService,
|
|
234
|
+
preferences,
|
|
235
|
+
resolveEmail,
|
|
236
|
+
debounceMs: DEBOUNCE_MS,
|
|
237
|
+
});
|
|
238
|
+
await shutdown();
|
|
239
|
+
// Events after shutdown should not trigger anything
|
|
240
|
+
emitter.emit(botUpdated("t1"));
|
|
241
|
+
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 50);
|
|
242
|
+
expect(notificationService.notifyFleetUpdateComplete).not.toHaveBeenCalled();
|
|
243
|
+
});
|
|
244
|
+
});
|
|
@@ -41,7 +41,7 @@ export interface FleetUpdaterConfig {
|
|
|
41
41
|
/** Optional fleet event emitter. When provided, bot.updated / bot.update_failed events are emitted. */
|
|
42
42
|
eventEmitter?: FleetEventEmitter;
|
|
43
43
|
/** Called with manual-mode tenant IDs when a new image is available but they are excluded from rollout. */
|
|
44
|
-
onManualTenantsSkipped?: (tenantIds: string[]) => void;
|
|
44
|
+
onManualTenantsSkipped?: (tenantIds: string[], imageTag: string) => void;
|
|
45
45
|
}
|
|
46
46
|
export interface FleetUpdaterHandle {
|
|
47
47
|
poller: ImagePoller;
|
|
@@ -36,6 +36,10 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
|
|
|
36
36
|
const updater = new ContainerUpdater(docker, profileStore, fleet, poller);
|
|
37
37
|
const snapshotManager = new VolumeSnapshotManager(docker, snapshotDir);
|
|
38
38
|
const strategy = createRolloutStrategy(strategyType, strategyOptions);
|
|
39
|
+
// Captured by the onUpdateAvailable handler and read by getUpdatableProfiles.
|
|
40
|
+
// Set before each orchestrator.rollout() call so the callback receives the
|
|
41
|
+
// image tag that triggered this rollout rather than a stale "latest" placeholder.
|
|
42
|
+
let currentImageTag = "latest";
|
|
39
43
|
const orchestrator = new RolloutOrchestrator({
|
|
40
44
|
updater,
|
|
41
45
|
snapshotManager,
|
|
@@ -53,7 +57,7 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
|
|
|
53
57
|
});
|
|
54
58
|
if (!configRepo) {
|
|
55
59
|
if (manualPolicyIds.length > 0 && onManualTenantsSkipped) {
|
|
56
|
-
onManualTenantsSkipped([...new Set(manualPolicyIds)]);
|
|
60
|
+
onManualTenantsSkipped([...new Set(manualPolicyIds)], currentImageTag);
|
|
57
61
|
}
|
|
58
62
|
return nonManualPolicy;
|
|
59
63
|
}
|
|
@@ -70,7 +74,7 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
|
|
|
70
74
|
}));
|
|
71
75
|
const allManualIds = [...manualPolicyIds, ...configManualIds];
|
|
72
76
|
if (allManualIds.length > 0 && onManualTenantsSkipped) {
|
|
73
|
-
onManualTenantsSkipped([...new Set(allManualIds)]);
|
|
77
|
+
onManualTenantsSkipped([...new Set(allManualIds)], currentImageTag);
|
|
74
78
|
}
|
|
75
79
|
return results.filter((p) => p !== null);
|
|
76
80
|
},
|
|
@@ -106,11 +110,23 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
|
|
|
106
110
|
// Wire the detection → orchestration pipeline.
|
|
107
111
|
// Any digest change triggers a fleet-wide rollout because the managed image
|
|
108
112
|
// is shared across all tenants — one new digest means all bots need updating.
|
|
109
|
-
poller.onUpdateAvailable = async (
|
|
113
|
+
poller.onUpdateAvailable = async (botId, _newDigest) => {
|
|
110
114
|
if (orchestrator.isRolling) {
|
|
111
115
|
logger.debug("Skipping update trigger — rollout already in progress");
|
|
112
116
|
return;
|
|
113
117
|
}
|
|
118
|
+
// Resolve the image tag from the bot that triggered the update so that
|
|
119
|
+
// onManualTenantsSkipped receives the real version instead of "latest".
|
|
120
|
+
try {
|
|
121
|
+
const triggeringProfile = await profileStore.get(botId);
|
|
122
|
+
if (triggeringProfile) {
|
|
123
|
+
const img = triggeringProfile.image;
|
|
124
|
+
currentImageTag = img.includes(":") ? (img.split(":").pop() ?? "latest") : "latest";
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// Best-effort — currentImageTag stays at previous value
|
|
129
|
+
}
|
|
114
130
|
logger.info("New image digest detected — starting fleet-wide rollout");
|
|
115
131
|
await orchestrator.rollout().catch((err) => {
|
|
116
132
|
logger.error("Rollout failed", { err });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests the profile-filtering + onManualTenantsSkipped logic used inside initFleetUpdater.
|
|
3
|
+
*
|
|
4
|
+
* We can't import initFleetUpdater directly because it constructs ImagePoller,
|
|
5
|
+
* ContainerUpdater, etc. which pull in heavy dependencies that cause hangs.
|
|
6
|
+
* Instead, we replicate the getUpdatableProfiles closure from initFleetUpdater
|
|
7
|
+
* and test it in isolation via a RolloutOrchestrator with mock deps.
|
|
8
|
+
*/
|
|
9
|
+
import { describe, expect, it, vi } from "vitest";
|
|
10
|
+
import { RolloutOrchestrator } from "./rollout-orchestrator.js";
|
|
11
|
+
vi.mock("../config/logger.js", () => ({
|
|
12
|
+
logger: {
|
|
13
|
+
info: vi.fn(),
|
|
14
|
+
error: vi.fn(),
|
|
15
|
+
warn: vi.fn(),
|
|
16
|
+
debug: vi.fn(),
|
|
17
|
+
},
|
|
18
|
+
}));
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Helpers
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
function makeProfileWithFields(fields) {
|
|
23
|
+
return {
|
|
24
|
+
...fields,
|
|
25
|
+
image: "ghcr.io/org/img:latest",
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function makeProfileRepo(profiles) {
|
|
29
|
+
return {
|
|
30
|
+
list: vi.fn().mockResolvedValue(profiles),
|
|
31
|
+
get: vi
|
|
32
|
+
.fn()
|
|
33
|
+
.mockImplementation((id) => Promise.resolve(profiles.find((p) => p.id === id) ?? null)),
|
|
34
|
+
save: vi.fn().mockResolvedValue(undefined),
|
|
35
|
+
delete: vi.fn().mockResolvedValue(false),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function makeConfigRepo(configs = {}) {
|
|
39
|
+
return {
|
|
40
|
+
get: vi.fn().mockImplementation((tenantId) => {
|
|
41
|
+
const cfg = configs[tenantId];
|
|
42
|
+
return Promise.resolve(cfg ? { tenantId, ...cfg, updatedAt: Date.now() } : null);
|
|
43
|
+
}),
|
|
44
|
+
upsert: vi.fn().mockResolvedValue(undefined),
|
|
45
|
+
listAutoEnabled: vi.fn().mockResolvedValue([]),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function makeMockUpdater() {
|
|
49
|
+
return {
|
|
50
|
+
updateBot: vi.fn().mockResolvedValue({
|
|
51
|
+
botId: "",
|
|
52
|
+
success: true,
|
|
53
|
+
previousImage: "",
|
|
54
|
+
newImage: "",
|
|
55
|
+
previousDigest: null,
|
|
56
|
+
newDigest: null,
|
|
57
|
+
rolledBack: false,
|
|
58
|
+
}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function makeMockSnapshotManager() {
|
|
62
|
+
return {
|
|
63
|
+
snapshot: vi.fn(),
|
|
64
|
+
restore: vi.fn(),
|
|
65
|
+
delete: vi.fn(),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function makeMockStrategy() {
|
|
69
|
+
return {
|
|
70
|
+
nextBatch: vi.fn().mockImplementation((remaining) => remaining),
|
|
71
|
+
pauseDuration: vi.fn().mockReturnValue(0),
|
|
72
|
+
onBotFailure: vi.fn().mockReturnValue("skip"),
|
|
73
|
+
maxRetries: vi.fn().mockReturnValue(0),
|
|
74
|
+
healthCheckTimeout: vi.fn().mockReturnValue(0),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Builds the same getUpdatableProfiles closure that initFleetUpdater creates,
|
|
79
|
+
* so we can test the filtering + callback logic without importing the heavy module.
|
|
80
|
+
*/
|
|
81
|
+
function buildGetUpdatableProfiles(profileRepo, configRepo, onManualTenantsSkipped, imageTag = "v1.2.3") {
|
|
82
|
+
return async () => {
|
|
83
|
+
const profiles = await profileRepo.list();
|
|
84
|
+
const manualPolicyIds = [];
|
|
85
|
+
const nonManualPolicy = profiles.filter((p) => {
|
|
86
|
+
if (p.updatePolicy === "manual") {
|
|
87
|
+
manualPolicyIds.push(p.tenantId);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
});
|
|
92
|
+
if (!configRepo) {
|
|
93
|
+
if (manualPolicyIds.length > 0 && onManualTenantsSkipped) {
|
|
94
|
+
onManualTenantsSkipped([...new Set(manualPolicyIds)], imageTag);
|
|
95
|
+
}
|
|
96
|
+
return nonManualPolicy;
|
|
97
|
+
}
|
|
98
|
+
const configManualIds = [];
|
|
99
|
+
const results = await Promise.all(nonManualPolicy.map(async (p) => {
|
|
100
|
+
const tenantCfg = await configRepo.get(p.tenantId);
|
|
101
|
+
if (tenantCfg && tenantCfg.mode === "manual") {
|
|
102
|
+
configManualIds.push(p.tenantId);
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
return p;
|
|
106
|
+
}));
|
|
107
|
+
const allManualIds = [...manualPolicyIds, ...configManualIds];
|
|
108
|
+
if (allManualIds.length > 0 && onManualTenantsSkipped) {
|
|
109
|
+
onManualTenantsSkipped([...new Set(allManualIds)], imageTag);
|
|
110
|
+
}
|
|
111
|
+
return results.filter((p) => p !== null);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// Tests
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
describe("initFleetUpdater — onManualTenantsSkipped", () => {
|
|
118
|
+
it("callback fires with tenant IDs of manual-mode tenants (policy-based)", async () => {
|
|
119
|
+
const profiles = [
|
|
120
|
+
makeProfileWithFields({ id: "b1", tenantId: "t-manual", updatePolicy: "manual" }),
|
|
121
|
+
makeProfileWithFields({ id: "b2", tenantId: "t-auto", updatePolicy: "auto" }),
|
|
122
|
+
];
|
|
123
|
+
const profileRepo = makeProfileRepo(profiles);
|
|
124
|
+
const onManualTenantsSkipped = vi.fn();
|
|
125
|
+
const orchestrator = new RolloutOrchestrator({
|
|
126
|
+
updater: makeMockUpdater(),
|
|
127
|
+
snapshotManager: makeMockSnapshotManager(),
|
|
128
|
+
strategy: makeMockStrategy(),
|
|
129
|
+
getUpdatableProfiles: buildGetUpdatableProfiles(profileRepo, undefined, onManualTenantsSkipped),
|
|
130
|
+
});
|
|
131
|
+
await orchestrator.rollout();
|
|
132
|
+
expect(onManualTenantsSkipped).toHaveBeenCalledWith(["t-manual"], "v1.2.3");
|
|
133
|
+
});
|
|
134
|
+
it("callback deduplicates tenant IDs", async () => {
|
|
135
|
+
const profiles = [
|
|
136
|
+
makeProfileWithFields({ id: "b1", tenantId: "t-dup", updatePolicy: "manual" }),
|
|
137
|
+
makeProfileWithFields({ id: "b2", tenantId: "t-dup", updatePolicy: "manual" }),
|
|
138
|
+
makeProfileWithFields({ id: "b3", tenantId: "t-auto", updatePolicy: "auto" }),
|
|
139
|
+
];
|
|
140
|
+
const profileRepo = makeProfileRepo(profiles);
|
|
141
|
+
const onManualTenantsSkipped = vi.fn();
|
|
142
|
+
const orchestrator = new RolloutOrchestrator({
|
|
143
|
+
updater: makeMockUpdater(),
|
|
144
|
+
snapshotManager: makeMockSnapshotManager(),
|
|
145
|
+
strategy: makeMockStrategy(),
|
|
146
|
+
getUpdatableProfiles: buildGetUpdatableProfiles(profileRepo, undefined, onManualTenantsSkipped),
|
|
147
|
+
});
|
|
148
|
+
await orchestrator.rollout();
|
|
149
|
+
expect(onManualTenantsSkipped).toHaveBeenCalledWith(["t-dup"], "v1.2.3");
|
|
150
|
+
});
|
|
151
|
+
it("callback not called when no manual tenants exist", async () => {
|
|
152
|
+
const profiles = [
|
|
153
|
+
makeProfileWithFields({ id: "b1", tenantId: "t1", updatePolicy: "auto" }),
|
|
154
|
+
makeProfileWithFields({ id: "b2", tenantId: "t2", updatePolicy: "auto" }),
|
|
155
|
+
];
|
|
156
|
+
const profileRepo = makeProfileRepo(profiles);
|
|
157
|
+
const onManualTenantsSkipped = vi.fn();
|
|
158
|
+
const orchestrator = new RolloutOrchestrator({
|
|
159
|
+
updater: makeMockUpdater(),
|
|
160
|
+
snapshotManager: makeMockSnapshotManager(),
|
|
161
|
+
strategy: makeMockStrategy(),
|
|
162
|
+
getUpdatableProfiles: buildGetUpdatableProfiles(profileRepo, undefined, onManualTenantsSkipped),
|
|
163
|
+
});
|
|
164
|
+
await orchestrator.rollout();
|
|
165
|
+
expect(onManualTenantsSkipped).not.toHaveBeenCalled();
|
|
166
|
+
});
|
|
167
|
+
it("callback fires with config-repo manual tenants when configRepo is provided", async () => {
|
|
168
|
+
const profiles = [
|
|
169
|
+
makeProfileWithFields({ id: "b1", tenantId: "t-cfg-manual", updatePolicy: "auto" }),
|
|
170
|
+
makeProfileWithFields({ id: "b2", tenantId: "t-cfg-auto", updatePolicy: "auto" }),
|
|
171
|
+
];
|
|
172
|
+
const profileRepo = makeProfileRepo(profiles);
|
|
173
|
+
const configRepo = makeConfigRepo({
|
|
174
|
+
"t-cfg-manual": { mode: "manual", preferredHourUtc: 3 },
|
|
175
|
+
});
|
|
176
|
+
const onManualTenantsSkipped = vi.fn();
|
|
177
|
+
const orchestrator = new RolloutOrchestrator({
|
|
178
|
+
updater: makeMockUpdater(),
|
|
179
|
+
snapshotManager: makeMockSnapshotManager(),
|
|
180
|
+
strategy: makeMockStrategy(),
|
|
181
|
+
getUpdatableProfiles: buildGetUpdatableProfiles(profileRepo, configRepo, onManualTenantsSkipped),
|
|
182
|
+
});
|
|
183
|
+
await orchestrator.rollout();
|
|
184
|
+
expect(onManualTenantsSkipped).toHaveBeenCalledWith(["t-cfg-manual"], "v1.2.3");
|
|
185
|
+
});
|
|
186
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|