@headless-lms/adapter-defaults 0.3.0 → 0.4.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.
@@ -1,4 +1,4 @@
1
- import { EventBus, Logger, OutboxRelay, OutboxStore } from "@headless-lms/core/shared/ports";
1
+ import { DomainEvent, EventBus, Logger, OutboxRelay, OutboxStore } from "@headless-lms/core/shared/ports";
2
2
  //#region src/events/outbox-relay.d.ts
3
3
  /** Backoff base: first retry 5s after the first failure, doubling per attempt. */
4
4
  declare const OUTBOX_BACKOFF_BASE_MS = 5000;
@@ -14,7 +14,9 @@ interface PollingOutboxRelayConfig {
14
14
  pollIntervalMs: number;
15
15
  /** Max rows fetched/dispatched per tick; a full batch re-polls immediately. */
16
16
  batchSize: number;
17
+ concurrency: number;
17
18
  }
19
+ declare function orderingKey(event: DomainEvent): string;
18
20
  declare class PollingOutboxRelay implements OutboxRelay {
19
21
  private readonly store;
20
22
  private readonly bus;
@@ -27,12 +29,13 @@ declare class PollingOutboxRelay implements OutboxRelay {
27
29
  start(): void;
28
30
  stop(): Promise<void>;
29
31
  private schedule;
30
- /** One poll: fetch a batch, dispatch in order, reschedule — immediately when
32
+ /** One poll: fetch a batch, dispatch in order per ordering key, reschedule — immediately when
31
33
  * the batch was full (drain bursts), else after the idle interval. Never
32
34
  * throws: a poll failure is logged and retried next tick. */
33
35
  private tick;
36
+ private dispatchBatch;
34
37
  private dispatch;
35
38
  }
36
39
  //#endregion
37
- export { OUTBOX_BACKOFF_BASE_MS, OUTBOX_BACKOFF_MAX_MS, PollingOutboxRelay, PollingOutboxRelayConfig, outboxBackoffMs };
40
+ export { OUTBOX_BACKOFF_BASE_MS, OUTBOX_BACKOFF_MAX_MS, PollingOutboxRelay, PollingOutboxRelayConfig, orderingKey, outboxBackoffMs };
38
41
  //# sourceMappingURL=outbox-relay.d.ts.map
@@ -9,6 +9,21 @@ const OUTBOX_BACKOFF_MAX_MS = 15 * 6e4;
9
9
  function outboxBackoffMs(attempts) {
10
10
  return Math.min(OUTBOX_BACKOFF_BASE_MS * 2 ** attempts, OUTBOX_BACKOFF_MAX_MS);
11
11
  }
12
+ const ORDERING_FIELDS = [
13
+ "chatId",
14
+ "postId",
15
+ "activityId",
16
+ "commentId",
17
+ "id"
18
+ ];
19
+ function orderingKey(event) {
20
+ const data = event.data;
21
+ if (data !== null && typeof data === "object") for (const field of ORDERING_FIELDS) {
22
+ const value = data[field];
23
+ if (typeof value === "string" && value.length > 0) return `${event.orgId}:${value}`;
24
+ }
25
+ return `${event.orgId}:${event.id}`;
26
+ }
12
27
  var PollingOutboxRelay = class {
13
28
  store;
14
29
  bus;
@@ -29,7 +44,8 @@ var PollingOutboxRelay = class {
29
44
  this.schedule(this.config.pollIntervalMs);
30
45
  this.logger.info("outbox relay started", {
31
46
  pollIntervalMs: this.config.pollIntervalMs,
32
- batchSize: this.config.batchSize
47
+ batchSize: this.config.batchSize,
48
+ concurrency: this.config.concurrency
33
49
  });
34
50
  }
35
51
  async stop() {
@@ -46,7 +62,7 @@ var PollingOutboxRelay = class {
46
62
  this.inFlight = this.tick();
47
63
  }, delayMs);
48
64
  }
49
- /** One poll: fetch a batch, dispatch in order, reschedule — immediately when
65
+ /** One poll: fetch a batch, dispatch in order per ordering key, reschedule — immediately when
50
66
  * the batch was full (drain bursts), else after the idle interval. Never
51
67
  * throws: a poll failure is logged and retried next tick. */
52
68
  async tick() {
@@ -55,12 +71,26 @@ var PollingOutboxRelay = class {
55
71
  const batch = await this.store.fetchBatch(this.config.batchSize);
56
72
  fetched = batch.length;
57
73
  if (fetched > 0) this.logger.debug("outbox batch fetched", { count: fetched });
58
- for (const message of batch) await this.dispatch(message);
74
+ await this.dispatchBatch(batch);
59
75
  } catch (err) {
60
76
  this.logger.error("outbox poll failed", { error: String(err) });
61
77
  }
62
78
  this.schedule(fetched >= this.config.batchSize ? 0 : this.config.pollIntervalMs);
63
79
  }
80
+ async dispatchBatch(batch) {
81
+ const lanes = /* @__PURE__ */ new Map();
82
+ for (const message of batch) {
83
+ const key = orderingKey(message.payload);
84
+ const lane = lanes.get(key);
85
+ if (lane) lane.push(message);
86
+ else lanes.set(key, [message]);
87
+ }
88
+ const queue = [...lanes.values()];
89
+ const workers = Math.min(Math.max(1, this.config.concurrency), queue.length);
90
+ await Promise.all(Array.from({ length: workers }, async () => {
91
+ for (let lane = queue.shift(); lane; lane = queue.shift()) for (const message of lane) await this.dispatch(message);
92
+ }));
93
+ }
64
94
  async dispatch(message) {
65
95
  try {
66
96
  await this.bus.publish(message.payload);
@@ -72,7 +102,17 @@ var PollingOutboxRelay = class {
72
102
  } catch (err) {
73
103
  const error = String(err);
74
104
  const nextAttemptAt = new Date(Date.now() + outboxBackoffMs(message.attempts));
75
- await this.store.markFailed(message.id, error, nextAttemptAt);
105
+ try {
106
+ await this.store.markFailed(message.id, error, nextAttemptAt);
107
+ } catch (markErr) {
108
+ this.logger.error("outbox failure not recorded", {
109
+ id: message.id,
110
+ type: message.payload.type,
111
+ error,
112
+ markError: String(markErr)
113
+ });
114
+ return;
115
+ }
76
116
  const attempt = message.attempts + 1;
77
117
  const meta = {
78
118
  id: message.id,
@@ -87,6 +127,6 @@ var PollingOutboxRelay = class {
87
127
  }
88
128
  };
89
129
  //#endregion
90
- export { OUTBOX_BACKOFF_BASE_MS, OUTBOX_BACKOFF_MAX_MS, PollingOutboxRelay, outboxBackoffMs };
130
+ export { OUTBOX_BACKOFF_BASE_MS, OUTBOX_BACKOFF_MAX_MS, PollingOutboxRelay, orderingKey, outboxBackoffMs };
91
131
 
92
132
  //# sourceMappingURL=outbox-relay.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-relay.js","names":[],"sources":["../../src/events/outbox-relay.ts"],"sourcesContent":["// Same-process outbox relay (implements the core OutboxRelay port). A\n// setTimeout-CHAINED poller (never setInterval — a slow batch must not overlap\n// the next tick): each tick fetches unprocessed rows in id order and publishes\n// them to the EventBus.\n//\n// Delivery is at-least-once — handlers must be idempotent, keyed on event.id.\n// Ordering is skip-past-failures: a failing row is stamped with the error and\n// an exponential-backoff next_attempt_at (retried once due) while later rows\n// flow; the store stops fetching it after OUTBOX_MAX_ATTEMPTS failures.\nimport type {\n EventBus,\n Logger,\n OutboxMessage,\n OutboxRelay,\n OutboxStore,\n} from \"@headless-lms/core/shared/ports\";\nimport { OUTBOX_MAX_ATTEMPTS } from \"@headless-lms/adapter-db\";\n\n/** Backoff base: first retry 5s after the first failure, doubling per attempt. */\nexport const OUTBOX_BACKOFF_BASE_MS = 5_000;\n/** Backoff ceiling: retries never wait longer than 15 minutes. */\nexport const OUTBOX_BACKOFF_MAX_MS = 15 * 60_000;\n\n/** Exponential backoff delay after a failure: min(base × 2^attempts, max),\n * where `attempts` is the PRIOR failure count (0 on the first failure). */\nexport function outboxBackoffMs(attempts: number): number {\n return Math.min(OUTBOX_BACKOFF_BASE_MS * 2 ** attempts, OUTBOX_BACKOFF_MAX_MS);\n}\n\nexport interface PollingOutboxRelayConfig {\n /** Master switch: false → start() is a no-op. */\n enabled: boolean;\n /** Idle delay between polls. */\n pollIntervalMs: number;\n /** Max rows fetched/dispatched per tick; a full batch re-polls immediately. */\n batchSize: number;\n}\n\nexport class PollingOutboxRelay implements OutboxRelay {\n private pollTimer: NodeJS.Timeout | undefined;\n private running = false;\n private inFlight: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly store: OutboxStore,\n private readonly bus: EventBus,\n private readonly config: PollingOutboxRelayConfig,\n private readonly logger: Logger,\n ) {}\n\n start(): void {\n if (!this.config.enabled || this.running) {\n return;\n }\n this.running = true;\n this.schedule(this.config.pollIntervalMs);\n this.logger.info(\"outbox relay started\", {\n pollIntervalMs: this.config.pollIntervalMs,\n batchSize: this.config.batchSize,\n });\n }\n\n async stop(): Promise<void> {\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n }\n this.pollTimer = undefined;\n const wasRunning = this.running;\n this.running = false;\n await this.inFlight;\n if (wasRunning) {\n this.logger.info(\"outbox relay stopped\");\n }\n }\n\n private schedule(delayMs: number): void {\n if (!this.running) {\n return;\n }\n this.pollTimer = setTimeout(() => {\n this.inFlight = this.tick();\n }, delayMs);\n }\n\n /** One poll: fetch a batch, dispatch in order, reschedule — immediately when\n * the batch was full (drain bursts), else after the idle interval. Never\n * throws: a poll failure is logged and retried next tick. */\n private async tick(): Promise<void> {\n let fetched = 0;\n try {\n const batch = await this.store.fetchBatch(this.config.batchSize);\n fetched = batch.length;\n if (fetched > 0) {\n this.logger.debug(\"outbox batch fetched\", { count: fetched });\n }\n for (const message of batch) {\n await this.dispatch(message);\n }\n } catch (err) {\n this.logger.error(\"outbox poll failed\", { error: String(err) });\n }\n this.schedule(fetched >= this.config.batchSize ? 0 : this.config.pollIntervalMs);\n }\n\n private async dispatch(message: OutboxMessage): Promise<void> {\n try {\n await this.bus.publish(message.payload);\n await this.store.markProcessed(message.id);\n this.logger.info(\"outbox event dispatched\", {\n id: message.id,\n type: message.payload.type,\n });\n } catch (err) {\n const error = String(err);\n const nextAttemptAt = new Date(Date.now() + outboxBackoffMs(message.attempts));\n await this.store.markFailed(message.id, error, nextAttemptAt);\n const attempt = message.attempts + 1;\n const meta = {\n id: message.id,\n type: message.payload.type,\n attempt,\n nextAttemptAt: nextAttemptAt.toISOString(),\n error,\n };\n // The store stops fetching after OUTBOX_MAX_ATTEMPTS — this failure parks the row.\n if (attempt >= OUTBOX_MAX_ATTEMPTS) {\n this.logger.warn(\"outbox event parked\", meta);\n } else {\n this.logger.error(\"outbox dispatch failed\", meta);\n }\n }\n }\n}\n"],"mappings":";;;AAmBA,MAAa,yBAAyB;;AAEtC,MAAa,wBAAwB,KAAK;;;AAI1C,SAAgB,gBAAgB,UAA0B;CACxD,OAAO,KAAK,IAAI,yBAAyB,KAAK,UAAU,qBAAqB;AAC/E;AAWA,IAAa,qBAAb,MAAuD;CAMlC;CACA;CACA;CACA;CARnB;CACA,UAAkB;CAClB,WAAkC,QAAQ,QAAQ;CAElD,YACE,OACA,KACA,Q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ACZ,MAAM,QAAQ,QAAQ;GACxB,CAAC;EACH,SAAS,KAAK;GACZ,MAAM,QAAQ,OAAO,GAAG;GACxB,MAAM,gBAAgB,IAAI,KAAK,KAAK,IAAI,IAAI,gBAAgB,QAAQ,QAAQ,CAAC;GAC7E,MAAM,KAAK,MAAM,WAAW,QAAQ,IAAI,OAAO,aAAa;GAC5D,MAAM,UAAU,QAAQ,WAAW;GACnC,MAAM,OAAO;IACX,IAAI,QAAQ;IACZ,MAAM,QAAQ,QAAQ;IACtB;IACA,eAAe,cAAc,YAAY;IACzC;GACF;GAEA,IAAI,WAAW,qBACb,KAAK,OAAO,KAAK,uBAAuB,IAAI;QAE5C,KAAK,OAAO,MAAM,0BAA0B,IAAI;EAEpD;CACF;AACF"}
1
+ {"version":3,"file":"outbox-relay.js","names":[],"sources":["../../src/events/outbox-relay.ts"],"sourcesContent":["// Same-process outbox relay (implements the core OutboxRelay port). A\n// setTimeout-CHAINED poller (never setInterval — a slow batch must not overlap\n// the next tick): each tick fetches unprocessed rows in id order and publishes\n// them to the EventBus, up to `concurrency` at once and in id order per ordering key.\n//\n// Delivery is at-least-once — handlers must be idempotent, keyed on event.id.\n// Ordering is skip-past-failures: a failing row is stamped with the error and\n// an exponential-backoff next_attempt_at (retried once due) while later rows\n// flow; the store stops fetching it after OUTBOX_MAX_ATTEMPTS failures.\nimport type {\n DomainEvent,\n EventBus,\n Logger,\n OutboxMessage,\n OutboxRelay,\n OutboxStore,\n} from \"@headless-lms/core/shared/ports\";\nimport { OUTBOX_MAX_ATTEMPTS } from \"@headless-lms/adapter-db\";\n\n/** Backoff base: first retry 5s after the first failure, doubling per attempt. */\nexport const OUTBOX_BACKOFF_BASE_MS = 5_000;\n/** Backoff ceiling: retries never wait longer than 15 minutes. */\nexport const OUTBOX_BACKOFF_MAX_MS = 15 * 60_000;\n\n/** Exponential backoff delay after a failure: min(base × 2^attempts, max),\n * where `attempts` is the PRIOR failure count (0 on the first failure). */\nexport function outboxBackoffMs(attempts: number): number {\n return Math.min(OUTBOX_BACKOFF_BASE_MS * 2 ** attempts, OUTBOX_BACKOFF_MAX_MS);\n}\n\nexport interface PollingOutboxRelayConfig {\n /** Master switch: false → start() is a no-op. */\n enabled: boolean;\n /** Idle delay between polls. */\n pollIntervalMs: number;\n /** Max rows fetched/dispatched per tick; a full batch re-polls immediately. */\n batchSize: number;\n concurrency: number;\n}\n\nconst ORDERING_FIELDS = [\"chatId\", \"postId\", \"activityId\", \"commentId\", \"id\"] as const;\n\nexport function orderingKey(event: DomainEvent): string {\n const data = event.data;\n if (data !== null && typeof data === \"object\") {\n for (const field of ORDERING_FIELDS) {\n const value = (data as Record<string, unknown>)[field];\n if (typeof value === \"string\" && value.length > 0) {\n return `${event.orgId}:${value}`;\n }\n }\n }\n return `${event.orgId}:${event.id}`;\n}\n\nexport class PollingOutboxRelay implements OutboxRelay {\n private pollTimer: NodeJS.Timeout | undefined;\n private running = false;\n private inFlight: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly store: OutboxStore,\n private readonly bus: EventBus,\n private readonly config: PollingOutboxRelayConfig,\n private readonly logger: Logger,\n ) {}\n\n start(): void {\n if (!this.config.enabled || this.running) {\n return;\n }\n this.running = true;\n this.schedule(this.config.pollIntervalMs);\n this.logger.info(\"outbox relay started\", {\n pollIntervalMs: this.config.pollIntervalMs,\n batchSize: this.config.batchSize,\n concurrency: this.config.concurrency,\n });\n }\n\n async stop(): Promise<void> {\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n }\n this.pollTimer = undefined;\n const wasRunning = this.running;\n this.running = false;\n await this.inFlight;\n if (wasRunning) {\n this.logger.info(\"outbox relay stopped\");\n }\n }\n\n private schedule(delayMs: number): void {\n if (!this.running) {\n return;\n }\n this.pollTimer = setTimeout(() => {\n this.inFlight = this.tick();\n }, delayMs);\n }\n\n /** One poll: fetch a batch, dispatch in order per ordering key, reschedule — immediately when\n * the batch was full (drain bursts), else after the idle interval. Never\n * throws: a poll failure is logged and retried next tick. */\n private async tick(): Promise<void> {\n let fetched = 0;\n try {\n const batch = await this.store.fetchBatch(this.config.batchSize);\n fetched = batch.length;\n if (fetched > 0) {\n this.logger.debug(\"outbox batch fetched\", { count: fetched });\n }\n await this.dispatchBatch(batch);\n } catch (err) {\n this.logger.error(\"outbox poll failed\", { error: String(err) });\n }\n this.schedule(fetched >= this.config.batchSize ? 0 : this.config.pollIntervalMs);\n }\n\n private async dispatchBatch(batch: OutboxMessage[]): Promise<void> {\n const lanes = new Map<string, OutboxMessage[]>();\n for (const message of batch) {\n const key = orderingKey(message.payload);\n const lane = lanes.get(key);\n if (lane) {\n lane.push(message);\n } else {\n lanes.set(key, [message]);\n }\n }\n const queue = [...lanes.values()];\n const workers = Math.min(Math.max(1, this.config.concurrency), queue.length);\n await Promise.all(\n Array.from({ length: workers }, async () => {\n for (let lane = queue.shift(); lane; lane = queue.shift()) {\n for (const message of lane) {\n await this.dispatch(message);\n }\n }\n }),\n );\n }\n\n private async dispatch(message: OutboxMessage): Promise<void> {\n try {\n await this.bus.publish(message.payload);\n await this.store.markProcessed(message.id);\n this.logger.info(\"outbox event dispatched\", {\n id: message.id,\n type: message.payload.type,\n });\n } catch (err) {\n const error = String(err);\n const nextAttemptAt = new Date(Date.now() + outboxBackoffMs(message.attempts));\n try {\n await this.store.markFailed(message.id, error, nextAttemptAt);\n } catch (markErr) {\n this.logger.error(\"outbox failure not recorded\", {\n id: message.id,\n type: message.payload.type,\n error,\n markError: String(markErr),\n });\n return;\n }\n const attempt = message.attempts + 1;\n const meta = {\n id: message.id,\n type: message.payload.type,\n attempt,\n nextAttemptAt: nextAttemptAt.toISOString(),\n error,\n };\n // The store stops fetching after OUTBOX_MAX_ATTEMPTS — this failure parks the row.\n if (attempt >= OUTBOX_MAX_ATTEMPTS) {\n this.logger.warn(\"outbox event parked\", meta);\n } else {\n this.logger.error(\"outbox dispatch failed\", meta);\n }\n }\n }\n}\n"],"mappings":";;;AAoBA,MAAa,yBAAyB;;AAEtC,MAAa,wBA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AO,GAAG;GACxB,MAAM,gBAAgB,IAAI,KAAK,KAAK,IAAI,IAAI,gBAAgB,QAAQ,QAAQ,CAAC;GAC7E,IAAI;IACF,MAAM,KAAK,MAAM,WAAW,QAAQ,IAAI,OAAO,aAAa;GAC9D,SAAS,SAAS;IAChB,KAAK,OAAO,MAAM,+BAA+B;KAC/C,IAAI,QAAQ;KACZ,MAAM,QAAQ,QAAQ;KACtB;KACA,WAAW,OAAO,OAAO;IAC3B,CAAC;IACD;GACF;GACA,MAAM,UAAU,QAAQ,WAAW;GACnC,MAAM,OAAO;IACX,IAAI,QAAQ;IACZ,MAAM,QAAQ,QAAQ;IACtB;IACA,eAAe,cAAc,YAAY;IACzC;GACF;GAEA,IAAI,WAAW,qBACb,KAAK,OAAO,KAAK,uBAAuB,IAAI;QAE5C,KAAK,OAAO,MAAM,0BAA0B,IAAI;EAEpD;CACF;AACF"}
@@ -1,13 +1,19 @@
1
1
  import { startScheduleLoop } from "./schedule.js";
2
- import { AutomationDispatch, AutomationEngine, AutomationExecutor, Logger } from "@headless-lms/core/types";
2
+ import { RecurringJob, ScheduledJob, Scheduler } from "@headless-lms/core/shared/ports";
3
+ import { AutomationDispatch, AutomationEngine, AutomationExecutor, DeliveryDispatch, JsonValue, Logger as Logger$1 } from "@headless-lms/core/types";
3
4
  //#region src/workflows/index.d.ts
4
- declare class InlineAutomationEngine implements AutomationEngine {
5
+ declare class InlineAutomationEngine implements AutomationEngine, Scheduler {
5
6
  private readonly logger?;
6
7
  private executor;
7
8
  private schedule;
8
- constructor(logger?: Logger | undefined);
9
+ private readonly jobs;
10
+ constructor(logger?: Logger$1 | undefined);
9
11
  register(executor: AutomationExecutor): void;
12
+ registerJobs(handlers: ScheduledJob[], recurring: RecurringJob[]): void;
13
+ at(job: string, runAt: Date, key: string, payload: JsonValue): Promise<void>;
14
+ cancel(job: string, key: string): Promise<void>;
10
15
  dispatch(d: AutomationDispatch): Promise<void>;
16
+ deliver(d: DeliveryDispatch): Promise<void>;
11
17
  start(): Promise<void>;
12
18
  stop(): Promise<void>;
13
19
  }
@@ -1,16 +1,28 @@
1
1
  import { startScheduleLoop } from "./schedule.js";
2
+ import { InlineJobs } from "./jobs.js";
2
3
  import { ActionFailedError, actionFailureMessage } from "@headless-lms/core/automations";
3
4
  //#region src/workflows/index.ts
4
5
  var InlineAutomationEngine = class {
5
6
  logger;
6
7
  executor;
7
8
  schedule;
9
+ jobs;
8
10
  constructor(logger) {
9
11
  this.logger = logger;
12
+ this.jobs = new InlineJobs(logger);
10
13
  }
11
14
  register(executor) {
12
15
  this.executor = executor;
13
16
  }
17
+ registerJobs(handlers, recurring) {
18
+ this.jobs.register(handlers, recurring);
19
+ }
20
+ async at(job, runAt, key, payload) {
21
+ this.jobs.at(job, runAt, key, payload);
22
+ }
23
+ async cancel(job, key) {
24
+ this.jobs.cancel(job, key);
25
+ }
14
26
  async dispatch(d) {
15
27
  if (!this.executor) throw new Error("InlineAutomationEngine.dispatch called before register()");
16
28
  const executor = this.executor;
@@ -35,13 +47,19 @@ var InlineAutomationEngine = class {
35
47
  }
36
48
  await executor.finalize(d, results);
37
49
  }
50
+ async deliver(d) {
51
+ if (!this.executor) throw new Error("InlineAutomationEngine.deliver called before register()");
52
+ await this.executor.runDelivery(d, true);
53
+ }
38
54
  async start() {
39
55
  this.schedule?.stop();
40
56
  this.schedule = startScheduleLoop(() => this.executor, this.logger);
57
+ this.jobs.start();
41
58
  }
42
59
  async stop() {
43
60
  this.schedule?.stop();
44
61
  this.schedule = void 0;
62
+ this.jobs.stop();
45
63
  }
46
64
  };
47
65
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/workflows/index.ts"],"sourcesContent":["// Default in-process engine — runs a dispatched automation immediately, one\n// attempt per action; durable engines (Hatchet, …) are installation adapters.\nimport type {\n AutomationActionResult,\n AutomationDispatch,\n AutomationEngine,\n AutomationExecutor,\n Logger,\n} from \"@headless-lms/core/types\";\nimport { ActionFailedError, actionFailureMessage } from \"@headless-lms/core/automations\";\nimport { startScheduleLoop } from \"./schedule.js\";\n\nexport { startScheduleLoop };\n\nexport class InlineAutomationEngine implements AutomationEngine {\n private executor: AutomationExecutor | undefined;\n private schedule: { stop(): void } | undefined;\n\n constructor(private readonly logger?: Logger) {}\n\n register(executor: AutomationExecutor): void {\n this.executor = executor;\n }\n\n async dispatch(d: AutomationDispatch): Promise<void> {\n if (!this.executor) {\n throw new Error(\"InlineAutomationEngine.dispatch called before register()\");\n }\n const executor = this.executor;\n\n const results: AutomationActionResult[] = [];\n for (let index = 0; index < d.actions.length; index++) {\n try {\n results.push(await executor.runAction(d, index));\n } catch (err) {\n if (!(err instanceof ActionFailedError)) {\n this.logger?.error(\"automation action failed\", {\n orgId: d.orgId,\n automationId: d.automationId,\n runId: d.runId,\n index,\n err,\n });\n }\n results.push({\n index,\n type: d.actions[index]!.type,\n status: \"failed\",\n error: actionFailureMessage(err),\n });\n break;\n }\n }\n\n await executor.finalize(d, results);\n }\n\n async start(): Promise<void> {\n this.schedule?.stop();\n this.schedule = startScheduleLoop(() => this.executor, this.logger);\n }\n\n async stop(): Promise<void> {\n this.schedule?.stop();\n this.schedule = undefined;\n }\n}\n"],"mappings":";;;AAcA,IAAa,yBAAb,MAAgE;CAIjC;CAH7B;CACA;CAEA,YAAY,QAAkC;EAAjB,KAAA,SAAA;CAAkB;CAE/C,SAAS,UAAoC;EAC3C,KAAK,WAAW;CAClB;CAEA,MAAM,SAAS,GAAsC;EACnD,IAAI,CAAC,KAAK,UACR,MAAM,IAAI,MAAM,0DAA0D;EAE5E,MAAM,WAAW,KAAK;EAEtB,MAAM,UAAoC,CAAC;EAC3C,KAAK,IAAI,QAAQ,GAAG,QAAQ,EAAE,QAAQ,QAAQ,SAC5C,IAAI;GACF,QAAQ,KAAK,MAAM,SAAS,UAAU,GAAG,KAAK,CAAC;EACjD,SAAS,KAAK;GACZ,IAAI,EAAE,eAAe,oBACnB,KAAK,QAAQ,MAAM,4BAA4B;IAC7C,OAAO,EAAE;IACT,cAAc,EAAE;IAChB,OAAO,EAAE;IACT;IACA;GACF,CAAC;GAEH,QAAQ,KAAK;IACX;IACA,MAAM,EAAE,QAAQ,MAAM,CAAE;IACxB,QAAQ;IACR,OAAO,qBAAqB,GAAG;GACjC,CAAC;GACD;EACF;EAGF,MAAM,SAAS,SAAS,GAAG,OAAO;CACpC;CAEA,MAAM,QAAuB;EAC3B,KAAK,UAAU,KAAK;EACpB,KAAK,WAAW,wBAAwB,KAAK,UAAU,KAAK,MAAM;CACpE;CAEA,MAAM,OAAsB;EAC1B,KAAK,UAAU,KAAK;EACpB,KAAK,WAAW,KAAA;CAClB;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/workflows/index.ts"],"sourcesContent":["// Default in-process engine — runs a dispatched automation immediately, one\n// attempt per action; durable engines (Hatchet, …) are installation adapters.\nimport type {\n AutomationActionResult,\n AutomationDispatch,\n AutomationEngine,\n AutomationExecutor,\n DeliveryDispatch,\n JsonValue,\n Logger,\n} from \"@headless-lms/core/types\";\nimport type { RecurringJob, ScheduledJob, Scheduler } from \"@headless-lms/core/shared/ports\";\nimport { ActionFailedError, actionFailureMessage } from \"@headless-lms/core/automations\";\nimport { startScheduleLoop } from \"./schedule.js\";\nimport { InlineJobs } from \"./jobs.js\";\n\nexport { startScheduleLoop };\n\nexport class InlineAutomationEngine implements AutomationEngine, Scheduler {\n private executor: AutomationExecutor | undefined;\n private schedule: { stop(): void } | undefined;\n private readonly jobs: InlineJobs;\n\n constructor(private readonly logger?: Logger) {\n this.jobs = new InlineJobs(logger);\n }\n\n register(executor: AutomationExecutor): void {\n this.executor = executor;\n }\n\n registerJobs(handlers: ScheduledJob[], recurring: RecurringJob[]): void {\n this.jobs.register(handlers, recurring);\n }\n\n async at(job: string, runAt: Date, key: string, payload: JsonValue): Promise<void> {\n this.jobs.at(job, runAt, key, payload);\n }\n\n async cancel(job: string, key: string): Promise<void> {\n this.jobs.cancel(job, key);\n }\n\n async dispatch(d: AutomationDispatch): Promise<void> {\n if (!this.executor) {\n throw new Error(\"InlineAutomationEngine.dispatch called before register()\");\n }\n const executor = this.executor;\n\n const results: AutomationActionResult[] = [];\n for (let index = 0; index < d.actions.length; index++) {\n try {\n results.push(await executor.runAction(d, index));\n } catch (err) {\n if (!(err instanceof ActionFailedError)) {\n this.logger?.error(\"automation action failed\", {\n orgId: d.orgId,\n automationId: d.automationId,\n runId: d.runId,\n index,\n err,\n });\n }\n results.push({\n index,\n type: d.actions[index]!.type,\n status: \"failed\",\n error: actionFailureMessage(err),\n });\n break;\n }\n }\n\n await executor.finalize(d, results);\n }\n\n async deliver(d: DeliveryDispatch): Promise<void> {\n if (!this.executor) {\n throw new Error(\"InlineAutomationEngine.deliver called before register()\");\n }\n await this.executor.runDelivery(d, true);\n }\n\n async start(): Promise<void> {\n this.schedule?.stop();\n this.schedule = startScheduleLoop(() => this.executor, this.logger);\n this.jobs.start();\n }\n\n async stop(): Promise<void> {\n this.schedule?.stop();\n this.schedule = undefined;\n this.jobs.stop();\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,yBAAb,MAA2E;CAK5C;CAJ7B;CACA;CACA;CAEA,YAAY,QAAkC;EAAjB,KAAA,SAAA;EAC3B,KAAK,OAAO,IAAI,WAAW,MAAM;CACnC;CAEA,SAAS,UAAoC;EAC3C,KAAK,WAAW;CAClB;CAEA,aAAa,UAA0B,WAAiC;EACtE,KAAK,KAAK,SAAS,UAAU,SAAS;CACxC;CAEA,MAAM,GAAG,KAAa,OAAa,KAAa,SAAmC;EACjF,KAAK,KAAK,GAAG,KAAK,OAAO,KAAK,OAAO;CACvC;CAEA,MAAM,OAAO,KAAa,KAA4B;EACpD,KAAK,KAAK,OAAO,KAAK,GAAG;CAC3B;CAEA,MAAM,SAAS,GAAsC;EACnD,IAAI,CAAC,KAAK,UACR,MAAM,IAAI,MAAM,0DAA0D;EAE5E,MAAM,WAAW,KAAK;EAEtB,MAAM,UAAoC,CAAC;EAC3C,KAAK,IAAI,QAAQ,GAAG,QAAQ,EAAE,QAAQ,QAAQ,SAC5C,IAAI;GACF,QAAQ,KAAK,MAAM,SAAS,UAAU,GAAG,KAAK,CAAC;EACjD,SAAS,KAAK;GACZ,IAAI,EAAE,eAAe,oBACnB,KAAK,QAAQ,MAAM,4BAA4B;IAC7C,OAAO,EAAE;IACT,cAAc,EAAE;IAChB,OAAO,EAAE;IACT;IACA;GACF,CAAC;GAEH,QAAQ,KAAK;IACX;IACA,MAAM,EAAE,QAAQ,MAAM,CAAE;IACxB,QAAQ;IACR,OAAO,qBAAqB,GAAG;GACjC,CAAC;GACD;EACF;EAGF,MAAM,SAAS,SAAS,GAAG,OAAO;CACpC;CAEA,MAAM,QAAQ,GAAoC;EAChD,IAAI,CAAC,KAAK,UACR,MAAM,IAAI,MAAM,yDAAyD;EAE3E,MAAM,KAAK,SAAS,YAAY,GAAG,IAAI;CACzC;CAEA,MAAM,QAAuB;EAC3B,KAAK,UAAU,KAAK;EACpB,KAAK,WAAW,wBAAwB,KAAK,UAAU,KAAK,MAAM;EAClE,KAAK,KAAK,MAAM;CAClB;CAEA,MAAM,OAAsB;EAC1B,KAAK,UAAU,KAAK;EACpB,KAAK,WAAW,KAAA;EAChB,KAAK,KAAK,KAAK;CACjB;AACF"}
@@ -0,0 +1,27 @@
1
+ import { RecurringJob, ScheduledJob } from "@headless-lms/core/shared/ports";
2
+ import { JsonValue, Logger as Logger$1 } from "@headless-lms/core/types";
3
+ //#region src/workflows/jobs.d.ts
4
+ declare class InlineJobs {
5
+ private readonly logger;
6
+ private handlers;
7
+ private recurring;
8
+ private readonly timers;
9
+ private loop;
10
+ private lastMinute;
11
+ private ticking;
12
+ constructor(logger?: Logger$1);
13
+ register(handlers: ScheduledJob[], recurring: RecurringJob[]): void;
14
+ at(job: string, runAt: Date, key: string, payload: JsonValue): void;
15
+ cancel(job: string, key: string): void;
16
+ start(): void;
17
+ stop(): void;
18
+ private stopLoop;
19
+ private arm;
20
+ private clear;
21
+ private tick;
22
+ private fireDue;
23
+ private fire;
24
+ }
25
+ //#endregion
26
+ export { InlineJobs };
27
+ //# sourceMappingURL=jobs.d.ts.map
@@ -0,0 +1,113 @@
1
+ import { noopLogger } from "@headless-lms/core/shared/logger";
2
+ import { cronMatches } from "@headless-lms/core/automations";
3
+ import { randomUUID } from "node:crypto";
4
+ //#region src/workflows/jobs.ts
5
+ const MINUTE_MS = 6e4;
6
+ const MAX_TIMER_MS = 2147483647;
7
+ function floorUtcMinute(at) {
8
+ const copy = new Date(at);
9
+ copy.setUTCSeconds(0, 0);
10
+ return copy.getTime();
11
+ }
12
+ function timerKey(job, key) {
13
+ return `${job}\0${key}`;
14
+ }
15
+ var InlineJobs = class {
16
+ logger;
17
+ handlers = /* @__PURE__ */ new Map();
18
+ recurring = [];
19
+ timers = /* @__PURE__ */ new Map();
20
+ loop;
21
+ lastMinute;
22
+ ticking = false;
23
+ constructor(logger = noopLogger) {
24
+ this.logger = logger;
25
+ }
26
+ register(handlers, recurring) {
27
+ this.handlers = new Map(handlers.map((handler) => [handler.job, handler]));
28
+ this.recurring = [...recurring];
29
+ }
30
+ at(job, runAt, key, payload) {
31
+ const id = timerKey(job, key);
32
+ this.clear(id);
33
+ this.arm(id, job, key, runAt.getTime(), payload);
34
+ }
35
+ cancel(job, key) {
36
+ this.clear(timerKey(job, key));
37
+ }
38
+ start() {
39
+ this.stopLoop();
40
+ this.tick();
41
+ this.loop = setInterval(() => this.tick(), MINUTE_MS);
42
+ this.loop.unref?.();
43
+ }
44
+ stop() {
45
+ this.stopLoop();
46
+ for (const timer of this.timers.values()) clearTimeout(timer);
47
+ this.timers.clear();
48
+ }
49
+ stopLoop() {
50
+ if (this.loop) clearInterval(this.loop);
51
+ this.loop = void 0;
52
+ }
53
+ arm(id, job, key, runAtMs, payload) {
54
+ const delay = Math.min(Math.max(runAtMs - Date.now(), 0), MAX_TIMER_MS);
55
+ const timer = setTimeout(() => {
56
+ if (runAtMs > Date.now()) {
57
+ this.arm(id, job, key, runAtMs, payload);
58
+ return;
59
+ }
60
+ this.timers.delete(id);
61
+ this.fire(job, key, payload);
62
+ }, delay);
63
+ timer.unref?.();
64
+ this.timers.set(id, timer);
65
+ }
66
+ clear(id) {
67
+ const timer = this.timers.get(id);
68
+ if (timer) clearTimeout(timer);
69
+ this.timers.delete(id);
70
+ }
71
+ tick() {
72
+ if (this.ticking) return;
73
+ this.ticking = true;
74
+ this.fireDue(/* @__PURE__ */ new Date()).finally(() => {
75
+ this.ticking = false;
76
+ });
77
+ }
78
+ async fireDue(now) {
79
+ const nowMs = floorUtcMinute(now);
80
+ const from = this.lastMinute === void 0 ? nowMs : this.lastMinute + MINUTE_MS;
81
+ for (let minute = from; minute <= nowMs; minute += MINUTE_MS) {
82
+ this.lastMinute = minute;
83
+ const at = new Date(minute);
84
+ for (const recurring of this.recurring) if (cronMatches(recurring.cron, at)) await this.fire(recurring.job, recurring.job, null);
85
+ }
86
+ }
87
+ async fire(job, key, payload) {
88
+ const handler = this.handlers.get(job);
89
+ if (!handler) {
90
+ this.logger.error("scheduled job has no handler", {
91
+ job,
92
+ key
93
+ });
94
+ return;
95
+ }
96
+ try {
97
+ await handler.run(payload, {
98
+ id: randomUUID(),
99
+ startedAt: /* @__PURE__ */ new Date()
100
+ });
101
+ } catch (err) {
102
+ this.logger.error("scheduled job failed", {
103
+ job,
104
+ key,
105
+ err
106
+ });
107
+ }
108
+ }
109
+ };
110
+ //#endregion
111
+ export { InlineJobs };
112
+
113
+ //# sourceMappingURL=jobs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobs.js","names":[],"sources":["../../src/workflows/jobs.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { JsonValue, Logger } from \"@headless-lms/core/types\";\nimport type { RecurringJob, ScheduledJob } from \"@headless-lms/core/shared/ports\";\nimport { cronMatches } from \"@headless-lms/core/automations\";\nimport { noopLogger } from \"@headless-lms/core/shared/logger\";\n\nconst MINUTE_MS = 60_000;\nconst MAX_TIMER_MS = 2_147_483_647;\n\nfunction floorUtcMinute(at: Date): number {\n const copy = new Date(at);\n copy.setUTCSeconds(0, 0);\n return copy.getTime();\n}\n\nfunction timerKey(job: string, key: string): string {\n return `${job}\\0${key}`;\n}\n\nexport class InlineJobs {\n private handlers = new Map<string, ScheduledJob>();\n private recurring: RecurringJob[] = [];\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private loop: ReturnType<typeof setInterval> | undefined;\n private lastMinute: number | undefined;\n private ticking = false;\n\n constructor(private readonly logger: Logger = noopLogger) {}\n\n register(handlers: ScheduledJob[], recurring: RecurringJob[]): void {\n this.handlers = new Map(handlers.map((handler) => [handler.job, handler]));\n this.recurring = [...recurring];\n }\n\n at(job: string, runAt: Date, key: string, payload: JsonValue): void {\n const id = timerKey(job, key);\n this.clear(id);\n this.arm(id, job, key, runAt.getTime(), payload);\n }\n\n cancel(job: string, key: string): void {\n this.clear(timerKey(job, key));\n }\n\n start(): void {\n this.stopLoop();\n this.tick();\n this.loop = setInterval(() => this.tick(), MINUTE_MS);\n this.loop.unref?.();\n }\n\n stop(): void {\n this.stopLoop();\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n\n private stopLoop(): void {\n if (this.loop) {\n clearInterval(this.loop);\n }\n this.loop = undefined;\n }\n\n private arm(id: string, job: string, key: string, runAtMs: number, payload: JsonValue): void {\n const delay = Math.min(Math.max(runAtMs - Date.now(), 0), MAX_TIMER_MS);\n const timer = setTimeout(() => {\n if (runAtMs > Date.now()) {\n this.arm(id, job, key, runAtMs, payload);\n return;\n }\n this.timers.delete(id);\n void this.fire(job, key, payload);\n }, delay);\n timer.unref?.();\n this.timers.set(id, timer);\n }\n\n private clear(id: string): void {\n const timer = this.timers.get(id);\n if (timer) {\n clearTimeout(timer);\n }\n this.timers.delete(id);\n }\n\n private tick(): void {\n if (this.ticking) {\n return;\n }\n this.ticking = true;\n void this.fireDue(new Date()).finally(() => {\n this.ticking = false;\n });\n }\n\n private async fireDue(now: Date): Promise<void> {\n const nowMs = floorUtcMinute(now);\n const from = this.lastMinute === undefined ? nowMs : this.lastMinute + MINUTE_MS;\n for (let minute = from; minute <= nowMs; minute += MINUTE_MS) {\n this.lastMinute = minute;\n const at = new Date(minute);\n for (const recurring of this.recurring) {\n if (cronMatches(recurring.cron, at)) {\n await this.fire(recurring.job, recurring.job, null);\n }\n }\n }\n }\n\n private async fire(job: string, key: string, payload: JsonValue): Promise<void> {\n const handler = this.handlers.get(job);\n if (!handler) {\n this.logger.error(\"scheduled job has no handler\", { job, key });\n return;\n }\n try {\n await handler.run(payload, { id: randomUUID(), startedAt: new Date() });\n } catch (err) {\n this.logger.error(\"scheduled job failed\", { job, key, err });\n }\n }\n}\n"],"mappings":";;;;AAMA,MAAM,YAAY;AAClB,MAAM,eAAe;AAErB,SAAS,eAAe,IAAkB;CACxC,MAAM,OAAO,IAAI,KAAK,EAAE;CACxB,KAAK,cAAc,GAAG,CAAC;CACvB,OAAO,KAAK,QAAQ;AACtB;AAEA,SAAS,SAAS,KAAa,KAAqB;CAClD,OAAO,GAAG,IAAI,IAAI;AACpB;AAEA,IAAa,aAAb,MAAwB;CAQO;CAP7B,2BAAmB,IAAI,IAA0B;CACjD,YAAoC,CAAC;CACrC,yBAA0B,IAAI,IAA2C;CACzE;CACA;CACA,UAAkB;CAElB,YAAY,SAAkC,YAAY;EAA7B,KAAA,SAAA;CAA8B;CAE3D,SAAS,UAA0B,WAAiC;EAClE,KAAK,WAAW,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;EACzE,KAAK,YAAY,CAAC,GAAG,SAAS;CAChC;CAEA,GAAG,KAAa,OAAa,KAAa,SAA0B;EAClE,MAAM,KAAK,SAAS,KAAK,GAAG;EAC5B,KAAK,MAAM,EAAE;EACb,KAAK,IAAI,IAAI,KAAK,KAAK,MAAM,QAAQ,GAAG,OAAO;CACjD;CAEA,OAAO,KAAa,KAAmB;EACrC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AAK,aAAa;GAClB,MAAM,KAAK,IAAI,KAAK,MAAM;GAC1B,KAAK,MAAM,aAAa,KAAK,WAC3B,IAAI,YAAY,UAAU,MAAM,EAAE,GAChC,MAAM,KAAK,KAAK,UAAU,KAAK,UAAU,KAAK,IAAI;EAGxD;CACF;CAEA,MAAc,KAAK,KAAa,KAAa,SAAmC;EAC9E,MAAM,UAAU,KAAK,SAAS,IAAI,GAAG;EACrC,IAAI,CAAC,SAAS;GACZ,KAAK,OAAO,MAAM,gCAAgC;IAAE;IAAK;GAAI,CAAC;GAC9D;EACF;EACA,IAAI;GACF,MAAM,QAAQ,IAAI,SAAS;IAAE,IAAI,WAAW;IAAG,2BAAW,IAAI,KAAK;GAAE,CAAC;EACxE,SAAS,KAAK;GACZ,KAAK,OAAO,MAAM,wBAAwB;IAAE;IAAK;IAAK;GAAI,CAAC;EAC7D;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@headless-lms/adapter-defaults",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./email": {
@@ -41,8 +41,8 @@
41
41
  ],
42
42
  "dependencies": {
43
43
  "pino": "^10.3.1",
44
- "@headless-lms/adapter-db": "0.3.0",
45
- "@headless-lms/core": "0.3.0"
44
+ "@headless-lms/adapter-db": "0.4.0",
45
+ "@headless-lms/core": "0.4.0"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/node": "^22.10.2",