notifkit 0.1.3 → 0.1.5

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 (96) hide show
  1. package/README.md +179 -152
  2. package/dist/index.d.mts +193 -129
  3. package/dist/index.d.mts.map +1 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{main-DtHWhueo.mjs → main-40zwq6b0.mjs} +28 -3
  7. package/dist/{main-DtHWhueo.mjs.map → main-40zwq6b0.mjs.map} +1 -1
  8. package/dist/{main-DyfbnJc3.mjs → main-BFre2-HQ.mjs} +2 -2
  9. package/dist/{main-DyfbnJc3.mjs.map → main-BFre2-HQ.mjs.map} +1 -1
  10. package/dist/{main-CAH0_Q6d.mjs → main-BNJtzY61.mjs} +3 -3
  11. package/dist/main-BNJtzY61.mjs.map +1 -0
  12. package/dist/{main-B561M1d3.mjs → main-BOPMYqsW.mjs} +2 -2
  13. package/dist/{main-B561M1d3.mjs.map → main-BOPMYqsW.mjs.map} +1 -1
  14. package/dist/{main-CCfc45ev.mjs → main-CiigNpsP.mjs} +7 -4
  15. package/dist/main-CiigNpsP.mjs.map +1 -0
  16. package/dist/{main-Ce9dcrsg.mjs → main-DeNFQ-UL.mjs} +6 -3
  17. package/dist/{main-Ce9dcrsg.mjs.map → main-DeNFQ-UL.mjs.map} +1 -1
  18. package/dist/{main-B-jwm8ED.mjs → main-DmCPcxOc.mjs} +2 -2
  19. package/dist/{main-B-jwm8ED.mjs.map → main-DmCPcxOc.mjs.map} +1 -1
  20. package/dist/{main-C45e7grq.mjs → main-DvgJSm11.mjs} +2 -2
  21. package/dist/{main-C45e7grq.mjs.map → main-DvgJSm11.mjs.map} +1 -1
  22. package/dist/{src-C-PfEDMY.mjs → src-vG79L-8m.mjs} +57 -26
  23. package/dist/src-vG79L-8m.mjs.map +1 -0
  24. package/drizzle/0002_wide_colleen_wing.sql +2 -0
  25. package/drizzle/0003_skinny_daimon_hellstrom.sql +1 -0
  26. package/drizzle/0004_pretty_bruce_banner.sql +1 -0
  27. package/drizzle/meta/0002_snapshot.json +1460 -0
  28. package/drizzle/meta/0003_snapshot.json +1460 -0
  29. package/drizzle/meta/0004_snapshot.json +1470 -0
  30. package/drizzle/meta/_journal.json +21 -0
  31. package/package.json +7 -1
  32. package/scripts/create-project.mjs +61 -0
  33. package/src/client.ts +412 -0
  34. package/src/config/index.ts +107 -0
  35. package/src/contracts/common.ts +28 -0
  36. package/src/contracts/envelope.ts +31 -0
  37. package/src/contracts/events/notification-ai-pending.ts +18 -0
  38. package/src/contracts/events/notification-canceled.ts +7 -0
  39. package/src/contracts/events/notification-created.ts +14 -0
  40. package/src/contracts/events/notification-delivered.ts +17 -0
  41. package/src/contracts/events/notification-dispatched.ts +45 -0
  42. package/src/contracts/events/notification-enriched.ts +46 -0
  43. package/src/contracts/events/notification-failed.ts +19 -0
  44. package/src/contracts/events/notification-requested.ts +36 -0
  45. package/src/contracts/events/notification-scheduled.ts +9 -0
  46. package/src/contracts/events/notification-skipped.ts +9 -0
  47. package/src/contracts/helpers.ts +21 -0
  48. package/src/contracts/index.ts +46 -0
  49. package/src/contracts/metadata.ts +10 -0
  50. package/src/contracts/registry.ts +88 -0
  51. package/src/contracts/sdk.ts +242 -0
  52. package/src/contracts/streams.ts +62 -0
  53. package/src/db/index.ts +69 -0
  54. package/src/db/schema.ts +412 -0
  55. package/src/idempotency/index.ts +50 -0
  56. package/src/index.ts +19 -0
  57. package/src/logger/index.ts +60 -0
  58. package/src/metrics/index.ts +53 -0
  59. package/src/queue/index.ts +501 -0
  60. package/src/rate-limiter/index.ts +210 -0
  61. package/src/redis/index.ts +89 -0
  62. package/src/repositories/index.ts +1246 -0
  63. package/src/server.ts +277 -0
  64. package/src/services/ai/main.ts +404 -0
  65. package/src/services/api/handlers.ts +1734 -0
  66. package/src/services/api/http.ts +64 -0
  67. package/src/services/api/main.ts +693 -0
  68. package/src/services/api/router.ts +82 -0
  69. package/src/services/delivery/main.ts +842 -0
  70. package/src/services/delivery/throttle.ts +71 -0
  71. package/src/services/engine/main.ts +827 -0
  72. package/src/services/enricher/main.ts +594 -0
  73. package/src/services/events/main.ts +365 -0
  74. package/src/services/scheduler/main.ts +319 -0
  75. package/src/services/workflow/main.ts +627 -0
  76. package/src/shared/batch-processor.ts +67 -0
  77. package/src/shared/cache.ts +47 -0
  78. package/src/shared/circuit-breaker.ts +74 -0
  79. package/src/shared/dataloader.ts +41 -0
  80. package/src/shared/events.ts +3 -0
  81. package/src/shared/index.ts +39 -0
  82. package/src/shared/semaphore.ts +33 -0
  83. package/src/shared/utils.ts +64 -0
  84. package/src/templates/cache.ts +32 -0
  85. package/src/templates/index.ts +69 -0
  86. package/src/templates/render.ts +128 -0
  87. package/src/transport/index.ts +96 -0
  88. package/src/unsubscribe/index.ts +127 -0
  89. package/src/workers/health.ts +31 -0
  90. package/src/workers/index.ts +266 -0
  91. package/src/workflows/index.ts +2 -0
  92. package/src/workflows/registry.ts +21 -0
  93. package/src/workflows/sdk.ts +106 -0
  94. package/dist/main-CAH0_Q6d.mjs.map +0 -1
  95. package/dist/main-CCfc45ev.mjs.map +0 -1
  96. package/dist/src-C-PfEDMY.mjs.map +0 -1
@@ -0,0 +1,627 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { loadEnv, readBaseConfig } from "@/index.js";
3
+ import { createLogger } from "@/index.js";
4
+ import { RedisClient, type Redis } from "@/index.js";
5
+ import {
6
+ StreamConsumer,
7
+ PendingMessageScanner,
8
+ StreamProducer,
9
+ type StreamMessage,
10
+ } from "@/index.js";
11
+ import { BaseWorker } from "@/index.js";
12
+ import { STREAMS, CONSUMER_GROUPS, buildStreamEvent } from "@/index.js";
13
+ import { type StreamName } from "@/contracts/streams.js";
14
+ import { createDatabase } from "@/db/index.js";
15
+ import {
16
+ workflowInstances,
17
+ workflowSteps,
18
+ workflowWaiters,
19
+ workflowDefinitions,
20
+ } from "@/db/schema.js";
21
+ import { eq, and } from "drizzle-orm";
22
+ import {
23
+ workflowRegistry,
24
+ SuspendExecutionError,
25
+ buildStepNotifyPayload,
26
+ type WorkflowContext,
27
+ type WorkflowStepContext,
28
+ } from "@/workflows/index.js";
29
+ import {
30
+ type WorkerOptions,
31
+ LUA_SCHEDULER_POLL,
32
+ LUA_RELEASE_LOCK,
33
+ LUA_RENEW_LOCK,
34
+ } from "@/shared/index.js";
35
+ import { startHealthReporter } from "@/workers/index.js";
36
+
37
+ /** How long a workflow instance lock is held before it self-expires. */
38
+ const WORKFLOW_LOCK_TTL_SECONDS = 60;
39
+ /** Renew the lock well inside its TTL so long-running handlers keep it. */
40
+ const WORKFLOW_LOCK_RENEW_MS = (WORKFLOW_LOCK_TTL_SECONDS / 3) * 1000;
41
+ /** How long a claimed workflow timer stays invisible to other pollers. */
42
+ const WORKFLOW_TIMER_VISIBILITY_MS = 60_000;
43
+
44
+ loadEnv();
45
+ const config = readBaseConfig();
46
+ let logger: ReturnType<typeof createLogger>;
47
+ let redis: RedisClient;
48
+ let sql: any;
49
+ let db: any;
50
+
51
+ let consumer: StreamConsumer;
52
+ let pendingScanner: PendingMessageScanner;
53
+ let worker: BaseWorker;
54
+ let healthInterval: NodeJS.Timeout | null = null;
55
+ let pollInterval: NodeJS.Timeout | null = null;
56
+ let reaperInterval: NodeJS.Timeout | null = null;
57
+
58
+ let notificationProducer: StreamProducer;
59
+ let workflowProducer: StreamProducer;
60
+
61
+ export interface WorkflowWorkerOptions extends WorkerOptions {
62
+ redis: Redis;
63
+ db: any;
64
+ workflowProducer: any;
65
+ notificationProducer: any;
66
+ }
67
+
68
+ export class WorkflowWorker extends BaseWorker {
69
+ private readonly redisCli: Redis;
70
+ private readonly dbConn: any;
71
+ private readonly workflowProducer: any;
72
+ private readonly notificationProducer: any;
73
+
74
+ private eventBuffer: {
75
+ producer: any;
76
+ event: any;
77
+ resolve: (result?: { messageId: string; notificationId: string }) => void;
78
+ reject: (err: any) => void;
79
+ }[] = [];
80
+ private flushTimer: NodeJS.Timeout | null = null;
81
+
82
+ constructor(options: WorkflowWorkerOptions) {
83
+ super(options);
84
+ this.redisCli = options.redis;
85
+ this.dbConn = options.db;
86
+ this.workflowProducer = options.workflowProducer;
87
+ this.notificationProducer = options.notificationProducer;
88
+
89
+ this.flushTimer = setInterval(() => void this.flushWorkerBuffers(), 100);
90
+ }
91
+
92
+ override async stop(): Promise<void> {
93
+ if (this.flushTimer) {
94
+ clearInterval(this.flushTimer);
95
+ this.flushTimer = null;
96
+ }
97
+ await this.flushWorkerBuffers();
98
+ await super.stop();
99
+ }
100
+
101
+ private async flushWorkerBuffers(): Promise<void> {
102
+ if (this.eventBuffer.length === 0) return;
103
+
104
+ const events = this.eventBuffer;
105
+ this.eventBuffer = [];
106
+
107
+ try {
108
+ const byProducer = new Map<any, typeof events>();
109
+ for (const item of events) {
110
+ if (!byProducer.has(item.producer)) byProducer.set(item.producer, []);
111
+ byProducer.get(item.producer)!.push(item);
112
+ }
113
+
114
+ for (const [producer, batch] of byProducer) {
115
+ const { messageIds, eventIds } = await producer.publishBatch(batch.map((b) => b.event));
116
+ for (let i = 0; i < batch.length; i++) {
117
+ const mId = messageIds[i];
118
+ const eId = eventIds[i];
119
+ if (mId && eId) batch[i]!.resolve({ messageId: mId, notificationId: eId });
120
+ }
121
+ }
122
+ } catch (err: any) {
123
+ this.logger.error({ err }, "failed to flush workflow worker buffer");
124
+ for (const e of events) e.reject(err);
125
+ }
126
+ }
127
+
128
+ async process(message: StreamMessage): Promise<void> {
129
+ const { event } = message;
130
+ const publishPromises: Promise<void>[] = [];
131
+
132
+ if (event.type !== "workflow.triggered" && event.type !== "workflow.resumed") {
133
+ return;
134
+ }
135
+
136
+ const payload = event.payload as any;
137
+ const name = payload.name;
138
+ const instanceId = payload.instanceId;
139
+
140
+ if (!name || !instanceId || !payload.projectId) {
141
+ this.logger.warn("Missing name, instanceId, or projectId in workflow event");
142
+ return;
143
+ }
144
+
145
+ let handler = workflowRegistry.get(name);
146
+ if (!handler) {
147
+ // Fallback: check dynamic JSON workflows
148
+ const defRows = await this.dbConn
149
+ .select()
150
+ .from(workflowDefinitions)
151
+ .where(
152
+ and(
153
+ eq(workflowDefinitions.projectId, payload.projectId),
154
+ eq(workflowDefinitions.name, name),
155
+ ),
156
+ )
157
+ .limit(1);
158
+
159
+ if (defRows.length === 0) {
160
+ this.logger.warn(
161
+ { name, projectId: payload.projectId },
162
+ "No handler or dynamic definition found for workflow",
163
+ );
164
+ return;
165
+ }
166
+
167
+ const def = defRows[0];
168
+ handler = async ({ step }) => {
169
+ const steps = def.steps as any[];
170
+ for (const stepDef of steps) {
171
+ if (stepDef.action === "notify") {
172
+ // A payload target wins; naming none inherits the instance user.
173
+ await step.notify(stepDef.payload);
174
+ } else if (stepDef.action === "wait") {
175
+ await step.wait(stepDef.duration);
176
+ } else if (stepDef.action === "waitForEvent") {
177
+ await step.waitForEvent(stepDef.event, stepDef.options);
178
+ } else {
179
+ this.logger.warn(
180
+ { action: (stepDef as any)?.action, name },
181
+ "unknown workflow step action",
182
+ );
183
+ }
184
+ }
185
+ };
186
+ }
187
+
188
+ const lockKey = `lock:workflow:${instanceId}`;
189
+ const lockToken = randomUUID();
190
+ const acquired = await this.redisCli.set(
191
+ lockKey,
192
+ lockToken,
193
+ "EX",
194
+ WORKFLOW_LOCK_TTL_SECONDS,
195
+ "NX",
196
+ );
197
+ if (!acquired) {
198
+ this.logger.info({ instanceId }, "Workflow is locked by another process, skipping");
199
+ return;
200
+ }
201
+
202
+ // Keep the lock alive while the handler runs; without this a handler that
203
+ // outlives the TTL lets a second resume execute the same steps in parallel.
204
+ const renewTimer = setInterval(() => {
205
+ void this.redisCli
206
+ .eval(LUA_RENEW_LOCK, 1, lockKey, lockToken, String(WORKFLOW_LOCK_TTL_SECONDS))
207
+ .catch((err: unknown) => {
208
+ this.logger.warn({ err, instanceId }, "failed to renew workflow lock");
209
+ });
210
+ }, WORKFLOW_LOCK_RENEW_MS);
211
+
212
+ try {
213
+ let instance = (
214
+ await this.dbConn
215
+ .select()
216
+ .from(workflowInstances)
217
+ .where(eq(workflowInstances.id, instanceId))
218
+ .limit(1)
219
+ )[0];
220
+ if (!instance) {
221
+ const rows = await this.dbConn
222
+ .insert(workflowInstances)
223
+ .values({
224
+ id: instanceId,
225
+ projectId: payload.projectId,
226
+ name: name,
227
+ status: "pending",
228
+ input: payload.input || {},
229
+ })
230
+ .returning();
231
+ instance = rows[0]!;
232
+ }
233
+
234
+ if (instance.status !== "pending") {
235
+ this.logger.info({ instanceId }, "Workflow is not pending, skipping");
236
+ return;
237
+ }
238
+
239
+ await this.dbConn
240
+ .update(workflowInstances)
241
+ .set({ status: "running" })
242
+ .where(eq(workflowInstances.id, instanceId));
243
+
244
+ // Load existing steps
245
+ const existingSteps = await this.dbConn
246
+ .select()
247
+ .from(workflowSteps)
248
+ .where(eq(workflowSteps.instanceId, instanceId));
249
+ const stepOutputMap = new Map<string, any>();
250
+ for (const s of existingSteps) {
251
+ stepOutputMap.set(s.stepIndex, s.output);
252
+ }
253
+
254
+ let currentStepIndex = 0;
255
+
256
+ const stepProxy: WorkflowStepContext = {
257
+ notify: async (args) => {
258
+ const stepId = String(currentStepIndex++);
259
+ if (stepOutputMap.has(stepId)) return stepOutputMap.get(stepId);
260
+
261
+ // The step payload is the same shape as notify(), but the wire event
262
+ // is not — translate rather than spread.
263
+ const requested = buildStepNotifyPayload(
264
+ args,
265
+ instance!.input,
266
+ payload.projectId,
267
+ `wf-${instanceId}-${stepId}`,
268
+ );
269
+
270
+ const result = await new Promise<{ messageId: string; notificationId: string }>(
271
+ (resolve, reject) => {
272
+ this.eventBuffer.push({
273
+ producer: this.notificationProducer,
274
+ event: buildStreamEvent(
275
+ "notification.requested",
276
+ requested as unknown as Record<string, unknown>,
277
+ "workflow",
278
+ event.metadata.traceId,
279
+ ),
280
+ resolve: resolve as any,
281
+ reject,
282
+ });
283
+ },
284
+ );
285
+
286
+ const output = {
287
+ success: true,
288
+ messageId: result.messageId,
289
+ notificationId: result.notificationId,
290
+ };
291
+
292
+ await this.dbConn.insert(workflowSteps).values({
293
+ instanceId: instance!.id,
294
+ projectId: payload.projectId,
295
+ stepIndex: stepId,
296
+ action: "notify",
297
+ output,
298
+ });
299
+
300
+ return output;
301
+ },
302
+ wait: async (duration) => {
303
+ const stepId = String(currentStepIndex++);
304
+ if (stepOutputMap.has(stepId)) return;
305
+
306
+ // Simple duration parse (e.g. '2h' -> ms)
307
+ let ms = 0;
308
+ if (duration.endsWith("d")) ms = parseInt(duration) * 24 * 60 * 60 * 1000;
309
+ else if (duration.endsWith("h")) ms = parseInt(duration) * 60 * 60 * 1000;
310
+ else if (duration.endsWith("m")) ms = parseInt(duration) * 60 * 1000;
311
+ else if (duration.endsWith("s")) ms = parseInt(duration) * 1000;
312
+ else throw new Error(`Invalid wait duration: ${duration}`);
313
+
314
+ const resumeAt = Date.now() + ms;
315
+
316
+ // Persist the wake-up signal before committing the suspended state.
317
+ // If the process dies after this point the source event is retried;
318
+ // if it dies after the database write, the timer is already durable.
319
+ await this.redisCli.zadd(
320
+ "notif:workflow:timers",
321
+ resumeAt,
322
+ JSON.stringify({
323
+ instanceId: instance!.id,
324
+ name: instance!.name,
325
+ projectId: payload.projectId,
326
+ input: instance!.input,
327
+ }),
328
+ );
329
+
330
+ await this.dbConn.insert(workflowSteps).values({
331
+ instanceId: instance!.id,
332
+ projectId: payload.projectId,
333
+ stepIndex: stepId,
334
+ action: "wait",
335
+ output: { scheduledAt: resumeAt },
336
+ });
337
+
338
+ throw new SuspendExecutionError("wait", { duration });
339
+ },
340
+ waitForEvent: async (eventName, options) => {
341
+ const stepId = String(currentStepIndex++);
342
+ if (stepOutputMap.has(stepId)) {
343
+ const out = stepOutputMap.get(stepId);
344
+ if (out && typeof out === "object" && (out as any).timedOut === true) {
345
+ return null;
346
+ }
347
+ return out;
348
+ }
349
+
350
+ options = options || {};
351
+ options.timeout = options.timeout || "24h";
352
+ options.match = options.match || {};
353
+
354
+ let ms = 0;
355
+ if (options.timeout.endsWith("d")) ms = parseInt(options.timeout) * 24 * 60 * 60 * 1000;
356
+ else if (options.timeout.endsWith("h")) ms = parseInt(options.timeout) * 60 * 60 * 1000;
357
+ else if (options.timeout.endsWith("m")) ms = parseInt(options.timeout) * 60 * 1000;
358
+ else if (options.timeout.endsWith("s")) ms = parseInt(options.timeout) * 1000;
359
+ else throw new Error(`Invalid waitForEvent timeout: ${options.timeout}`);
360
+
361
+ const resumeAt = Date.now() + ms;
362
+
363
+ await this.redisCli.zadd(
364
+ "notif:workflow:timers",
365
+ resumeAt,
366
+ JSON.stringify({
367
+ instanceId: instance!.id,
368
+ name: instance!.name,
369
+ projectId: payload.projectId,
370
+ input: instance!.input,
371
+ isEventTimeout: true,
372
+ eventName,
373
+ stepId,
374
+ }),
375
+ );
376
+
377
+ // Register waiter
378
+ await this.dbConn.insert(workflowWaiters).values({
379
+ instanceId: instance!.id,
380
+ projectId: payload.projectId,
381
+ eventName: eventName,
382
+ matchCriteria: options.match,
383
+ expiresAt: new Date(resumeAt),
384
+ });
385
+
386
+ // Register step as pending event
387
+ await this.dbConn.insert(workflowSteps).values({
388
+ instanceId: instance!.id,
389
+ projectId: payload.projectId,
390
+ stepIndex: stepId,
391
+ action: "waitForEvent",
392
+ output: null, // this will be updated by event worker or timeout
393
+ });
394
+
395
+ throw new SuspendExecutionError("waitForEvent", { eventName });
396
+ },
397
+ run: async (stepName, fn) => {
398
+ const stepId = String(currentStepIndex++);
399
+ if (stepOutputMap.has(stepId)) return stepOutputMap.get(stepId);
400
+
401
+ const result = await fn();
402
+ await this.dbConn.insert(workflowSteps).values({
403
+ instanceId: instance!.id,
404
+ projectId: payload.projectId,
405
+ stepIndex: stepId,
406
+ action: "run",
407
+ output: result,
408
+ });
409
+ return result;
410
+ },
411
+ };
412
+
413
+ const ctx: WorkflowContext = {
414
+ step: stepProxy,
415
+ event: (instance!.input as any) || { user: { id: "unknown" } },
416
+ };
417
+
418
+ try {
419
+ await handler(ctx);
420
+ // If we reach here, workflow completed
421
+ await this.dbConn
422
+ .update(workflowInstances)
423
+ .set({ status: "completed" })
424
+ .where(eq(workflowInstances.id, instance!.id));
425
+ this.logger.info({ instanceId: instance!.id }, "Workflow completed successfully");
426
+ } catch (err: any) {
427
+ if (err instanceof SuspendExecutionError || err.name === "SuspendExecutionError") {
428
+ await this.dbConn
429
+ .update(workflowInstances)
430
+ .set({ status: "pending" })
431
+ .where(eq(workflowInstances.id, instance!.id));
432
+ this.logger.info({ instanceId: instance!.id, reason: err.reason }, "Workflow suspended");
433
+ } else {
434
+ this.logger.error({ err, instanceId: instance!.id }, "Workflow failed");
435
+ await this.dbConn
436
+ .update(workflowInstances)
437
+ .set({ status: "failed" })
438
+ .where(eq(workflowInstances.id, instance!.id));
439
+ }
440
+ }
441
+ } finally {
442
+ clearInterval(renewTimer);
443
+ // Compare-and-delete: never release a lock a later process re-acquired.
444
+ await this.redisCli.eval(LUA_RELEASE_LOCK, 1, lockKey, lockToken);
445
+ }
446
+
447
+ await Promise.all(publishPromises);
448
+ }
449
+ }
450
+
451
+ export function __injectForTests(r: any, d: any, wp: any, np: any) {
452
+ redis = r;
453
+ db = d;
454
+ workflowProducer = wp;
455
+ notificationProducer = np;
456
+ }
457
+
458
+ export async function startWorkflowWorker() {
459
+ logger = createLogger({ name: "workflow-worker", level: config.LOG_LEVEL });
460
+ redis = new RedisClient({ url: config.REDIS_URL, name: "workflow", logger });
461
+ const dbData = createDatabase({ url: config.DATABASE_URL, applicationName: "workflow", logger });
462
+ sql = dbData.sql;
463
+ db = dbData.db;
464
+ notificationProducer = new StreamProducer({
465
+ redis: redis.native,
466
+ stream: STREAMS.INBOUND_NORMAL,
467
+ logger,
468
+ });
469
+ workflowProducer = new StreamProducer({
470
+ redis: redis.native,
471
+ stream: STREAMS.WORKFLOW_INBOUND,
472
+ logger,
473
+ });
474
+ consumer = new StreamConsumer({
475
+ redis: redis.native,
476
+ stream: STREAMS.WORKFLOW_INBOUND as StreamName,
477
+ group: CONSUMER_GROUPS.WORKFLOW as any,
478
+ consumer: `workflow-${process.pid}`,
479
+ dlqStream: STREAMS.DEAD_LETTER,
480
+ batchSize: config.WORKER_CONCURRENCY,
481
+ logger,
482
+ });
483
+
484
+ pendingScanner = new PendingMessageScanner({
485
+ redis: redis.native,
486
+ stream: STREAMS.WORKFLOW_INBOUND as StreamName,
487
+ group: CONSUMER_GROUPS.WORKFLOW as any,
488
+ consumer: `workflow-${process.pid}`,
489
+ logger,
490
+ });
491
+
492
+ worker = new WorkflowWorker({
493
+ consumer,
494
+ pendingScanner,
495
+ logger,
496
+ concurrency: config.WORKER_CONCURRENCY,
497
+ redis: redis.native,
498
+ db,
499
+ workflowProducer,
500
+ notificationProducer,
501
+ });
502
+
503
+ // Polling loop for timers
504
+ pollInterval = setInterval(() => {
505
+ void (async () => {
506
+ try {
507
+ const now = Date.now();
508
+ const tasks = (await redis.native.eval(
509
+ LUA_SCHEDULER_POLL,
510
+ 1,
511
+ "notif:workflow:timers",
512
+ now,
513
+ 100,
514
+ WORKFLOW_TIMER_VISIBILITY_MS,
515
+ )) as string[];
516
+
517
+ for (const taskStr of tasks) {
518
+ const task = JSON.parse(taskStr);
519
+
520
+ // Check if workflow is already completed/failed
521
+ const inst = (
522
+ await db
523
+ .select()
524
+ .from(workflowInstances)
525
+ .where(eq(workflowInstances.id, task.instanceId))
526
+ .limit(1)
527
+ )[0];
528
+ if (!inst || inst.status === "completed" || inst.status === "failed") {
529
+ await redis.native.zrem("notif:workflow:timers", taskStr);
530
+ continue;
531
+ }
532
+ // A timer can be observed while the worker is still persisting the
533
+ // corresponding suspension. Leave the claimed member in place; its
534
+ // visibility timeout will make it eligible once the instance becomes
535
+ // pending instead of losing the wake-up signal.
536
+ if (inst.status === "running") continue;
537
+
538
+ if (task.isEventTimeout) {
539
+ // It's a timeout for waitForEvent. Clean up only this step's waiter
540
+ const deleted = await db
541
+ .delete(workflowWaiters)
542
+ .where(
543
+ and(
544
+ eq(workflowWaiters.instanceId, task.instanceId),
545
+ eq(workflowWaiters.eventName, task.eventName),
546
+ ),
547
+ )
548
+ .returning();
549
+
550
+ // If the waiter was already deleted (by EventWorker when event arrived before timeout),
551
+ // this timer is stale. Clean up from Redis and skip re-resuming the workflow.
552
+ if (deleted.length === 0) {
553
+ await redis.native.zrem("notif:workflow:timers", taskStr);
554
+ continue;
555
+ }
556
+
557
+ // Record timedOut state on the pending waitForEvent step
558
+ const steps = await db
559
+ .select()
560
+ .from(workflowSteps)
561
+ .where(
562
+ and(
563
+ eq(workflowSteps.instanceId, task.instanceId),
564
+ eq(workflowSteps.action, "waitForEvent"),
565
+ ),
566
+ );
567
+ const pendingStep = steps.find((s: any) => s.output === null);
568
+ if (pendingStep) {
569
+ await db
570
+ .update(workflowSteps)
571
+ .set({ output: { timedOut: true } })
572
+ .where(eq(workflowSteps.id, pendingStep.id));
573
+ }
574
+ }
575
+
576
+ await workflowProducer.publish(
577
+ buildStreamEvent("workflow.resumed", task, "scheduler", undefined),
578
+ );
579
+ await redis.native.zrem("notif:workflow:timers", taskStr);
580
+ logger.info({ instanceId: task.instanceId }, "Workflow resumed from timer");
581
+ }
582
+ } catch (err) {
583
+ logger.error({ err }, "error in workflow polling loop");
584
+ }
585
+ })();
586
+ }, 5000);
587
+
588
+ reaperInterval = setInterval(() => {
589
+ void (async () => {
590
+ try {
591
+ const runningInstances = await db
592
+ .select({ id: workflowInstances.id })
593
+ .from(workflowInstances)
594
+ .where(eq(workflowInstances.status, "running"));
595
+ for (const inst of runningInstances) {
596
+ const lockKey = `lock:workflow:${inst.id}`;
597
+ const hasLock = await redis.native.exists(lockKey);
598
+ if (!hasLock) {
599
+ await db
600
+ .update(workflowInstances)
601
+ .set({ status: "pending" })
602
+ .where(eq(workflowInstances.id, inst.id));
603
+ logger.info({ instanceId: inst.id }, "Reaped stuck workflow instance (lock expired)");
604
+ }
605
+ }
606
+ } catch (err) {
607
+ logger.error({ err }, "error in stuck workflow reaper");
608
+ }
609
+ })();
610
+ }, 60000);
611
+
612
+ healthInterval = startHealthReporter("workflow", worker, redis, logger);
613
+
614
+ logger.info("workflow worker starting");
615
+ await worker.start();
616
+ }
617
+
618
+ export async function stopWorkflowWorker(): Promise<void> {
619
+ logger?.info("shutdown initiated");
620
+ if (healthInterval) clearInterval(healthInterval);
621
+ if (pollInterval) clearInterval(pollInterval);
622
+ if (reaperInterval) clearInterval(reaperInterval);
623
+ if (worker) await worker.stop();
624
+ if (sql) await sql.end();
625
+ if (redis) await redis.disconnect();
626
+ logger?.info("workflow worker stopped");
627
+ }
@@ -0,0 +1,67 @@
1
+ export interface BatchItem<T, R> {
2
+ item: T;
3
+ resolve: (value: R) => void;
4
+ reject: (reason?: any) => void;
5
+ }
6
+
7
+ export class BatchProcessor<T, R = void> {
8
+ private buffer: BatchItem<T, R>[] = [];
9
+ private timer: NodeJS.Timeout | null = null;
10
+ private isFlushing = false;
11
+
12
+ constructor(
13
+ private readonly maxSize: number,
14
+ private readonly maxWaitMs: number,
15
+ private readonly flushFn: (items: T[]) => Promise<R[]>,
16
+ ) {}
17
+
18
+ add(item: T): Promise<R> {
19
+ return new Promise((resolve, reject) => {
20
+ this.buffer.push({ item, resolve, reject });
21
+ if (this.buffer.length >= this.maxSize && !this.isFlushing) {
22
+ if (this.timer) {
23
+ clearTimeout(this.timer);
24
+ this.timer = null;
25
+ }
26
+ void this.flush();
27
+ } else if (!this.timer && !this.isFlushing) {
28
+ this.timer = setTimeout(() => {
29
+ this.timer = null;
30
+ void this.flush();
31
+ }, this.maxWaitMs);
32
+ }
33
+ });
34
+ }
35
+
36
+ async flush(): Promise<void> {
37
+ if (this.isFlushing || this.buffer.length === 0) return;
38
+
39
+ this.isFlushing = true;
40
+ const batch = this.buffer;
41
+ this.buffer = [];
42
+
43
+ try {
44
+ const items = batch.map((b) => b.item);
45
+ const results = await this.flushFn(items);
46
+ for (let i = 0; i < batch.length; i++) {
47
+ batch[i]!.resolve(results[i] as R);
48
+ }
49
+ } catch (err) {
50
+ for (const b of batch) {
51
+ b.reject(err);
52
+ }
53
+ } finally {
54
+ this.isFlushing = false;
55
+ if (this.buffer.length > 0 && !this.timer) {
56
+ if (this.buffer.length >= this.maxSize) {
57
+ void this.flush();
58
+ } else {
59
+ this.timer = setTimeout(() => {
60
+ this.timer = null;
61
+ void this.flush();
62
+ }, this.maxWaitMs);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }