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
@@ -0,0 +1,514 @@
1
+ import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.js";
2
+ import { isDue, parseSchedule } from "./schedule.js";
3
+ export const isPlainObject = (v) => !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
4
+ /**
5
+ * JSON with object keys sorted, so `{ a, b }` and `{ b, a }` are one input, like TanStack Query's `hashKey`. Undefined
6
+ * properties drop out, as in JSON; array order counts. The input as passed, before its schema runs (defaults aren't
7
+ * applied), so a schema change doesn't move what's waiting.
8
+ */
9
+ const canonical = (value) => JSON.stringify(value, (_, v) => (isPlainObject(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v)) ?? "";
10
+ /**
11
+ * What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
12
+ * newer call with the same one replaces it while it waits. Undefined for every other job.
13
+ */
14
+ export const replaceKeyOf = (job) => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
15
+ /**
16
+ * The key adapters that keep one waiting job per key (`replaces: true`) store: a delivery's `unique` as it is, a call's
17
+ * `replaceKeyOf` as `<function id>@<sha-256 of the input>`, so a large input still fits an index and the function
18
+ * stays readable. Undefined for every other job.
19
+ */
20
+ export async function storedUniqueKey(job) {
21
+ if (job.kind === "delivery")
22
+ return job.unique;
23
+ if (job.kind !== "call" || !job.replace)
24
+ return undefined;
25
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
26
+ return `${job.fn}@${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
27
+ }
28
+ /**
29
+ * A `failed({ scope })` filter as the fields it matches: `{ organization: { id: "o1" } }` is `organization.id = "o1"`.
30
+ * Strings, numbers, booleans and null; never an array or an empty object, which two databases would read differently.
31
+ */
32
+ function scopeMatches(filter) {
33
+ const out = [];
34
+ const walk = (value, path) => {
35
+ if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) {
36
+ out.push({ path, value });
37
+ return;
38
+ }
39
+ const where = path.length ? path.join(".") : "scope";
40
+ if (!isPlainObject(value))
41
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) matches strings, numbers, booleans and null: ${where} is ${Array.isArray(value) ? "an array" : typeof value}.`);
42
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined);
43
+ if (!keys.length)
44
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) matches fields: ${where} is an empty object.`);
45
+ for (const k of keys)
46
+ walk(value[k], [...path, k]);
47
+ };
48
+ walk(filter, []);
49
+ return out;
50
+ }
51
+ /**
52
+ * Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
53
+ * core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
54
+ */
55
+ export const defaultBackoff = (attempt) => Math.exp(Math.min(attempt, 10));
56
+ /** Where the docs list each adapter and what it can do. */
57
+ export const ADAPTERS = "see Jobs, Adapters in the docs";
58
+ /** The loops running each adapter's jobs in this process (`work()`), by adapter: every registry on it shares them. */
59
+ const localWorkers = new WeakMap();
60
+ const workerSet = (adapter) => {
61
+ let set = localWorkers.get(adapter);
62
+ if (!set)
63
+ localWorkers.set(adapter, (set = new Set()));
64
+ return set;
65
+ };
66
+ /** What an adapter's `connect` gets as `setup.workers`: does a loop here take this job, and wake them. */
67
+ export function workersOf(adapter) {
68
+ const set = workerSet(adapter);
69
+ return {
70
+ takes: (job) => [...set].some((w) => !w.queues || w.queues.includes(job.queue ?? "default")),
71
+ wake: (count) => {
72
+ for (const worker of set)
73
+ worker.wake(count);
74
+ },
75
+ };
76
+ }
77
+ /** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
78
+ function minuteOf(at, what) {
79
+ if (Number.isNaN(at.getTime()))
80
+ throw new Error(`[logic-sdk] ${what} needs a valid date (got ${String(at)}).`);
81
+ const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
82
+ return { minute, stamp: minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z" };
83
+ }
84
+ /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
85
+ export const deliveryOf = (l, e) => ({
86
+ kind: "delivery",
87
+ id: `${l.id}@${e.id}`,
88
+ listener: l.id,
89
+ envelope: e,
90
+ attempts: l.listener.attempts ?? 1,
91
+ });
92
+ /**
93
+ * A try that runs past its timeout: aborts its signal (its `ctx.signal`, and no new `ctx.run` starts) and fails the try,
94
+ * as Laravel's `$timeout` and Oban's `timeout/1` count it. JavaScript can't kill it, so what it still does is ignored.
95
+ */
96
+ async function stopAfter(work, seconds, stop, why) {
97
+ let timer;
98
+ const timedOut = new Promise((_, reject) => {
99
+ timer = setTimeout(() => {
100
+ const error = new Error(`[logic-sdk] ${why}`);
101
+ stop.abort(error);
102
+ reject(error);
103
+ }, seconds * 1000);
104
+ });
105
+ work.catch(() => { }); // it may still settle after the timeout: not this try's anymore
106
+ try {
107
+ return await Promise.race([work, timedOut]);
108
+ }
109
+ finally {
110
+ clearTimeout(timer);
111
+ }
112
+ }
113
+ /**
114
+ * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
115
+ * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
116
+ */
117
+ export function makeJobs(deps) {
118
+ const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, queues, now, wrap, report, runAs, handlerCtx } = deps;
119
+ /** Your adapter, as messages name it: by what it can't do, and by its own name. */
120
+ const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
121
+ // ── queues ───────────────────────────────────────────────────────────────
122
+ for (const q of queues)
123
+ if (typeof q !== "string" || !q || q === "default")
124
+ throw new Error(`[logic-sdk] jobs.queues takes names besides "default" (got ${JSON.stringify(q)}).`);
125
+ if (new Set(queues).size !== queues.length)
126
+ throw new Error(`[logic-sdk] jobs.queues lists a queue twice: ${queues.join(", ")}.`);
127
+ const queueNames = ["default", ...queues];
128
+ if (queues.length && !jobsAdapter.queues)
129
+ throw new Error(`[logic-sdk] jobs.queues declares ${queues.join(", ")}, but ${yours} keeps every job in one queue. Use one that keeps them apart (${ADAPTERS}).`);
130
+ if (typeof jobsAdapter.queues === "object")
131
+ for (const q of queueNames)
132
+ if (!jobsAdapter.queues.includes(q))
133
+ throw new Error(`[logic-sdk] ${yours} has no queue for "${q}": give it one (it has ${jobsAdapter.queues.join(", ") || "none"}).`);
134
+ /** A queue someone named: one of `jobs.queues`, or `"default"`. */
135
+ function checkQueue(what, queue) {
136
+ if (queue !== undefined && !queueNames.includes(queue))
137
+ throw new Error(`[logic-sdk] ${what} has queue ${JSON.stringify(queue)}, which jobs.queues doesn't declare (${queueNames.join(", ")}).`);
138
+ }
139
+ for (const l of listeners)
140
+ checkQueue(l.id, l.listener.queue);
141
+ for (const c of crons)
142
+ checkQueue(c.id, c.cron.queue);
143
+ if (failedStore && jobsAdapter.failed)
144
+ throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
145
+ const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
146
+ if (enqueue && crons.length && !database)
147
+ throw new Error(`[logic-sdk] Crons need \`database\` with ${yours}: their runs are written in a transaction of their own.`);
148
+ /** Cron runs, queued in a transaction of their own (a stored adapter runs each minute once there). */
149
+ const enqueueAlone = async (jobs) => {
150
+ if (enqueue && database)
151
+ await database.transaction((tx) => enqueue(tx, jobs));
152
+ };
153
+ // ── listeners ────────────────────────────────────────────────────────────
154
+ const byEvent = new Map();
155
+ for (const l of listeners) {
156
+ const name = idOf(l.event);
157
+ byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
158
+ }
159
+ const listenerById = new Map(listeners.map((l) => [l.id, l]));
160
+ const scheduled = crons.map((c) => ({ ...c, schedule: parseSchedule(c.cron.schedule) }));
161
+ const cronById = new Map(crons.map((c) => [c.id, c]));
162
+ const fnById = new Map(functions.map((f) => [f.id, f]));
163
+ /**
164
+ * A job that waits (a listener's `delay`, `ctx.schedule`) needs an adapter that holds it: run early it'd be wrong,
165
+ * kept in memory it'd be lost on restart. Laravel's sync queue drops the delay; we refuse instead.
166
+ */
167
+ function checkHold(what, seconds) {
168
+ const { holds } = jobsAdapter;
169
+ if (!holds)
170
+ throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but ${yours} can't hold jobs. Use one that holds them (${ADAPTERS}).`);
171
+ if (holds !== true && seconds > holds.max)
172
+ throw new Error(`[logic-sdk] ${what} waits ${seconds}s; ${yours} holds jobs for at most ${holds.max}s. Use one that holds them longer, or a jobs table in front of it (${ADAPTERS}).`);
173
+ }
174
+ /** `attempts` above 1 need an adapter that runs a job again: ignored, a failure would just be lost. Rails' inline adapter refuses too. */
175
+ function checkRetries(what, attempts) {
176
+ if (attempts > 1 && !jobsAdapter.retries)
177
+ throw new Error(`[logic-sdk] ${what} has attempts: ${attempts}, but ${yours} runs each job once. Use one that retries (${ADAPTERS}), or attempts: 1.`);
178
+ }
179
+ for (const l of listeners)
180
+ if (l.listener.delay)
181
+ checkHold(l.id, l.listener.delay);
182
+ for (const l of listeners)
183
+ checkRetries(l.id, l.listener.attempts ?? 1);
184
+ for (const c of crons)
185
+ checkRetries(c.id, c.cron.attempts ?? 1);
186
+ for (const l of listeners) {
187
+ if (l.listener.key && !jobsAdapter.orders)
188
+ throw new Error(`[logic-sdk] ${l.id} has a key, but ${yours} can't run jobs one at a time by key. Use one that can (see Jobs, "key" in the docs).`);
189
+ // nothing waits on an adapter that runs jobs at once, so there's nothing to drop
190
+ if (l.listener.unique && jobsAdapter.holds && !jobsAdapter.replaces)
191
+ throw new Error(`[logic-sdk] ${l.id} is unique, but ${yours} can't drop a job it already has. Use one that can (see Jobs, "unique" in the docs).`);
192
+ }
193
+ /**
194
+ * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
195
+ * scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
196
+ * delay) are dropped, reported once.
197
+ */
198
+ function toJobs(envelopes, calls, parsed) {
199
+ /** Its `when`, if any. A throw is a bug in the app: it fails the mutation, naming the listener. */
200
+ const wants = (l, e, payload) => {
201
+ try {
202
+ return !l.listener.when || l.listener.when(payload);
203
+ }
204
+ catch (error) {
205
+ throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
206
+ }
207
+ };
208
+ /** Its `key` or `unique`, as `<listener id>@<value>`. A throw or an empty value is a bug in the app: it fails the mutation. */
209
+ const valueOf = (l, option, e, payload) => {
210
+ const of = l.listener[option];
211
+ if (!of)
212
+ return undefined;
213
+ let value;
214
+ try {
215
+ value = of(payload);
216
+ }
217
+ catch (error) {
218
+ throw new Error(`[logic-sdk] ${l.id}'s ${option} threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
219
+ }
220
+ if (typeof value !== "string" || !value)
221
+ throw new Error(`[logic-sdk] ${l.id}'s ${option} must return a non-empty string (got ${JSON.stringify(value)}) on ${e.name}.`);
222
+ return `${l.id}@${value}`;
223
+ };
224
+ const fits = (job) => job.depth <= maxEventDepth;
225
+ const deepEvent = envelopes.find((e) => !fits(e));
226
+ const deepCall = calls.find((c) => !fits(c));
227
+ const loop = (what) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
228
+ if (deepEvent)
229
+ report(loop(deepEvent.name), { source: deepEvent.name });
230
+ else if (deepCall)
231
+ report(loop(deepCall.fn), infoOf(deepCall));
232
+ const unique = new Set();
233
+ const deliveries = envelopes.filter(fits).flatMap((e) => (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).flatMap((l) => {
234
+ const job = deliveryOf(l, e);
235
+ const delay = l.listener.delay;
236
+ if (delay)
237
+ job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
238
+ const key = valueOf(l, "key", e, parsed.get(e));
239
+ if (key)
240
+ job.key = key;
241
+ if (l.listener.queue)
242
+ job.queue = l.listener.queue;
243
+ job.unique = valueOf(l, "unique", e, parsed.get(e));
244
+ if (!job.unique)
245
+ return [job];
246
+ if (unique.has(job.unique))
247
+ return []; // the same commit's first one waits; adapters drop later commits' ones
248
+ unique.add(job.unique);
249
+ return [job];
250
+ }));
251
+ return [...deliveries, ...calls.filter(fits)];
252
+ }
253
+ /** An adapter that couldn't take a commit's jobs: each one may be lost, so each is reported. */
254
+ const reportEach = (error, jobs) => {
255
+ for (const job of jobs)
256
+ report(error, { source: "(jobs adapter)", job });
257
+ };
258
+ /** What `onError` hears about a job. */
259
+ const infoOf = (job, attempt) => job.kind === "delivery"
260
+ ? { source: job.listener, job, attempt }
261
+ : { source: job.kind === "cron" ? job.cron : job.fn, job, attempt };
262
+ /** Who a stored job runs as: `jobs.scope.load` rebuilds it; null means discard it (reported). */
263
+ async function scopeOf(job, stored, attempt) {
264
+ if (!jobScope?.load)
265
+ return stored;
266
+ const loaded = await jobScope.load(stored);
267
+ if (loaded === undefined)
268
+ throw new Error(`[logic-sdk] jobs.scope.load returned undefined for ${job.id}. Return the scope, or null to discard the job.`);
269
+ if (loaded === null)
270
+ report(new Error(`[logic-sdk] jobs.scope.load returned null for ${job.id}, so it was discarded.`), { ...infoOf(job, attempt), outcome: "discarded" });
271
+ return loaded;
272
+ }
273
+ /**
274
+ * 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
275
+ * help and there are tries left. `fail` keeps a job that failed for good. The jobs it queues land in `queued`, for
276
+ * `deliver` to run once this one is settled; without it (`registry.jobs.run`, in a consumer) they're delivered at once.
277
+ */
278
+ async function runJob(job, { attempt = 1, fail } = {}, queued) {
279
+ const info = infoOf(job, attempt);
280
+ // read before narrowing: a job queued by another version can have a kind this one doesn't know
281
+ const { id, kind } = job;
282
+ /** Its definition's `failed`, once its last try failed: after it's kept, at most once. A throw is reported. */
283
+ let afterFailed;
284
+ const failed = async (error) => {
285
+ report(error, { ...info, outcome: "failed" });
286
+ await fail?.(error);
287
+ if (afterFailed)
288
+ await afterFailed(error).catch((e) => report(e, { source: `${info.source} (failed)`, job, attempt }));
289
+ return "failed";
290
+ };
291
+ /** One try of the job's `attempts`. */
292
+ const attemptOnce = async (work) => {
293
+ const { attempts } = job;
294
+ // its last try was claimed but never finished: a crash, or slower than the lease (Laravel checks this too)
295
+ if (attempt > attempts)
296
+ return failed(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.`));
297
+ try {
298
+ return await work();
299
+ }
300
+ catch (error) {
301
+ // a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
302
+ const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
303
+ const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
304
+ if (!retrying)
305
+ return failed(error);
306
+ report(error, { ...info, outcome: "retry" });
307
+ throw error;
308
+ }
309
+ };
310
+ // code this process doesn't have (renamed, removed, or not deployed here yet) is a try like any other, as Laravel
311
+ // treats a missing class: in a rolling deploy the new code gets a later one.
312
+ const cantRun = (why) => attemptOnce(async () => {
313
+ throw new Error(`[logic-sdk] ${why}`);
314
+ });
315
+ const missing = (what, id) => cantRun(`${id} isn't a registered ${what} (renamed, removed or not deployed here yet?), so job ${job.id} can't run.`);
316
+ if (job.kind === "cron") {
317
+ const c = cronById.get(job.cron);
318
+ if (!c)
319
+ return missing("cron", job.cron);
320
+ const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
321
+ const hook = c.cron.failed;
322
+ if (hook)
323
+ afterFailed = (error) => hook({ ...handlerCtx(c.cron.scope, 0, c.id, queued), cron: run }, error); // SAFETY: as below
324
+ return attemptOnce(async () => {
325
+ // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
326
+ const { scope, meta, handler } = c.cron;
327
+ await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () => handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run }));
328
+ return "done";
329
+ });
330
+ }
331
+ if (job.kind === "call") {
332
+ const f = fnById.get(job.fn);
333
+ if (!f)
334
+ return missing("function", job.fn);
335
+ return attemptOnce(async () => {
336
+ const scope = await scopeOf(job, job.scope, attempt);
337
+ if (!scope)
338
+ return "discarded";
339
+ await runAs(f.fn, job.input, scope, job.depth, queued, { id: job.id, attempt });
340
+ return "done";
341
+ });
342
+ }
343
+ if (job.kind !== "delivery")
344
+ return cantRun(`job ${id} has kind ${JSON.stringify(kind)}, which this version can't run.`);
345
+ const l = listenerById.get(job.listener);
346
+ if (!l)
347
+ return missing("listener", job.listener);
348
+ const { envelope } = job;
349
+ const { timeout } = l.listener;
350
+ const stop = timeout ? new AbortController() : undefined;
351
+ const hook = l.listener.failed;
352
+ // with today's scope and the parsed payload, as its handler would get them; a stale job or a scope that's gone has neither
353
+ if (hook)
354
+ afterFailed = async (error) => {
355
+ if (error instanceof StalePayload)
356
+ return;
357
+ const scope = jobScope?.load ? await jobScope.load(envelope.scope) : envelope.scope;
358
+ const r = await l.event.payload["~standard"].validate(envelope.payload);
359
+ if (!scope || r.issues || idOf(l.event) !== envelope.name)
360
+ return;
361
+ const ctxEvent = { id: envelope.id, name: envelope.name, payload: r.value, occurredAt: envelope.occurredAt, attempt };
362
+ return hook({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, r.value, error); // SAFETY: as the handler's
363
+ };
364
+ return attemptOnce(async () => {
365
+ const scope = await scopeOf(job, envelope.scope, attempt);
366
+ if (!scope)
367
+ return "discarded";
368
+ const handled = wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
369
+ // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
370
+ if (idOf(l.event) !== envelope.name)
371
+ throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
372
+ const r = await l.event.payload["~standard"].validate(envelope.payload);
373
+ if (r.issues)
374
+ throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
375
+ const payload = r.value;
376
+ const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
377
+ return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued, stop?.signal), event: ctxEvent }, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
378
+ });
379
+ await (timeout && stop ? stopAfter(handled, timeout, stop, `${l.id} ran past its timeout of ${timeout}s, so this try was stopped.`) : handled);
380
+ return "done";
381
+ });
382
+ }
383
+ /** A runner whose jobs' own jobs are collected in `queued`. */
384
+ const runnerInto = (queued) => ({
385
+ // a job the adapter runs here and doesn't record itself (inProcess) is kept by the store, if there's one
386
+ run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (failedStore && ((error) => failedStore.fail(job, error))) }, queued),
387
+ report: (e, job, attempt) => report(e, infoOf(job, attempt)),
388
+ });
389
+ /**
390
+ * Deliver jobs, then the jobs those queued, and so on. A job is settled before what it queued starts, as a Laravel
391
+ * worker deletes a job before it pops the ones it pushed: a crash in a follow-up can't run the job again.
392
+ */
393
+ async function deliver(jobs) {
394
+ while (jobs.length) {
395
+ const batch = jobs;
396
+ jobs = [];
397
+ await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
398
+ }
399
+ }
400
+ /**
401
+ * 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.
402
+ * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
403
+ */
404
+ function due(at, only) {
405
+ const { minute, stamp } = minuteOf(at, "tick");
406
+ return scheduled
407
+ .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
408
+ .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1, ...(c.cron.queue ? { queue: c.cron.queue } : {}) }));
409
+ }
410
+ const jobs = {
411
+ async run(job, options) {
412
+ // a signal: the adapter's row says what runs, and records how it went
413
+ if (jobsAdapter.consume) {
414
+ const queued = [];
415
+ await jobsAdapter.consume(job, runnerInto(queued)).catch((error) => {
416
+ report(error, { source: "(jobs adapter)", job }); // the consumer retries the message: nothing else hears of it
417
+ throw error;
418
+ });
419
+ await deliver(queued);
420
+ return "done";
421
+ }
422
+ return runJob(job, { attempt: options?.attempt, fail: failedStore && ((error) => failedStore.fail(job, error)) });
423
+ },
424
+ async tick(at = now()) {
425
+ const jobs = due(at);
426
+ if (!jobs.length)
427
+ return [];
428
+ await enqueueAlone(jobs);
429
+ await deliver(jobs);
430
+ return jobs.map((job) => job.cron);
431
+ },
432
+ async sweep(options) {
433
+ for (const q of options?.queues ?? [])
434
+ checkQueue("jobs.sweep({ queues })", q);
435
+ const queued = [];
436
+ const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
437
+ await deliver(queued);
438
+ return result;
439
+ },
440
+ attach(worker) {
441
+ for (const q of worker.queues ?? [])
442
+ checkQueue("A worker", q);
443
+ const set = workerSet(jobsAdapter);
444
+ set.add(worker);
445
+ return () => void set.delete(worker);
446
+ },
447
+ async retry(id) {
448
+ if (jobsAdapter.retry)
449
+ return jobsAdapter.retry(id);
450
+ if (!failedStore)
451
+ throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to retry (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
452
+ // out of the store, back to the queue with a fresh set of tries; a hand-off that fails puts it back and throws
453
+ const job = await failedStore.take(id);
454
+ if (!job)
455
+ return false;
456
+ const queued = [];
457
+ try {
458
+ await jobsAdapter.deliver([job], runnerInto(queued));
459
+ }
460
+ catch (error) {
461
+ await failedStore.fail(job, error);
462
+ throw error;
463
+ }
464
+ await deliver(queued);
465
+ return true;
466
+ },
467
+ async failed(options = {}) {
468
+ const store = jobsAdapter.failed ? jobsAdapter : failedStore;
469
+ if (!store?.failed)
470
+ throw new Error(`[logic-sdk] ${yours} can't list failed jobs. Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
471
+ const { source, scope, limit = 100, cursor } = options;
472
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
473
+ throw new Error(`[logic-sdk] jobs.failed({ limit }) takes 1 to 1000 (got ${String(limit)}).`);
474
+ const page = await store.failed({ source, scope: scope === undefined ? undefined : scopeMatches(scope), limit, cursor });
475
+ return {
476
+ jobs: page.rows.map(({ id, job, error, failedAt }) => ({
477
+ id,
478
+ kind: job.kind,
479
+ source: infoOf(job).source,
480
+ scope: (job.kind === "call" ? job.scope : job.kind === "delivery" ? job.envelope.scope : undefined), // what `store` saved, typed by the caller
481
+ error,
482
+ failedAt,
483
+ job,
484
+ })),
485
+ cursor: page.cursor,
486
+ };
487
+ },
488
+ async forget(id) {
489
+ const store = jobsAdapter.forget ? jobsAdapter : failedStore;
490
+ if (!store?.forget)
491
+ throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to forget (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
492
+ return store.forget(id);
493
+ },
494
+ /**
495
+ * One run of a cron, due or not, through the adapter as a tick's would go. Its id is the minute's plus a uuid, so a
496
+ * tick for that minute still runs (stored adapters run each id once), and so does a second invoke.
497
+ */
498
+ async invoke(target, options = {}) {
499
+ const c = typeof target === "string" ? cronById.get(target) : crons.find((r) => r.cron === target);
500
+ if (!c)
501
+ throw new Error(typeof target === "string"
502
+ ? `[logic-sdk] jobs.invoke(${JSON.stringify(target)}): no cron has that id (${[...cronById.keys()].join(", ") || "none registered"}).`
503
+ : "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.");
504
+ const { minute, stamp } = minuteOf(options.at ?? now(), "jobs.invoke({ at })");
505
+ const job = { kind: "cron", id: `${c.id}@${stamp}-${crypto.randomUUID()}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1, ...(c.cron.queue ? { queue: c.cron.queue } : {}) };
506
+ await enqueueAlone([job]);
507
+ const queued = [];
508
+ await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
509
+ await deliver(queued);
510
+ return job.id;
511
+ },
512
+ };
513
+ return { toJobs, deliver, jobs, due, checkHold, checkRetries, checkQueue, yours };
514
+ }