@wopr-network/platform-core 1.29.0 → 1.31.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.
@@ -5,18 +5,21 @@
5
5
  * Do NOT put the interval inside this class.
6
6
  */
7
7
  import type { EmailClient } from "./client.js";
8
+ import type { HandlebarsRenderer } from "./handlebars-renderer.js";
8
9
  import type { INotificationPreferencesRepository, INotificationQueueRepository } from "./notification-repository-types.js";
9
10
  export interface NotificationWorkerConfig {
10
11
  queue: INotificationQueueRepository;
11
12
  emailClient: EmailClient;
12
13
  preferences: INotificationPreferencesRepository;
13
14
  batchSize?: number;
15
+ handlebarsRenderer?: HandlebarsRenderer;
14
16
  }
15
17
  export declare class NotificationWorker {
16
18
  private readonly queue;
17
19
  private readonly emailClient;
18
20
  private readonly preferences;
19
21
  private readonly batchSize;
22
+ private readonly handlebarsRenderer;
20
23
  constructor(config: NotificationWorkerConfig);
21
24
  /** Process one batch of pending notifications. Returns count of processed items. */
22
25
  processBatch(): Promise<number>;
@@ -35,17 +35,21 @@ const PREF_MAP = {
35
35
  "dividend-weekly-digest": "billing_receipts",
36
36
  "role-changed": "account_role_changes",
37
37
  "team-invite": "account_team_invites",
38
+ "fleet-update-available": "fleet_updates",
39
+ "fleet-update-complete": "fleet_updates",
38
40
  };
39
41
  export class NotificationWorker {
40
42
  queue;
41
43
  emailClient;
42
44
  preferences;
43
45
  batchSize;
46
+ handlebarsRenderer;
44
47
  constructor(config) {
45
48
  this.queue = config.queue;
46
49
  this.emailClient = config.emailClient;
47
50
  this.preferences = config.preferences;
48
51
  this.batchSize = config.batchSize ?? 10;
52
+ this.handlebarsRenderer = config.handlebarsRenderer;
49
53
  }
50
54
  /** Process one batch of pending notifications. Returns count of processed items. */
51
55
  async processBatch() {
@@ -74,8 +78,14 @@ export class NotificationWorker {
74
78
  continue;
75
79
  }
76
80
  }
77
- // Render the template
78
- const rendered = renderNotificationTemplate(notif.template, data);
81
+ // Try DB-driven Handlebars first, fall back to code templates
82
+ let rendered = null;
83
+ if (this.handlebarsRenderer) {
84
+ rendered = await this.handlebarsRenderer.render(notif.template, data);
85
+ }
86
+ if (!rendered) {
87
+ rendered = renderNotificationTemplate(notif.template, data);
88
+ }
79
89
  // Send via email client
80
90
  await this.emailClient.send({
81
91
  to: email,
@@ -7,6 +7,8 @@ export interface BotFleetEvent {
7
7
  botId: string;
8
8
  tenantId: string;
9
9
  timestamp: string;
10
+ /** Image tag or version string, when available (e.g. from update events). */
11
+ version?: string;
10
12
  }
11
13
  export interface NodeFleetEvent {
12
14
  type: NodeEventType;
@@ -0,0 +1,13 @@
1
+ import type { INotificationPreferencesRepository } from "../email/notification-repository-types.js";
2
+ import type { NotificationService } from "../email/notification-service.js";
3
+ import type { FleetEventEmitter } from "./fleet-event-emitter.js";
4
+ export interface FleetNotificationListenerDeps {
5
+ eventEmitter: FleetEventEmitter;
6
+ notificationService: NotificationService;
7
+ preferences: INotificationPreferencesRepository;
8
+ /** Resolve tenant ID to owner email. Return null if no email found. */
9
+ resolveEmail: (tenantId: string) => Promise<string | null>;
10
+ /** Debounce window in ms before sending summary email. Default 60_000. */
11
+ debounceMs?: number;
12
+ }
13
+ export declare function initFleetNotificationListener(deps: FleetNotificationListenerDeps): () => Promise<void>;
@@ -0,0 +1,67 @@
1
+ import { logger } from "../config/logger.js";
2
+ export function initFleetNotificationListener(deps) {
3
+ const { eventEmitter, notificationService, preferences, resolveEmail } = deps;
4
+ const debounceMs = deps.debounceMs ?? 60_000;
5
+ const pending = new Map();
6
+ async function flush(tenantId) {
7
+ const rollout = pending.get(tenantId);
8
+ if (!rollout)
9
+ return;
10
+ pending.delete(tenantId);
11
+ try {
12
+ const prefs = await preferences.get(tenantId);
13
+ if (!prefs.fleet_updates)
14
+ return;
15
+ const email = await resolveEmail(tenantId);
16
+ if (!email) {
17
+ logger.warn("Fleet notification skipped: no email for tenant", { tenantId });
18
+ return;
19
+ }
20
+ notificationService.notifyFleetUpdateComplete(tenantId, email, rollout.version, rollout.succeeded, rollout.failed);
21
+ }
22
+ catch (err) {
23
+ logger.error("Fleet notification flush error", { err, tenantId });
24
+ }
25
+ }
26
+ const unsubscribe = eventEmitter.subscribe((event) => {
27
+ if (!("tenantId" in event))
28
+ return;
29
+ const botEvent = event;
30
+ if (botEvent.type !== "bot.updated" && botEvent.type !== "bot.update_failed")
31
+ return;
32
+ let rollout = pending.get(botEvent.tenantId);
33
+ if (!rollout) {
34
+ rollout = {
35
+ tenantId: botEvent.tenantId,
36
+ version: botEvent.version ?? "latest",
37
+ succeeded: 0,
38
+ failed: 0,
39
+ timer: setTimeout(() => flush(botEvent.tenantId), debounceMs),
40
+ };
41
+ pending.set(botEvent.tenantId, rollout);
42
+ }
43
+ else {
44
+ // Reset timer on each new event (sliding window)
45
+ clearTimeout(rollout.timer);
46
+ rollout.timer = setTimeout(() => flush(botEvent.tenantId), debounceMs);
47
+ if (botEvent.version)
48
+ rollout.version = botEvent.version;
49
+ }
50
+ if (botEvent.type === "bot.updated") {
51
+ rollout.succeeded++;
52
+ }
53
+ else {
54
+ rollout.failed++;
55
+ }
56
+ });
57
+ return async () => {
58
+ unsubscribe();
59
+ const flushes = [];
60
+ for (const [tenantId, rollout] of pending) {
61
+ clearTimeout(rollout.timer);
62
+ flushes.push(flush(tenantId));
63
+ }
64
+ pending.clear();
65
+ await Promise.allSettled(flushes);
66
+ };
67
+ }
@@ -1,4 +1,6 @@
1
1
  export * from "./drizzle-tenant-update-config-repository.js";
2
+ export type { FleetNotificationListenerDeps } from "./fleet-notification-listener.js";
3
+ export { initFleetNotificationListener } from "./fleet-notification-listener.js";
2
4
  export * from "./init-fleet-updater.js";
3
5
  export * from "./repository-types.js";
4
6
  export * from "./rollout-orchestrator.js";
@@ -1,4 +1,5 @@
1
1
  export * from "./drizzle-tenant-update-config-repository.js";
2
+ export { initFleetNotificationListener } from "./fleet-notification-listener.js";
2
3
  export * from "./init-fleet-updater.js";
3
4
  export * from "./repository-types.js";
4
5
  export * from "./rollout-orchestrator.js";
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import type Docker from "dockerode";
14
14
  import type { IBotProfileRepository } from "./bot-profile-repository.js";
15
- import type { FleetEventEmitter } from "./fleet-event-emitter.js";
15
+ import { FleetEventEmitter } from "./fleet-event-emitter.js";
16
16
  import type { FleetManager } from "./fleet-manager.js";
17
17
  import { ImagePoller } from "./image-poller.js";
18
18
  import type { IProfileStore } from "./profile-store.js";
@@ -46,6 +46,8 @@ export interface FleetUpdaterHandle {
46
46
  updater: ContainerUpdater;
47
47
  orchestrator: RolloutOrchestrator;
48
48
  snapshotManager: VolumeSnapshotManager;
49
+ /** Fleet event emitter for subscribing to bot/node lifecycle events */
50
+ eventEmitter: FleetEventEmitter;
49
51
  /** Stop the poller and wait for any active rollout to finish */
50
52
  stop: () => Promise<void>;
51
53
  }
@@ -11,6 +11,7 @@
11
11
  * all bots need updating.
12
12
  */
13
13
  import { logger } from "../config/logger.js";
14
+ import { FleetEventEmitter } from "./fleet-event-emitter.js";
14
15
  import { ImagePoller } from "./image-poller.js";
15
16
  import { RolloutOrchestrator } from "./rollout-orchestrator.js";
16
17
  import { createRolloutStrategy } from "./rollout-strategy.js";
@@ -29,7 +30,8 @@ import { VolumeSnapshotManager } from "./volume-snapshot-manager.js";
29
30
  * @param config - Optional pipeline configuration
30
31
  */
31
32
  export function initFleetUpdater(docker, fleet, profileStore, profileRepo, config = {}) {
32
- const { strategy: strategyType = "rolling-wave", strategyOptions, snapshotDir = "/data/fleet/snapshots", onBotUpdated, onRolloutComplete, configRepo, eventEmitter, } = config;
33
+ const { strategy: strategyType = "rolling-wave", strategyOptions, snapshotDir = "/data/fleet/snapshots", onBotUpdated, onRolloutComplete, configRepo, eventEmitter: configEventEmitter, } = config;
34
+ const emitter = configEventEmitter ?? new FleetEventEmitter();
33
35
  const poller = new ImagePoller(docker, profileStore);
34
36
  const updater = new ContainerUpdater(docker, profileStore, fleet, poller);
35
37
  const snapshotManager = new VolumeSnapshotManager(docker, snapshotDir);
@@ -54,16 +56,28 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
54
56
  return results.filter((p) => p !== null);
55
57
  },
56
58
  onBotUpdated: (result) => {
57
- // Emit fleet events if emitter is provided
58
- if (eventEmitter) {
59
- eventEmitter.emit({
59
+ // Fire-and-forget: resolve tenantId + emit event asynchronously
60
+ // The orchestrator callback is sync (void return) — async work must not block rollout progress
61
+ void (async () => {
62
+ let tenantId = "";
63
+ try {
64
+ const profile = await profileRepo.get(result.botId);
65
+ if (profile)
66
+ tenantId = profile.tenantId;
67
+ }
68
+ catch {
69
+ // Best-effort — event still fires with empty tenantId
70
+ }
71
+ // Extract version tag from image name (e.g. "ghcr.io/org/image:v1.2.3" → "v1.2.3")
72
+ const version = result.newImage.includes(":") ? (result.newImage.split(":").pop() ?? "latest") : "latest";
73
+ emitter.emit({
60
74
  type: result.success ? "bot.updated" : "bot.update_failed",
61
75
  botId: result.botId,
62
- tenantId: "",
76
+ tenantId,
63
77
  timestamp: new Date().toISOString(),
78
+ version,
64
79
  });
65
- }
66
- // Chain user-provided callback
80
+ })();
67
81
  onBotUpdated?.(result);
68
82
  },
69
83
  onRolloutComplete: (result) => {
@@ -96,6 +110,7 @@ export function initFleetUpdater(docker, fleet, profileStore, profileRepo, confi
96
110
  updater,
97
111
  orchestrator,
98
112
  snapshotManager,
113
+ eventEmitter: emitter,
99
114
  stop: async () => {
100
115
  poller.stop();
101
116
  // Wait for any in-flight rollout to complete before returning
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wopr-network/platform-core",
3
- "version": "1.29.0",
3
+ "version": "1.31.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -7,17 +7,20 @@
7
7
 
8
8
  import { logger } from "../config/logger.js";
9
9
  import type { EmailClient } from "./client.js";
10
+ import type { HandlebarsRenderer } from "./handlebars-renderer.js";
10
11
  import type {
11
12
  INotificationPreferencesRepository,
12
13
  INotificationQueueRepository,
13
14
  } from "./notification-repository-types.js";
14
15
  import { renderNotificationTemplate, type TemplateName } from "./notification-templates.js";
16
+ import type { TemplateResult } from "./templates.js";
15
17
 
16
18
  export interface NotificationWorkerConfig {
17
19
  queue: INotificationQueueRepository;
18
20
  emailClient: EmailClient;
19
21
  preferences: INotificationPreferencesRepository;
20
22
  batchSize?: number;
23
+ handlebarsRenderer?: HandlebarsRenderer;
21
24
  }
22
25
 
23
26
  /** Templates that bypass user preference checks — always sent. */
@@ -50,6 +53,8 @@ const PREF_MAP: Record<string, string> = {
50
53
  "dividend-weekly-digest": "billing_receipts",
51
54
  "role-changed": "account_role_changes",
52
55
  "team-invite": "account_team_invites",
56
+ "fleet-update-available": "fleet_updates",
57
+ "fleet-update-complete": "fleet_updates",
53
58
  };
54
59
 
55
60
  export class NotificationWorker {
@@ -57,12 +62,14 @@ export class NotificationWorker {
57
62
  private readonly emailClient: EmailClient;
58
63
  private readonly preferences: INotificationPreferencesRepository;
59
64
  private readonly batchSize: number;
65
+ private readonly handlebarsRenderer: HandlebarsRenderer | undefined;
60
66
 
61
67
  constructor(config: NotificationWorkerConfig) {
62
68
  this.queue = config.queue;
63
69
  this.emailClient = config.emailClient;
64
70
  this.preferences = config.preferences;
65
71
  this.batchSize = config.batchSize ?? 10;
72
+ this.handlebarsRenderer = config.handlebarsRenderer;
66
73
  }
67
74
 
68
75
  /** Process one batch of pending notifications. Returns count of processed items. */
@@ -96,8 +103,14 @@ export class NotificationWorker {
96
103
  }
97
104
  }
98
105
 
99
- // Render the template
100
- const rendered = renderNotificationTemplate(notif.template as TemplateName, data);
106
+ // Try DB-driven Handlebars first, fall back to code templates
107
+ let rendered: TemplateResult | null = null;
108
+ if (this.handlebarsRenderer) {
109
+ rendered = await this.handlebarsRenderer.render(notif.template, data);
110
+ }
111
+ if (!rendered) {
112
+ rendered = renderNotificationTemplate(notif.template as TemplateName, data);
113
+ }
101
114
 
102
115
  // Send via email client
103
116
  await this.emailClient.send({
@@ -26,6 +26,8 @@ export interface BotFleetEvent {
26
26
  botId: string;
27
27
  tenantId: string;
28
28
  timestamp: string;
29
+ /** Image tag or version string, when available (e.g. from update events). */
30
+ version?: string;
29
31
  }
30
32
 
31
33
  export interface NodeFleetEvent {
@@ -0,0 +1,95 @@
1
+ import { logger } from "../config/logger.js";
2
+ import type { INotificationPreferencesRepository } from "../email/notification-repository-types.js";
3
+ import type { NotificationService } from "../email/notification-service.js";
4
+ import type { BotFleetEvent, FleetEventEmitter } from "./fleet-event-emitter.js";
5
+
6
+ export interface FleetNotificationListenerDeps {
7
+ eventEmitter: FleetEventEmitter;
8
+ notificationService: NotificationService;
9
+ preferences: INotificationPreferencesRepository;
10
+ /** Resolve tenant ID to owner email. Return null if no email found. */
11
+ resolveEmail: (tenantId: string) => Promise<string | null>;
12
+ /** Debounce window in ms before sending summary email. Default 60_000. */
13
+ debounceMs?: number;
14
+ }
15
+
16
+ interface PendingRollout {
17
+ tenantId: string;
18
+ version: string;
19
+ succeeded: number;
20
+ failed: number;
21
+ timer: ReturnType<typeof setTimeout>;
22
+ }
23
+
24
+ export function initFleetNotificationListener(deps: FleetNotificationListenerDeps): () => Promise<void> {
25
+ const { eventEmitter, notificationService, preferences, resolveEmail } = deps;
26
+ const debounceMs = deps.debounceMs ?? 60_000;
27
+ const pending = new Map<string, PendingRollout>();
28
+
29
+ async function flush(tenantId: string): Promise<void> {
30
+ const rollout = pending.get(tenantId);
31
+ if (!rollout) return;
32
+ pending.delete(tenantId);
33
+
34
+ try {
35
+ const prefs = await preferences.get(tenantId);
36
+ if (!prefs.fleet_updates) return;
37
+
38
+ const email = await resolveEmail(tenantId);
39
+ if (!email) {
40
+ logger.warn("Fleet notification skipped: no email for tenant", { tenantId });
41
+ return;
42
+ }
43
+
44
+ notificationService.notifyFleetUpdateComplete(
45
+ tenantId,
46
+ email,
47
+ rollout.version,
48
+ rollout.succeeded,
49
+ rollout.failed,
50
+ );
51
+ } catch (err) {
52
+ logger.error("Fleet notification flush error", { err, tenantId });
53
+ }
54
+ }
55
+
56
+ const unsubscribe = eventEmitter.subscribe((event) => {
57
+ if (!("tenantId" in event)) return;
58
+ const botEvent = event as BotFleetEvent;
59
+ if (botEvent.type !== "bot.updated" && botEvent.type !== "bot.update_failed") return;
60
+
61
+ let rollout = pending.get(botEvent.tenantId);
62
+ if (!rollout) {
63
+ rollout = {
64
+ tenantId: botEvent.tenantId,
65
+ version: botEvent.version ?? "latest",
66
+ succeeded: 0,
67
+ failed: 0,
68
+ timer: setTimeout(() => flush(botEvent.tenantId), debounceMs),
69
+ };
70
+ pending.set(botEvent.tenantId, rollout);
71
+ } else {
72
+ // Reset timer on each new event (sliding window)
73
+ clearTimeout(rollout.timer);
74
+ rollout.timer = setTimeout(() => flush(botEvent.tenantId), debounceMs);
75
+ if (botEvent.version) rollout.version = botEvent.version;
76
+ }
77
+
78
+ if (botEvent.type === "bot.updated") {
79
+ rollout.succeeded++;
80
+ } else {
81
+ rollout.failed++;
82
+ }
83
+ });
84
+
85
+ return async () => {
86
+ unsubscribe();
87
+ const flushes: Promise<void>[] = [];
88
+ for (const [tenantId, rollout] of pending) {
89
+ clearTimeout(rollout.timer);
90
+ flushes.push(flush(tenantId));
91
+ }
92
+ pending.clear();
93
+ await Promise.allSettled(flushes);
94
+ };
95
+ }
@@ -1,4 +1,6 @@
1
1
  export * from "./drizzle-tenant-update-config-repository.js";
2
+ export type { FleetNotificationListenerDeps } from "./fleet-notification-listener.js";
3
+ export { initFleetNotificationListener } from "./fleet-notification-listener.js";
2
4
  export * from "./init-fleet-updater.js";
3
5
  export * from "./repository-types.js";
4
6
  export * from "./rollout-orchestrator.js";
@@ -14,7 +14,7 @@
14
14
  import type Docker from "dockerode";
15
15
  import { logger } from "../config/logger.js";
16
16
  import type { IBotProfileRepository } from "./bot-profile-repository.js";
17
- import type { FleetEventEmitter } from "./fleet-event-emitter.js";
17
+ import { FleetEventEmitter } from "./fleet-event-emitter.js";
18
18
  import type { FleetManager } from "./fleet-manager.js";
19
19
  import { ImagePoller } from "./image-poller.js";
20
20
  import type { IProfileStore } from "./profile-store.js";
@@ -46,6 +46,8 @@ export interface FleetUpdaterHandle {
46
46
  updater: ContainerUpdater;
47
47
  orchestrator: RolloutOrchestrator;
48
48
  snapshotManager: VolumeSnapshotManager;
49
+ /** Fleet event emitter for subscribing to bot/node lifecycle events */
50
+ eventEmitter: FleetEventEmitter;
49
51
  /** Stop the poller and wait for any active rollout to finish */
50
52
  stop: () => Promise<void>;
51
53
  }
@@ -76,9 +78,11 @@ export function initFleetUpdater(
76
78
  onBotUpdated,
77
79
  onRolloutComplete,
78
80
  configRepo,
79
- eventEmitter,
81
+ eventEmitter: configEventEmitter,
80
82
  } = config;
81
83
 
84
+ const emitter = configEventEmitter ?? new FleetEventEmitter();
85
+
82
86
  const poller = new ImagePoller(docker, profileStore);
83
87
  const updater = new ContainerUpdater(docker, profileStore, fleet, poller);
84
88
  const snapshotManager = new VolumeSnapshotManager(docker, snapshotDir);
@@ -106,16 +110,28 @@ export function initFleetUpdater(
106
110
  return results.filter((p) => p !== null);
107
111
  },
108
112
  onBotUpdated: (result) => {
109
- // Emit fleet events if emitter is provided
110
- if (eventEmitter) {
111
- eventEmitter.emit({
113
+ // Fire-and-forget: resolve tenantId + emit event asynchronously
114
+ // The orchestrator callback is sync (void return) — async work must not block rollout progress
115
+ void (async () => {
116
+ let tenantId = "";
117
+ try {
118
+ const profile = await profileRepo.get(result.botId);
119
+ if (profile) tenantId = profile.tenantId;
120
+ } catch {
121
+ // Best-effort — event still fires with empty tenantId
122
+ }
123
+
124
+ // Extract version tag from image name (e.g. "ghcr.io/org/image:v1.2.3" → "v1.2.3")
125
+ const version = result.newImage.includes(":") ? (result.newImage.split(":").pop() ?? "latest") : "latest";
126
+
127
+ emitter.emit({
112
128
  type: result.success ? "bot.updated" : "bot.update_failed",
113
129
  botId: result.botId,
114
- tenantId: "",
130
+ tenantId,
115
131
  timestamp: new Date().toISOString(),
132
+ version,
116
133
  });
117
- }
118
- // Chain user-provided callback
134
+ })();
119
135
  onBotUpdated?.(result);
120
136
  },
121
137
  onRolloutComplete: (result) => {
@@ -152,6 +168,7 @@ export function initFleetUpdater(
152
168
  updater,
153
169
  orchestrator,
154
170
  snapshotManager,
171
+ eventEmitter: emitter,
155
172
  stop: async () => {
156
173
  poller.stop();
157
174
  // Wait for any in-flight rollout to complete before returning