logic-sdk 0.7.1 → 0.7.3

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 (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
package/src/jobs.ts DELETED
@@ -1,307 +0,0 @@
1
- import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.ts";
2
- import { isDue, parseSchedule } from "./schedule.ts";
3
- import type {
4
- ActionCtx,
5
- Call,
6
- CallJob,
7
- CronJob,
8
- DatabaseAdapter,
9
- Delivery,
10
- Envelope,
11
- FailureInfo,
12
- Fn,
13
- InProcess,
14
- Job,
15
- JobOutcome,
16
- JobsAdapter,
17
- JobScope,
18
- Jobs,
19
- CronRun,
20
- ListenerEvent,
21
- RegisteredCron,
22
- RegisteredFn,
23
- RegisteredListener,
24
- RunJobOptions,
25
- Runner,
26
- } from "./types.ts";
27
- import { RUNS_NOW } from "./types.ts";
28
-
29
- const IN_PROCESS: InProcess = {
30
- [RUNS_NOW]: true,
31
- async deliver(jobs, { run }) {
32
- // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
33
- for (const job of jobs) await run({ ...job, attempts: 1 });
34
- },
35
- };
36
- /**
37
- * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
38
- * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
39
- */
40
- export const inProcess = (): InProcess => IN_PROCESS;
41
- /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
42
- export const runsNow = (adapter: JobsAdapter) => adapter === IN_PROCESS;
43
-
44
- /**
45
- * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
46
- * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
47
- */
48
- export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
49
-
50
- /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
51
- export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
52
- kind: "delivery",
53
- id: `${l.id}@${e.id}`,
54
- listener: l.id,
55
- envelope: e,
56
- attempts: l.listener.attempts ?? 1,
57
- });
58
-
59
- /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
60
- export interface JobsDeps {
61
- listeners: readonly RegisteredListener[];
62
- crons: readonly RegisteredCron[];
63
- functions: readonly RegisteredFn[];
64
- idOf(x: object): string;
65
- jobsAdapter: JobsAdapter;
66
- database: DatabaseAdapter<unknown, unknown> | undefined;
67
- jobScope: JobScope | undefined;
68
- maxEventDepth: number;
69
- now(): Date;
70
- wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
71
- report(error: unknown, info: FailureInfo): void;
72
- /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
73
- runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
74
- /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
75
- handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
76
- }
77
-
78
- /**
79
- * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
80
- * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
81
- */
82
- export function makeJobs(deps: JobsDeps) {
83
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
84
- const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
85
- const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
86
-
87
- // ── listeners ────────────────────────────────────────────────────────────
88
- const byEvent = new Map<string, RegisteredListener[]>();
89
- for (const l of listeners) {
90
- const name = idOf(l.event);
91
- byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
92
- }
93
-
94
- const listenerById = new Map(listeners.map((l) => [l.id, l]));
95
-
96
- const scheduled = crons.map((c) => ({ ...c, schedule: parseSchedule(c.cron.schedule) }));
97
- const cronById = new Map(crons.map((c) => [c.id, c]));
98
- const fnById = new Map(functions.map((f) => [f.id, f]));
99
-
100
- /**
101
- * A job that waits (a listener's `delay`, `ctx.schedule`) needs an adapter that holds it: run early it'd be wrong,
102
- * kept in memory it'd be lost on restart. Laravel's sync queue drops the delay; we refuse instead.
103
- */
104
- function checkHold(what: string, seconds: number) {
105
- const { holds } = jobsAdapter;
106
- if (!holds)
107
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
108
- if (holds !== true && seconds > holds.max)
109
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s; your jobs adapter holds jobs for at most ${holds.max}s. Put an outbox in front, outbox(database, queue): it holds them as long as needed.`);
110
- }
111
- for (const l of listeners) if (l.listener.delay) checkHold(l.id, l.listener.delay);
112
-
113
- /**
114
- * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
115
- * scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
116
- * delay) are dropped, reported once.
117
- */
118
- function toJobs(envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>): Job[] {
119
- /** Its `when`, if any. A throw is a bug in the app: it fails the mutation, naming the listener. */
120
- const wants = (l: RegisteredListener, e: Envelope, payload: unknown) => {
121
- try {
122
- return !l.listener.when || l.listener.when(payload);
123
- } catch (error) {
124
- throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
125
- }
126
- };
127
- const fits = (job: { depth: number }) => job.depth <= maxEventDepth;
128
- const deepEvent = envelopes.find((e) => !fits(e));
129
- const deepCall = calls.find((c) => !fits(c));
130
- const loop = (what: string) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
131
- if (deepEvent) report(loop(deepEvent.name), { source: deepEvent.name });
132
- else if (deepCall) report(loop(deepCall.fn), infoOf(deepCall));
133
- const deliveries = envelopes.filter(fits).flatMap((e) =>
134
- (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).map((l): Delivery => {
135
- const job = deliveryOf(l, e);
136
- const delay = l.listener.delay;
137
- if (delay) job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
138
- return job;
139
- }),
140
- );
141
- return [...deliveries, ...calls.filter(fits)];
142
- }
143
-
144
- /** An adapter that couldn't take a commit's jobs: each one may be lost, so each is reported. */
145
- const reportEach = (error: unknown, jobs: Job[]) => {
146
- for (const job of jobs) report(error, { source: "(jobs adapter)", job });
147
- };
148
-
149
- /** What `onError` hears about a job. */
150
- const infoOf = (job: Job, attempt?: number): FailureInfo =>
151
- job.kind === "delivery"
152
- ? { source: job.listener, job, attempt }
153
- : { source: job.kind === "cron" ? job.cron : job.fn, job, attempt };
154
-
155
- /** Who a stored job runs as: `jobs.scope.load` rebuilds it; null means discard it (reported). */
156
- async function scopeOf(job: Job, stored: object, attempt: number): Promise<object | null> {
157
- if (!jobScope?.load) return stored;
158
- const loaded = await jobScope.load(stored);
159
- if (loaded === undefined) throw new Error(`[logic-sdk] jobs.scope.load returned undefined for ${job.id}. Return the scope, or null to discard the job.`);
160
- if (loaded === null) report(new Error(`[logic-sdk] jobs.scope.load returned null for ${job.id}, so it was discarded.`), { ...infoOf(job, attempt), outcome: "discarded" });
161
- return loaded;
162
- }
163
-
164
- /**
165
- * Run one job: a listener's share of an event, a cron's run, or a scheduled call. Reports every failure; throws only when a retry might
166
- * help and there are tries left. `fail` keeps a job that failed for good. The jobs it queues land in `queued`, for
167
- * `deliver` to run once this one is settled; without it (`registry.jobs.run`, in a consumer) they're delivered at once.
168
- */
169
- async function runJob(job: Job, { attempt = 1, fail }: RunJobOptions = {}, queued?: Job[]): Promise<JobOutcome> {
170
- const info = infoOf(job, attempt);
171
- // read before narrowing: a job queued by another version can have a kind this one doesn't know
172
- const { id, kind }: { id: string; kind: string } = job;
173
- const failed = async (error: unknown) => {
174
- report(error, { ...info, outcome: "failed" });
175
- await fail?.(error);
176
- return "failed" as const;
177
- };
178
- /** One try of the job's `attempts`. */
179
- const attemptOnce = async (work: () => Promise<JobOutcome>): Promise<JobOutcome> => {
180
- const { attempts } = job;
181
- // its last try was claimed but never finished: a crash, or slower than the lease (Laravel checks this too)
182
- if (attempt > attempts)
183
- return failed(
184
- new Error(`[logic-sdk] ${job.id} has used its ${attempts} attempt(s): the last one never finished (crashed or outlived the lease), or its result wasn't recorded.`),
185
- );
186
- try {
187
- return await work();
188
- } catch (error) {
189
- // a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
190
- const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
191
- const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
192
- if (!retrying) return failed(error);
193
- report(error, { ...info, outcome: "retry" });
194
- throw error;
195
- }
196
- };
197
-
198
- // code this process doesn't have (renamed, removed, or not deployed here yet) is a try like any other, as Laravel
199
- // treats a missing class: in a rolling deploy the new code gets a later one.
200
- const cantRun = (why: string) =>
201
- attemptOnce(async () => {
202
- throw new Error(`[logic-sdk] ${why}`);
203
- });
204
- const missing = (what: string, id: string) =>
205
- cantRun(`${id} isn't a registered ${what} (renamed, removed or not deployed here yet?), so job ${job.id} can't run.`);
206
- if (job.kind === "cron") {
207
- const c = cronById.get(job.cron);
208
- if (!c) return missing("cron", job.cron);
209
- return attemptOnce(async () => {
210
- // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
211
- const { scope, meta, handler } = c.cron;
212
- const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
213
- await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () =>
214
- handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
215
- );
216
- return "done";
217
- });
218
- }
219
- if (job.kind === "call") {
220
- const f = fnById.get(job.fn);
221
- if (!f) return missing("function", job.fn);
222
- return attemptOnce(async () => {
223
- const scope = await scopeOf(job, job.scope, attempt);
224
- if (!scope) return "discarded";
225
- await runAs(f.fn, job.input, scope, job.depth, queued);
226
- return "done";
227
- });
228
- }
229
- if (job.kind !== "delivery") return cantRun(`job ${id} has kind ${JSON.stringify(kind)}, which this version can't run.`);
230
- const l = listenerById.get(job.listener);
231
- if (!l) return missing("listener", job.listener);
232
- const { envelope } = job;
233
- return attemptOnce(async () => {
234
- const scope = await scopeOf(job, envelope.scope, attempt);
235
- if (!scope) return "discarded";
236
- await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
237
- // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
238
- if (idOf(l.event) !== envelope.name)
239
- throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
240
- const r = await l.event.payload["~standard"].validate(envelope.payload);
241
- if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
242
- const payload = r.value;
243
- const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
244
- return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
245
- });
246
- return "done";
247
- });
248
- }
249
-
250
- /** A runner whose jobs' own jobs are collected in `queued`. */
251
- const runnerInto = (queued: Job[]): Runner => ({
252
- run: (job, options) => runJob(job, options, queued),
253
- report: (e, job, attempt) => report(e, infoOf(job, attempt)),
254
- });
255
-
256
- /**
257
- * Deliver jobs, then the jobs those queued, and so on. A job is settled before what it queued starts, as a Laravel
258
- * worker deletes a job before it pops the ones it pushed: a crash in a follow-up can't run the job again.
259
- */
260
- async function deliver(jobs: Job[]) {
261
- while (jobs.length) {
262
- const batch = jobs;
263
- jobs = [];
264
- await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
265
- }
266
- }
267
-
268
- /**
269
- * The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
270
- * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
271
- */
272
- function due(at: Date, only?: string): CronJob[] {
273
- if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
274
- const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
275
- const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
276
- return scheduled
277
- .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
278
- .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
279
- }
280
-
281
- const jobs: Jobs = {
282
- // a consumer's own `fail` (pg-boss's work(), which records the reason itself) wins over the adapter's
283
- run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (keepFailed && ((error) => keepFailed(job, error))) }),
284
- async tick(at = now()) {
285
- const jobs = due(at);
286
- if (!jobs.length) return [];
287
- if (enqueue) {
288
- if (!database) throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
289
- await database.transaction((tx) => enqueue(tx, jobs));
290
- }
291
- await deliver(jobs);
292
- return jobs.map((job) => job.cron);
293
- },
294
- async sweep(options) {
295
- const queued: Job[] = [];
296
- const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
297
- await deliver(queued);
298
- return result;
299
- },
300
- async retry(id) {
301
- if (!jobsAdapter.retry) throw new Error(`[logic-sdk] your jobs adapter keeps no jobs, so there's nothing to retry (${id}). databaseQueue(database), outbox(database, queue) and pgBoss(boss) do.`);
302
- return jobsAdapter.retry(id);
303
- },
304
- };
305
-
306
- return { toJobs, deliver, jobs, due, checkHold };
307
- }
package/src/pg-boss.ts DELETED
@@ -1,241 +0,0 @@
1
- /// <reference types="node" />
2
- // pg-boss runs on Node (`pg`, `node:events`), so this subpath may too; the core stays runtime-neutral.
3
- import { createHash } from "node:crypto";
4
- import { sql } from "drizzle-orm";
5
- import { fromDrizzle, type Db, type DrizzleTransactionLike, type JobInsert, type JobResult, type PgBoss, type Queue, type WorkOptions } from "pg-boss";
6
- import { replaceKeyOf, type DatabaseAdapter, type ForListeners, type Job, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
7
- import { startTicking } from "./node.ts";
8
-
9
- /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
10
- export interface PgBossTuning {
11
- /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
12
- queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
13
- /** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
14
- worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
15
- }
16
-
17
- /**
18
- * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
19
- * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
20
- * listener's `attempts`, and the other adapters ignore it.
21
- */
22
- export type PgBossMeta = ForListeners<{ pgBoss?: PgBossTuning }>;
23
-
24
- /** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
25
- const PREFIX = "logic-sdk.";
26
- /** A listener's or cron's queue: `logic-sdk.notifications.send`. */
27
- const queueName = (id: string) => `${PREFIX}${id}`;
28
- /** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
29
- const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
30
-
31
- /** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
32
- const queueOf = (job: Job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
33
-
34
- /** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
35
- const queueConfig = (queue: PgBossTuning["queue"]) => ({ ...queue, retryBackoff: true });
36
-
37
- /** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
38
- const tuningOf = (meta: Readonly<Record<string, unknown>> | undefined) => meta?.pgBoss as PgBossTuning | undefined;
39
-
40
- // A UUID of our own, so the v5 ids below can't collide with anyone else's.
41
- const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
42
-
43
- /**
44
- * The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
45
- * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
46
- */
47
- export function pgBossId(id: string): string {
48
- const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
49
- hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
50
- hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
51
- const hex = hash.toString("hex", 0, 16);
52
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
53
- }
54
-
55
- /**
56
- * A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
57
- * never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
58
- * left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
59
- * at pickup. A last try that throws is `deadletter`, so it never uses the spare.
60
- */
61
- const rowOf = (job: Job, replaceKey?: string): JobInsert<Job> => ({
62
- id: pgBossId(job.id),
63
- data: job,
64
- startAfter: job.runAt,
65
- retryLimit: job.attempts,
66
- retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
67
- singletonKey: replaceKey,
68
- });
69
-
70
- // SAFETY: `check` requires a database adapter. Only `drizzleAdapter`'s (Postgres) transactions run pg-boss's SQL: another
71
- // adapter fails at the first enqueue. Any adapter's `query` is for after 0.5.0 (pg-boss passes arrays and JSON).
72
- const inTx = (tx: unknown): Db => fromDrizzle(tx as DrizzleTransactionLike, sql);
73
-
74
- /**
75
- * Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
76
- * like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
77
- * `await boss.start()` first.
78
- *
79
- * ```ts
80
- * const boss = new PgBoss(process.env.DATABASE_URL!);
81
- * boss.on("error", console.error);
82
- * const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
83
- * ```
84
- */
85
- export function pgBoss(boss: PgBoss): JobsAdapter {
86
- let database: DatabaseAdapter<unknown, unknown> | undefined;
87
- const queueOptions = new Map<string, PgBossTuning["queue"]>();
88
-
89
- /**
90
- * pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
91
- * new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
92
- * on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
93
- */
94
- async function inQueue(name: string, write: () => Promise<unknown>) {
95
- try {
96
- await write();
97
- } catch (error) {
98
- if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND")) throw error;
99
- await boss.createQueue(name, queueConfig(queueOptions.get(name)));
100
- await write();
101
- }
102
- }
103
-
104
- /**
105
- * The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
106
- * a job in `retry` has started, and isn't touched.
107
- */
108
- async function replaceWaiting(db: Db, keys: string[]) {
109
- // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
110
- for (const key of [...new Set(keys)].sort()) {
111
- // one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
112
- await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
113
- // a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
114
- const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
115
- if (!locked.length) continue;
116
- const queued = await boss.findJobs<Job>(CALLS_QUEUE, { key, queued: true, db });
117
- const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
118
- if (waiting.length) await boss.deleteJob(CALLS_QUEUE, waiting, { db });
119
- }
120
- }
121
-
122
- return {
123
- holds: true, // `startAfter`, however far ahead
124
- replaces: true,
125
- /** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
126
- check({ listeners, crons, database: given }) {
127
- if (!given) throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
128
- database = given;
129
- for (const l of listeners) queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
130
- for (const c of crons) queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
131
- },
132
- /** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
133
- async enqueue(tx, jobs) {
134
- const db = inTx(tx);
135
- for (const [name, list] of Map.groupBy(jobs, queueOf)) {
136
- const keys = list.map(replaceKeyOf).filter((key) => key !== undefined);
137
- await inQueue(name, async () => {
138
- if (keys.length) await replaceWaiting(db, keys);
139
- await boss.insert(name, list.map((job) => rowOf(job, replaceKeyOf(job))), { db });
140
- });
141
- }
142
- },
143
- /** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
144
- async deliver() {},
145
- /**
146
- * A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
147
- * it has run, so it's no longer a call a newer one replaces.
148
- */
149
- async retry(id) {
150
- // its queue: the listener's or cron's (the id's prefix), or the calls queue. Looked up first: inside the
151
- // transaction, a lookup on pg-boss's own connection would wait for it on PGlite.
152
- const at = id.lastIndexOf("@");
153
- if (at < 0) return false; // not a job id
154
- const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
155
- const queues = await boss.getQueues(names);
156
- if (!database || !queues.length) return false;
157
- const uuid = pgBossId(id);
158
- return database.transaction(async (tx) => {
159
- const db = inTx(tx);
160
- for (const { name } of queues) {
161
- // failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
162
- const { affected } = await boss.retry(name, uuid, { db });
163
- if (!affected) continue;
164
- const [failed] = await boss.findJobs<Job>(name, { id: uuid, db });
165
- if (!failed) continue;
166
- // as new: retry count 0, and its retries again
167
- await boss.deleteJob(name, uuid, { db });
168
- await boss.insert(name, [rowOf(failed.data)], { db });
169
- return true;
170
- }
171
- return false;
172
- });
173
- },
174
- };
175
- }
176
-
177
- export interface PgBossWorkOptions {
178
- /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
179
- calls?: PgBossTuning;
180
- /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
181
- onError?: (error: unknown) => void;
182
- }
183
-
184
- /**
185
- * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
186
- * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
187
- *
188
- * ```ts
189
- * await boss.start();
190
- * await work(registry, boss);
191
- * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
192
- * ```
193
- */
194
- export async function work(
195
- registry: Pick<Registry, "definitions"> & { jobs: Pick<Jobs, "run" | "tick" | "sweep"> },
196
- boss: PgBoss,
197
- options: PgBossWorkOptions = {},
198
- ): Promise<void> {
199
- const { listeners, crons } = registry.definitions;
200
- const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
201
- const queues: { name: string; tuning: PgBossTuning | undefined }[] = [
202
- ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
203
- ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
204
- { name: CALLS_QUEUE, tuning: options.calls },
205
- ];
206
-
207
- /** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
208
- const settle = async (job: { id: string; data: Job; retryCount: number }): Promise<JobResult> => {
209
- let reason: unknown;
210
- const fail = async (error: unknown) => {
211
- reason = error; // kept by pg-boss as the failed job's output
212
- };
213
- try {
214
- const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
215
- if (outcome === "failed") return { id: job.id, status: "deadletter", output: reason };
216
- return { id: job.id, status: "completed" };
217
- } catch (error) {
218
- return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
219
- }
220
- };
221
-
222
- for (const { name, tuning } of queues) {
223
- const config = queueConfig(tuning?.queue);
224
- const { partition: _createOnly, ...updatable } = config;
225
- await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
226
- await boss.updateQueue(name, updatable);
227
- await boss.work<Job>(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
228
- }
229
-
230
- // a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
231
- // They never get a try that could report, so say so here
232
- const ours = new Set(queues.map((q) => q.name));
233
- for (const q of await boss.getQueues())
234
- if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
235
- onError(new Error(`[logic-sdk] pg-boss queue ${q.name} has ${q.queuedCount} job(s) and no listener or cron here (renamed or removed?). Give it its old id back, or delete the queue.`));
236
-
237
- if (!crons.length) return;
238
- // ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
239
- const stop = startTicking(registry, { sweepEvery: 0, onError });
240
- boss.once("stopped", () => void stop());
241
- }