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/dist/pg-boss.js DELETED
@@ -1,213 +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 } from "pg-boss";
6
- import { replaceKeyOf } from "./index.js";
7
- import { startTicking } from "./node.js";
8
- /** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
9
- const PREFIX = "logic-sdk.";
10
- /** A listener's or cron's queue: `logic-sdk.notifications.send`. */
11
- const queueName = (id) => `${PREFIX}${id}`;
12
- /** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
13
- const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
14
- /** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
15
- const queueOf = (job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
16
- /** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
17
- const queueConfig = (queue) => ({ ...queue, retryBackoff: true });
18
- /** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
19
- const tuningOf = (meta) => meta?.pgBoss;
20
- // A UUID of our own, so the v5 ids below can't collide with anyone else's.
21
- const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
22
- /**
23
- * 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
24
- * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
25
- */
26
- export function pgBossId(id) {
27
- const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
28
- hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
29
- hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
30
- const hex = hash.toString("hex", 0, 16);
31
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
32
- }
33
- /**
34
- * A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
35
- * never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
36
- * left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
37
- * at pickup. A last try that throws is `deadletter`, so it never uses the spare.
38
- */
39
- const rowOf = (job, replaceKey) => ({
40
- id: pgBossId(job.id),
41
- data: job,
42
- startAfter: job.runAt,
43
- retryLimit: job.attempts,
44
- retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
45
- singletonKey: replaceKey,
46
- });
47
- // SAFETY: `check` requires a database adapter. Only `drizzleAdapter`'s (Postgres) transactions run pg-boss's SQL: another
48
- // adapter fails at the first enqueue. Any adapter's `query` is for after 0.5.0 (pg-boss passes arrays and JSON).
49
- const inTx = (tx) => fromDrizzle(tx, sql);
50
- /**
51
- * Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
52
- * like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
53
- * `await boss.start()` first.
54
- *
55
- * ```ts
56
- * const boss = new PgBoss(process.env.DATABASE_URL!);
57
- * boss.on("error", console.error);
58
- * const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
59
- * ```
60
- */
61
- export function pgBoss(boss) {
62
- let database;
63
- const queueOptions = new Map();
64
- /**
65
- * pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
66
- * new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
67
- * on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
68
- */
69
- async function inQueue(name, write) {
70
- try {
71
- await write();
72
- }
73
- catch (error) {
74
- if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND"))
75
- throw error;
76
- await boss.createQueue(name, queueConfig(queueOptions.get(name)));
77
- await write();
78
- }
79
- }
80
- /**
81
- * The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
82
- * a job in `retry` has started, and isn't touched.
83
- */
84
- async function replaceWaiting(db, keys) {
85
- // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
86
- for (const key of [...new Set(keys)].sort()) {
87
- // one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
88
- await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
89
- // a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
90
- const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
91
- if (!locked.length)
92
- continue;
93
- const queued = await boss.findJobs(CALLS_QUEUE, { key, queued: true, db });
94
- const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
95
- if (waiting.length)
96
- await boss.deleteJob(CALLS_QUEUE, waiting, { db });
97
- }
98
- }
99
- return {
100
- holds: true, // `startAfter`, however far ahead
101
- replaces: true,
102
- /** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
103
- check({ listeners, crons, database: given }) {
104
- if (!given)
105
- throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
106
- database = given;
107
- for (const l of listeners)
108
- queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
109
- for (const c of crons)
110
- queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
111
- },
112
- /** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
113
- async enqueue(tx, jobs) {
114
- const db = inTx(tx);
115
- for (const [name, list] of Map.groupBy(jobs, queueOf)) {
116
- const keys = list.map(replaceKeyOf).filter((key) => key !== undefined);
117
- await inQueue(name, async () => {
118
- if (keys.length)
119
- await replaceWaiting(db, keys);
120
- await boss.insert(name, list.map((job) => rowOf(job, replaceKeyOf(job))), { db });
121
- });
122
- }
123
- },
124
- /** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
125
- async deliver() { },
126
- /**
127
- * A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
128
- * it has run, so it's no longer a call a newer one replaces.
129
- */
130
- async retry(id) {
131
- // its queue: the listener's or cron's (the id's prefix), or the calls queue. Looked up first: inside the
132
- // transaction, a lookup on pg-boss's own connection would wait for it on PGlite.
133
- const at = id.lastIndexOf("@");
134
- if (at < 0)
135
- return false; // not a job id
136
- const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
137
- const queues = await boss.getQueues(names);
138
- if (!database || !queues.length)
139
- return false;
140
- const uuid = pgBossId(id);
141
- return database.transaction(async (tx) => {
142
- const db = inTx(tx);
143
- for (const { name } of queues) {
144
- // failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
145
- const { affected } = await boss.retry(name, uuid, { db });
146
- if (!affected)
147
- continue;
148
- const [failed] = await boss.findJobs(name, { id: uuid, db });
149
- if (!failed)
150
- continue;
151
- // as new: retry count 0, and its retries again
152
- await boss.deleteJob(name, uuid, { db });
153
- await boss.insert(name, [rowOf(failed.data)], { db });
154
- return true;
155
- }
156
- return false;
157
- });
158
- },
159
- };
160
- }
161
- /**
162
- * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
163
- * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
164
- *
165
- * ```ts
166
- * await boss.start();
167
- * await work(registry, boss);
168
- * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
169
- * ```
170
- */
171
- export async function work(registry, boss, options = {}) {
172
- const { listeners, crons } = registry.definitions;
173
- const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
174
- const queues = [
175
- ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
176
- ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
177
- { name: CALLS_QUEUE, tuning: options.calls },
178
- ];
179
- /** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
180
- const settle = async (job) => {
181
- let reason;
182
- const fail = async (error) => {
183
- reason = error; // kept by pg-boss as the failed job's output
184
- };
185
- try {
186
- const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
187
- if (outcome === "failed")
188
- return { id: job.id, status: "deadletter", output: reason };
189
- return { id: job.id, status: "completed" };
190
- }
191
- catch (error) {
192
- return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
193
- }
194
- };
195
- for (const { name, tuning } of queues) {
196
- const config = queueConfig(tuning?.queue);
197
- const { partition: _createOnly, ...updatable } = config;
198
- await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
199
- await boss.updateQueue(name, updatable);
200
- await boss.work(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
201
- }
202
- // a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
203
- // They never get a try that could report, so say so here
204
- const ours = new Set(queues.map((q) => q.name));
205
- for (const q of await boss.getQueues())
206
- if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
207
- 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.`));
208
- if (!crons.length)
209
- return;
210
- // ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
211
- const stop = startTicking(registry, { sweepEvery: 0, onError });
212
- boss.once("stopped", () => void stop());
213
- }
@@ -1,64 +0,0 @@
1
- import { type JobsAdapter, type Runner, type SqlDatabase, type SweepResult } from "./index.ts";
2
- /**
3
- * The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
4
- * lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
5
- * the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
6
- */
7
- export interface JobsSql {
8
- /** `(pickup, rows)`: rows is JSON `[{ id, job, at, key }]`, `at` in epoch ms or null (due now, a sweep's after `pickup` seconds). A waiting row with the same `key` becomes the new one. */
9
- insert: string;
10
- /** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
11
- recordTicks: string;
12
- /** `()`: forgets ticks older than a day. */
13
- pruneTicks: string;
14
- /** `(receipt, lease, ids)`: the first claim, of rows nobody claimed. Returns `id`. */
15
- claimNew: string;
16
- /** `(receipt, lease)`: claims the one row due first. Returns `job` (JSON text) and `attempts`. */
17
- claimDue: string;
18
- /** `(lease, ids, receipt)`, on rows this receipt still owns, like the three below. */
19
- extend: string;
20
- /** `(seconds, error, ids, receipt)` */
21
- backOff: string;
22
- /** `(error, ids, receipt)` */
23
- markFailed: string;
24
- /** `(ids, receipt)` */
25
- remove: string;
26
- /** `(id)`: a failed row back in line. Returns `id`. */
27
- retry: string;
28
- /** `(id, job, error)`: a failed row, new or over the one there. */
29
- fail: string;
30
- }
31
- export interface DatabaseQueueOptions {
32
- /**
33
- * Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
34
- * job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
35
- * longer than that.
36
- */
37
- lease?: number;
38
- /** Seconds to wait after a failed try. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
39
- backoff?: (attempt: number) => number;
40
- }
41
- export interface OutboxOptions {
42
- /** Seconds a send owns its jobs: how soon one that crashed is sent again. Default 300. */
43
- lease?: number;
44
- /** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
45
- backoff?: (attempt: number) => number;
46
- /**
47
- * Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
48
- * are its `attempts`.
49
- */
50
- maxAttempts?: number;
51
- }
52
- /** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
53
- export interface StoredJobs extends JobsAdapter {
54
- /** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
55
- sweep(runner: Runner, options?: {
56
- limit?: number;
57
- }): Promise<SweepResult>;
58
- /** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
59
- retry(id: string): Promise<boolean>;
60
- }
61
- /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
62
- /** Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. */
63
- export declare const defaultBackoff: (attempt: number) => number;
64
- export declare function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxOptions, via?: JobsAdapter): StoredJobs;
@@ -1,188 +0,0 @@
1
- // Jobs in your database, written in the mutation's transaction: run from there (databaseQueue), or kept until a queue
2
- // has them (outbox). The table's statements are SQL, one set per database (postgres.ts, sqlite.ts), and run through
3
- // the database adapter's `query`, so this file knows no ORM and no driver.
4
- import { replaceKeyOf } from "./index.js";
5
- /** Seconds a job due now waits for the request that queued it, before a sweep may take it: how soon a crash after commit is noticed. */
6
- const PICKUP = 30;
7
- /**
8
- * Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer, and pg-boss's default
9
- * expiry. Past it, a job that hangs is taken over like a crashed one. A longer job needs a `lease` that long.
10
- */
11
- const MAX_EXTEND = 15 * 60;
12
- /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
13
- /** Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. */
14
- export const defaultBackoff = (attempt) => Math.exp(Math.min(attempt, 10));
15
- export function storedJobs(sql, database, options, via) {
16
- const lease = options.lease ?? 300;
17
- const maxAttempts = options.maxAttempts ?? 10;
18
- const backoff = options.backoff ?? defaultBackoff;
19
- /** Outside a mutation: on the database itself. */
20
- const query = (text, params) => database.query(database.db, text, params);
21
- const list = (ids) => JSON.stringify(ids);
22
- // These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
23
- // newer runner's work, and a handoff that finishes late can't delete the failure a consumer already recorded. By
24
- // receipt, not attempt number: `retry(id)` starts those again at 1.
25
- const markFailed = (ids, claim, error) => query(sql.markFailed, [describe(error), list(ids), claim.receipt]);
26
- const backOff = (ids, claim, error) => query(sql.backOff, [backoff(claim.attempt), describe(error), list(ids), claim.receipt]);
27
- const remove = (ids, claim) => query(sql.remove, [list(ids), claim.receipt]);
28
- /**
29
- * While a job runs, its lease is extended, as Laravel Cloud does on SQS: a slow job stays its runner's, and a dead
30
- * runner's job is free a lease later. Returns the stop, which waits for the extension on its way: landing after a
31
- * backoff, it would replace the backoff.
32
- */
33
- function keepExtending(job, claim, runner) {
34
- const until = Date.now() + MAX_EXTEND * 1000;
35
- let extending = Promise.resolve();
36
- const timer = setInterval(() => {
37
- if (Date.now() >= until)
38
- return clearInterval(timer);
39
- extending = extending
40
- .then(() => query(sql.extend, [lease, list([job.id]), claim.receipt]))
41
- .catch((e) => runner.report(e, job, claim.attempt));
42
- }, (lease * 1000) / 3);
43
- return () => {
44
- clearInterval(timer);
45
- return extending;
46
- };
47
- }
48
- /**
49
- * Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
50
- * (tries left: back off), or done and discarded (delete the row).
51
- */
52
- async function run(job, claim, runner) {
53
- const stopExtending = keepExtending(job, claim, runner);
54
- let outcome;
55
- try {
56
- outcome = await runner
57
- .run(job, {
58
- attempt: claim.attempt,
59
- fail: async (error) => {
60
- await markFailed([job.id], claim, error);
61
- },
62
- })
63
- .finally(stopExtending);
64
- }
65
- catch (e) {
66
- await backOff([job.id], claim, e);
67
- return "retrying";
68
- }
69
- if (outcome !== "failed")
70
- await remove([job.id], claim);
71
- return outcome;
72
- }
73
- /** Hand claimed jobs to `via` in one send. Done once the queue has them; a failed send keeps them all for a retry. */
74
- async function handOff(queue, jobs, claim, runner) {
75
- const ids = jobs.map((j) => j.id);
76
- try {
77
- await queue.deliver(jobs, runner);
78
- }
79
- catch (e) {
80
- for (const job of jobs)
81
- runner.report(e, job, claim.attempt); // the queue's failure, not the listener's: run never saw it
82
- if (claim.attempt >= maxAttempts) {
83
- await markFailed(ids, claim, e);
84
- return "failed";
85
- }
86
- await backOff(ids, claim, e);
87
- return "retrying";
88
- }
89
- await remove(ids, claim);
90
- return "done";
91
- }
92
- /** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
93
- async function recordTicks(tx, ticks) {
94
- if (!ticks.length)
95
- return new Set();
96
- const first = await database.query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
97
- await database.query(tx, sql.pruneTicks, []);
98
- return new Set(first.map((row) => row.id));
99
- }
100
- const settle = (job, claim, runner) => (via ? handOff(via, [job], claim, runner) : run(job, claim, runner));
101
- /** The first claim of jobs just committed, by the request that queued them: the ones no sweep took meanwhile. */
102
- async function claimNew(jobs) {
103
- const claim = { receipt: crypto.randomUUID(), attempt: 1 };
104
- const rows = await query(sql.claimNew, [claim.receipt, lease, list(jobs.map((j) => j.id))]);
105
- const ids = new Set(rows.map((row) => row.id));
106
- return { claim, won: jobs.filter((j) => ids.has(j.id)) }; // in emit order: RETURNING has none
107
- }
108
- return {
109
- holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
110
- replaces: true, // a waiting row is replaced in place; under `via` too, since rows wait here until they're due
111
- /** Must share the transaction it writes in. */
112
- check({ database: given }) {
113
- if (given && given.db !== database.db)
114
- throw new Error(`[logic-sdk] ${via ? "outbox(database, queue)" : "databaseQueue(database)"} must use the same database as \`database\`: jobs are written in your mutation's transaction. ` +
115
- "A queue in another database goes behind an outbox: outbox(database, queue).");
116
- },
117
- /**
118
- * Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
119
- * request. Delayed: available from `runAt`, for a sweep. A cron's minute runs once: only ticks nobody recorded yet.
120
- */
121
- async enqueue(tx, jobs) {
122
- const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
123
- const rows = jobs
124
- .filter((j) => j.kind !== "cron" || firstTicks.has(j.id))
125
- .map((j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: replaceKeyOf(j) ?? null }))
126
- // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
127
- .sort((a, b) => byText(a.key ?? "", b.key ?? ""));
128
- if (rows.length)
129
- await database.query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
130
- },
131
- /**
132
- * After commit, in this request: each job is claimed just before it runs, so a slow or dead one doesn't spend the
133
- * others' attempt. Under `via` they're claimed together, for one send. What isn't claimed yet when the process dies
134
- * is a sweep's, as a first try.
135
- */
136
- async deliver(jobs, runner) {
137
- const due = jobs.filter((j) => !j.runAt);
138
- if (!due.length)
139
- return;
140
- if (via) {
141
- const { claim, won } = await claimNew(due);
142
- if (won.length)
143
- await handOff(via, won, claim, runner);
144
- return;
145
- }
146
- for (const job of due) {
147
- try {
148
- const { claim, won } = await claimNew([job]);
149
- if (won.length)
150
- await run(job, claim, runner);
151
- }
152
- catch (e) {
153
- runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
154
- }
155
- }
156
- },
157
- /** One at a time, so every claim gets a full lease and a job the queue rejects (too big) can't hold back the others. */
158
- async sweep(runner, { limit = 100 } = {}) {
159
- const result = { done: 0, failed: 0, discarded: 0, retrying: 0 };
160
- for (let i = 0; i < limit; i++) {
161
- const receipt = crypto.randomUUID();
162
- const [row] = await query(sql.claimDue, [receipt, lease]);
163
- if (!row)
164
- break;
165
- const job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
166
- const attempt = Number(row.attempts);
167
- try {
168
- result[await settle(job, { receipt, attempt }, runner)]++;
169
- }
170
- catch (e) {
171
- runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
172
- }
173
- }
174
- return result;
175
- },
176
- /** Failed rows only: a pending one belongs to its runner or a sweep, and resetting it could run it twice at once. */
177
- async retry(id) {
178
- return (await query(sql.retry, [id])).length > 0;
179
- },
180
- /** A job that failed for good in a queue consumer: keep it as a failed row, so you can query it and `retry` it. */
181
- async fail(job, error) {
182
- await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
183
- },
184
- };
185
- }
186
- /** Not `localeCompare`: processes with another locale would lock in another order. */
187
- const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
188
- const describe = (e) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message