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
@@ -1,260 +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, type Job, type JobOutcome, type JobsAdapter, type Runner, type SqlDatabase, type SweepResult } from "./index.ts";
5
-
6
- /**
7
- * The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
8
- * lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
9
- * the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
10
- */
11
- export interface JobsSql {
12
- /** `(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. */
13
- insert: string;
14
- /** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
15
- recordTicks: string;
16
- /** `()`: forgets ticks older than a day. */
17
- pruneTicks: string;
18
- /** `(receipt, lease, ids)`: the first claim, of rows nobody claimed. Returns `id`. */
19
- claimNew: string;
20
- /** `(receipt, lease)`: claims the one row due first. Returns `job` (JSON text) and `attempts`. */
21
- claimDue: string;
22
- /** `(lease, ids, receipt)`, on rows this receipt still owns, like the three below. */
23
- extend: string;
24
- /** `(seconds, error, ids, receipt)` */
25
- backOff: string;
26
- /** `(error, ids, receipt)` */
27
- markFailed: string;
28
- /** `(ids, receipt)` */
29
- remove: string;
30
- /** `(id)`: a failed row back in line. Returns `id`. */
31
- retry: string;
32
- /** `(id, job, error)`: a failed row, new or over the one there. */
33
- fail: string;
34
- }
35
-
36
- /** 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. */
37
- const PICKUP = 30;
38
-
39
- /**
40
- * Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer, and pg-boss's default
41
- * expiry. Past it, a job that hangs is taken over like a crashed one. A longer job needs a `lease` that long.
42
- */
43
- const MAX_EXTEND = 15 * 60;
44
-
45
- /** Who owns a job while it runs. */
46
- interface Claim {
47
- receipt: string;
48
- attempt: number;
49
- }
50
-
51
- export interface DatabaseQueueOptions {
52
- /**
53
- * Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
54
- * job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
55
- * longer than that.
56
- */
57
- lease?: number;
58
- /** Seconds to wait after a failed try. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
59
- backoff?: (attempt: number) => number;
60
- }
61
-
62
- export interface OutboxOptions {
63
- /** Seconds a send owns its jobs: how soon one that crashed is sent again. Default 300. */
64
- lease?: number;
65
- /** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
66
- backoff?: (attempt: number) => number;
67
- /**
68
- * Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
69
- * are its `attempts`.
70
- */
71
- maxAttempts?: number;
72
- }
73
-
74
- /** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
75
- export interface StoredJobs extends JobsAdapter {
76
- /** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
77
- sweep(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
78
- /** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
79
- retry(id: string): Promise<boolean>;
80
- }
81
-
82
- /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
83
- /** Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. */
84
- export const defaultBackoff = (attempt: number) => Math.exp(Math.min(attempt, 10));
85
-
86
- export function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxOptions, via?: JobsAdapter): StoredJobs {
87
- const lease = options.lease ?? 300;
88
- const maxAttempts = options.maxAttempts ?? 10;
89
- const backoff = options.backoff ?? defaultBackoff;
90
- /** Outside a mutation: on the database itself. */
91
- const query = (text: string, params: unknown[]) => database.query(database.db, text, params);
92
- const list = (ids: string[]) => JSON.stringify(ids);
93
-
94
- // These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
95
- // newer runner's work, and a handoff that finishes late can't delete the failure a consumer already recorded. By
96
- // receipt, not attempt number: `retry(id)` starts those again at 1.
97
- const markFailed = (ids: string[], claim: Claim, error: unknown) => query(sql.markFailed, [describe(error), list(ids), claim.receipt]);
98
- const backOff = (ids: string[], claim: Claim, error: unknown) => query(sql.backOff, [backoff(claim.attempt), describe(error), list(ids), claim.receipt]);
99
- const remove = (ids: string[], claim: Claim) => query(sql.remove, [list(ids), claim.receipt]);
100
-
101
- /**
102
- * While a job runs, its lease is extended, as Laravel Cloud does on SQS: a slow job stays its runner's, and a dead
103
- * runner's job is free a lease later. Returns the stop, which waits for the extension on its way: landing after a
104
- * backoff, it would replace the backoff.
105
- */
106
- function keepExtending(job: Job, claim: Claim, runner: Runner): () => Promise<unknown> {
107
- const until = Date.now() + MAX_EXTEND * 1000;
108
- let extending: Promise<unknown> = Promise.resolve();
109
- const timer = setInterval(
110
- () => {
111
- if (Date.now() >= until) return clearInterval(timer);
112
- extending = extending
113
- .then(() => query(sql.extend, [lease, list([job.id]), claim.receipt]))
114
- .catch((e) => runner.report(e, job, claim.attempt));
115
- },
116
- (lease * 1000) / 3,
117
- );
118
- return () => {
119
- clearInterval(timer);
120
- return extending;
121
- };
122
- }
123
-
124
- /**
125
- * Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
126
- * (tries left: back off), or done and discarded (delete the row).
127
- */
128
- async function run(job: Job, claim: Claim, runner: Runner): Promise<keyof SweepResult> {
129
- const stopExtending = keepExtending(job, claim, runner);
130
- let outcome: JobOutcome;
131
- try {
132
- outcome = await runner
133
- .run(job, {
134
- attempt: claim.attempt,
135
- fail: async (error) => {
136
- await markFailed([job.id], claim, error);
137
- },
138
- })
139
- .finally(stopExtending);
140
- } catch (e) {
141
- await backOff([job.id], claim, e);
142
- return "retrying";
143
- }
144
- if (outcome !== "failed") await remove([job.id], claim);
145
- return outcome;
146
- }
147
-
148
- /** Hand claimed jobs to `via` in one send. Done once the queue has them; a failed send keeps them all for a retry. */
149
- async function handOff(queue: JobsAdapter, jobs: Job[], claim: Claim, runner: Runner): Promise<keyof SweepResult> {
150
- const ids = jobs.map((j) => j.id);
151
- try {
152
- await queue.deliver(jobs, runner);
153
- } catch (e) {
154
- for (const job of jobs) runner.report(e, job, claim.attempt); // the queue's failure, not the listener's: run never saw it
155
- if (claim.attempt >= maxAttempts) {
156
- await markFailed(ids, claim, e);
157
- return "failed";
158
- }
159
- await backOff(ids, claim, e);
160
- return "retrying";
161
- }
162
- await remove(ids, claim);
163
- return "done";
164
- }
165
-
166
- /** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
167
- async function recordTicks(tx: unknown, ticks: Job[]): Promise<Set<unknown>> {
168
- if (!ticks.length) return new Set();
169
- const first = await database.query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
170
- await database.query(tx, sql.pruneTicks, []);
171
- return new Set(first.map((row) => row.id));
172
- }
173
-
174
- const settle = (job: Job, claim: Claim, runner: Runner) => (via ? handOff(via, [job], claim, runner) : run(job, claim, runner));
175
-
176
- /** The first claim of jobs just committed, by the request that queued them: the ones no sweep took meanwhile. */
177
- async function claimNew(jobs: Job[]): Promise<{ claim: Claim; won: Job[] }> {
178
- const claim = { receipt: crypto.randomUUID(), attempt: 1 };
179
- const rows = await query(sql.claimNew, [claim.receipt, lease, list(jobs.map((j) => j.id))]);
180
- const ids = new Set(rows.map((row) => row.id));
181
- return { claim, won: jobs.filter((j) => ids.has(j.id)) }; // in emit order: RETURNING has none
182
- }
183
-
184
- return {
185
- holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
186
- replaces: true, // a waiting row is replaced in place; under `via` too, since rows wait here until they're due
187
- /** Must share the transaction it writes in. */
188
- check({ database: given }) {
189
- if (given && given.db !== database.db)
190
- throw new Error(
191
- `[logic-sdk] ${via ? "outbox(database, queue)" : "databaseQueue(database)"} must use the same database as \`database\`: jobs are written in your mutation's transaction. ` +
192
- "A queue in another database goes behind an outbox: outbox(database, queue).",
193
- );
194
- },
195
- /**
196
- * Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
197
- * request. Delayed: available from `runAt`, for a sweep. A cron's minute runs once: only ticks nobody recorded yet.
198
- */
199
- async enqueue(tx, jobs) {
200
- const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
201
- const rows = jobs
202
- .filter((j) => j.kind !== "cron" || firstTicks.has(j.id))
203
- .map((j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: replaceKeyOf(j) ?? null }))
204
- // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
205
- .sort((a, b) => byText(a.key ?? "", b.key ?? ""));
206
- if (rows.length) await database.query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
207
- },
208
- /**
209
- * After commit, in this request: each job is claimed just before it runs, so a slow or dead one doesn't spend the
210
- * others' attempt. Under `via` they're claimed together, for one send. What isn't claimed yet when the process dies
211
- * is a sweep's, as a first try.
212
- */
213
- async deliver(jobs, runner) {
214
- const due = jobs.filter((j) => !j.runAt);
215
- if (!due.length) return;
216
- if (via) {
217
- const { claim, won } = await claimNew(due);
218
- if (won.length) await handOff(via, won, claim, runner);
219
- return;
220
- }
221
- for (const job of due) {
222
- try {
223
- const { claim, won } = await claimNew([job]);
224
- if (won.length) await run(job, claim, runner);
225
- } catch (e) {
226
- runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
227
- }
228
- }
229
- },
230
- /** 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. */
231
- async sweep(runner, { limit = 100 } = {}) {
232
- const result: SweepResult = { done: 0, failed: 0, discarded: 0, retrying: 0 };
233
- for (let i = 0; i < limit; i++) {
234
- const receipt = crypto.randomUUID();
235
- const [row] = await query(sql.claimDue, [receipt, lease]);
236
- if (!row) break;
237
- const job: Job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
238
- const attempt = Number(row.attempts);
239
- try {
240
- result[await settle(job, { receipt, attempt }, runner)]++;
241
- } catch (e) {
242
- runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
243
- }
244
- }
245
- return result;
246
- },
247
- /** Failed rows only: a pending one belongs to its runner or a sweep, and resetting it could run it twice at once. */
248
- async retry(id) {
249
- return (await query(sql.retry, [id])).length > 0;
250
- },
251
- /** A job that failed for good in a queue consumer: keep it as a failed row, so you can query it and `retry` it. */
252
- async fail(job, error) {
253
- await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
254
- },
255
- };
256
- }
257
-
258
- /** Not `localeCompare`: processes with another locale would lock in another order. */
259
- const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
260
- const describe = (e: unknown) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes