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.
- package/README.md +9 -10
- package/dist/adapters/cloudflare-queue.d.ts +15 -0
- package/dist/adapters/cloudflare-queue.js +58 -0
- package/dist/adapters/drizzle-pg.d.ts +280 -0
- package/dist/adapters/drizzle-pg.js +78 -0
- package/dist/adapters/drizzle-sqlite.d.ts +273 -0
- package/dist/adapters/drizzle-sqlite.js +203 -0
- package/dist/adapters/postgres.d.ts +33 -0
- package/dist/adapters/postgres.js +129 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +108 -0
- package/dist/adapters/stored-jobs.d.ts +89 -0
- package/dist/adapters/stored-jobs.js +370 -0
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +37 -0
- package/dist/core/jobs.d.ts +63 -0
- package/dist/core/jobs.js +514 -0
- package/dist/core/registry.d.ts +156 -0
- package/dist/core/registry.js +515 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +232 -0
- package/dist/{types.d.ts → core/types.d.ts} +289 -64
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +43 -0
- package/dist/hosts/cloudflare.js +40 -0
- package/dist/hosts/node.d.ts +36 -0
- package/dist/hosts/node.js +103 -0
- package/dist/index.d.ts +5 -122
- package/dist/index.js +4 -492
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -75
- package/dist/testing.js +1 -227
- package/package.json +2 -12
- package/skills/logic-sdk/SKILL.md +6 -5
- package/src/adapters/cloudflare-queue.ts +65 -0
- package/src/adapters/drizzle-pg.ts +117 -0
- package/src/adapters/drizzle-sqlite.ts +241 -0
- package/src/adapters/postgres.ts +136 -0
- package/src/adapters/sqlite.ts +116 -0
- package/src/adapters/stored-jobs.ts +463 -0
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +38 -0
- package/src/core/jobs.ts +548 -0
- package/src/core/registry.ts +719 -0
- package/src/core/testing.ts +309 -0
- package/src/{types.ts → core/types.ts} +280 -60
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +55 -0
- package/src/hosts/node.ts +126 -0
- package/src/index.ts +17 -652
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- package/dist/jobs.d.ts +0 -44
- package/dist/jobs.js +0 -260
- package/dist/pg-boss.d.ts +0 -53
- package/dist/pg-boss.js +0 -213
- package/dist/stored-jobs.d.ts +0 -64
- package/dist/stored-jobs.js +0 -188
- package/src/jobs.ts +0 -307
- package/src/pg-boss.ts +0 -241
- package/src/stored-jobs.ts +0 -260
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /package/src/{schedule.ts → core/schedule.ts} +0 -0
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
// Jobs in the registry's database, written in the mutation's transaction: run from there (databaseQueue), or kept
|
|
2
|
+
// until a queue 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 { defaultBackoff, storedUniqueKey } from "../core/jobs.ts";
|
|
5
|
+
import type { AdapterSetup, FailedJobs, FailedQuery, FailedRow, Job, JobOutcome, JobsAdapter, Runner, SqlDatabase, SweepOptions, SweepResult } from "../core/types.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
|
|
9
|
+
* lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
|
|
10
|
+
* the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
|
|
11
|
+
*/
|
|
12
|
+
export interface JobsSql {
|
|
13
|
+
/**
|
|
14
|
+
* `(pickup, rows)`: rows is JSON `[{ id, job, at, unique, order }]`, `at` in epoch ms or null (due now, a sweep's
|
|
15
|
+
* after `pickup` seconds). A waiting row with the same `unique` is replaced by a call, and kept over a delivery.
|
|
16
|
+
*/
|
|
17
|
+
insert: string;
|
|
18
|
+
/** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
|
|
19
|
+
recordTicks: string;
|
|
20
|
+
/** `()`: forgets ticks older than a day. */
|
|
21
|
+
pruneTicks: string;
|
|
22
|
+
/** `(receipt, lease, id)`: the first claim, of a row nobody claimed. Returns `id`. */
|
|
23
|
+
claimNew: string;
|
|
24
|
+
/**
|
|
25
|
+
* `(receipt, lease, grace, queue)`: claims the one row due first (`grace` seconds ago) in `queue` (`''`: any; a job
|
|
26
|
+
* without one is in `"default"`), the first open one of its key. Returns `job` (JSON text) and `attempts`.
|
|
27
|
+
*/
|
|
28
|
+
claimDue: string;
|
|
29
|
+
/** `(receipt, lease, id)`: claims the row a signal names, if it's due. Returns `job` and `attempts`. */
|
|
30
|
+
claimOne: string;
|
|
31
|
+
/** `(receipt, lease, order)`: claims the next row of a key, due or waiting only for its turn. Returns `job` and `attempts`. */
|
|
32
|
+
claimNext: string;
|
|
33
|
+
/** `(lease, id, receipt)`, on a row this receipt still owns, like the three below. */
|
|
34
|
+
extend: string;
|
|
35
|
+
/** `(seconds, error, id, receipt)` */
|
|
36
|
+
backOff: string;
|
|
37
|
+
/** `(error, id, receipt)` */
|
|
38
|
+
markFailed: string;
|
|
39
|
+
/** `(id, receipt)` */
|
|
40
|
+
remove: string;
|
|
41
|
+
/** `(id)`: a failed row back in line. Returns `id`. */
|
|
42
|
+
retry: string;
|
|
43
|
+
/** `(id, job, error)`: a failed row, new or over the one there. */
|
|
44
|
+
fail: string;
|
|
45
|
+
/**
|
|
46
|
+
* `(source, matches, at, id, limit)`, `''` for "any": failed rows newest first, after the cursor row (`at`, `id`), each
|
|
47
|
+
* matching the source and every field in `matches` (JSON `[{ path, jsonPath, value }]`). Returns `id`, `job` (JSON
|
|
48
|
+
* text), `last_error` and `failed_at` (as `at` takes it back).
|
|
49
|
+
*/
|
|
50
|
+
failed: string;
|
|
51
|
+
/** `(id)`: deletes a failed row. Returns `id`. */
|
|
52
|
+
forget: string;
|
|
53
|
+
/** `(id)`: deletes a failed row. Returns `job` (JSON text). */
|
|
54
|
+
take: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Seconds a job due now waits for the request that queued it before a sweep may take it (how soon a crash after
|
|
59
|
+
* commit is noticed). Behind an outbox, also how long past due a sweep leaves a row to its signal.
|
|
60
|
+
*/
|
|
61
|
+
const PICKUP = 30;
|
|
62
|
+
|
|
63
|
+
/** A signal for a later time goes out this much later, so a clock ahead of the database's doesn't land it early. */
|
|
64
|
+
const SLACK = 1000;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer. Past it, a job that
|
|
68
|
+
* hangs is taken over like a crashed one. A longer job needs a `lease` that long.
|
|
69
|
+
*/
|
|
70
|
+
const MAX_EXTEND = 15 * 60;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Seconds a queue consumer keeps running one key's jobs before it hands the rest to the next message: one busy key
|
|
74
|
+
* can't hold a consumer, and the messages behind it, until the platform stops it.
|
|
75
|
+
*/
|
|
76
|
+
const DRAIN = 60;
|
|
77
|
+
|
|
78
|
+
/** A delivery's `key`: its jobs run one at a time, in insert order. */
|
|
79
|
+
const keyOf = (job: Job) => (job.kind === "delivery" ? job.key : undefined);
|
|
80
|
+
|
|
81
|
+
/** Who owns a job while it runs. */
|
|
82
|
+
interface Claim {
|
|
83
|
+
receipt: string;
|
|
84
|
+
attempt: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface OutboxOptions {
|
|
88
|
+
/**
|
|
89
|
+
* Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
|
|
90
|
+
* job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
|
|
91
|
+
* longer than that.
|
|
92
|
+
*/
|
|
93
|
+
lease?: number;
|
|
94
|
+
/** Seconds to wait after a failed try. Default `defaultBackoff`, the curve Graphile Worker uses. */
|
|
95
|
+
backoff?: (attempt: number) => number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface DatabaseQueueOptions extends OutboxOptions {
|
|
99
|
+
/**
|
|
100
|
+
* Who runs a job due now. `"request"` (default): the request that committed it, right after commit (after the
|
|
101
|
+
* response, with `waitUntil`), unless `work(registry)` runs in this process: then that loop takes it, and the request
|
|
102
|
+
* answers at once. `"worker"`: workers in other processes run every job, and requests only write rows.
|
|
103
|
+
*/
|
|
104
|
+
runIn?: "request" | "worker";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
|
|
108
|
+
export interface StoredJobs extends JobsAdapter {
|
|
109
|
+
/** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
|
|
110
|
+
sweep(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
|
|
111
|
+
/** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
|
|
112
|
+
retry(id: string): Promise<boolean>;
|
|
113
|
+
/** A page of failed rows, newest first. */
|
|
114
|
+
failed(query: FailedQuery): Promise<{ rows: FailedRow[]; cursor: string | null }>;
|
|
115
|
+
/** Delete a failed row. `false` when no failed row has that id. */
|
|
116
|
+
forget(id: string): Promise<boolean>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The registry's database, taken at `createRegistry` (`sql: true`, so the core refuses one that doesn't run SQL): jobs
|
|
121
|
+
* are rows written in the mutation's transaction, so there's no other database they could go to. Laravel's `database`
|
|
122
|
+
* driver uses the app's connection too.
|
|
123
|
+
*/
|
|
124
|
+
function registryDatabase(name: string) {
|
|
125
|
+
let database: SqlDatabase | undefined;
|
|
126
|
+
let workers: AdapterSetup["workers"] = { takes: () => false, wake: () => {} };
|
|
127
|
+
return {
|
|
128
|
+
connect(setup: AdapterSetup) {
|
|
129
|
+
const { sql } = setup;
|
|
130
|
+
if (database && sql && database.db !== sql.db)
|
|
131
|
+
throw new Error(`[logic-sdk] ${name} is already connected to another registry's database: call it once per registry.`);
|
|
132
|
+
database = sql;
|
|
133
|
+
workers = setup.workers;
|
|
134
|
+
},
|
|
135
|
+
/** The loops running jobs in this process (`work()`). */
|
|
136
|
+
workers: () => workers,
|
|
137
|
+
get(): SqlDatabase {
|
|
138
|
+
if (!database) throw new Error(`[logic-sdk] ${name} isn't connected: pass it to createRegistry.`);
|
|
139
|
+
return database;
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it, the queue carries signals. */
|
|
145
|
+
export function storedJobs(sql: JobsSql, options: DatabaseQueueOptions, via?: JobsAdapter): StoredJobs {
|
|
146
|
+
const name = via ? "outbox(queue)" : "databaseQueue()";
|
|
147
|
+
// its jobs would be signalled to a `deliver` that has nothing to do
|
|
148
|
+
if (via?.enqueue)
|
|
149
|
+
throw new Error(`[logic-sdk] outbox(queue) got a queue that writes its jobs in your transaction itself (it has \`enqueue\`): use it on its own, without an outbox.`);
|
|
150
|
+
const database = registryDatabase(name);
|
|
151
|
+
const lease = options.lease ?? 300;
|
|
152
|
+
const backoff = options.backoff ?? defaultBackoff;
|
|
153
|
+
const inWorker = options.runIn === "worker";
|
|
154
|
+
/**
|
|
155
|
+
* Whether this request leaves its jobs due now to workers: always with `runIn: "worker"`, and when a loop in this
|
|
156
|
+
* process takes every one of them. Asked the same way at insert and after commit, so the row is free for it at once.
|
|
157
|
+
*/
|
|
158
|
+
const leaves = (jobs: Job[]) => inWorker || jobs.filter((j) => !j.runAt).every((j) => database.workers().takes(j));
|
|
159
|
+
/** Outside a mutation: on the database itself. */
|
|
160
|
+
const query = (text: string, params: unknown[]) => database.get().query(database.get().db, text, params);
|
|
161
|
+
const list = (ids: string[]) => JSON.stringify(ids);
|
|
162
|
+
|
|
163
|
+
// These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
|
|
164
|
+
// newer runner's work. By receipt, not attempt number: `retry(id)` starts those again at 1.
|
|
165
|
+
const failedRows = rowsOfFailed(sql, query);
|
|
166
|
+
const markFailed = (job: Job, claim: Claim, error: unknown) => query(sql.markFailed, [describe(error), job.id, claim.receipt]);
|
|
167
|
+
const backOff = (job: Job, claim: Claim, seconds: number, error: unknown) => query(sql.backOff, [seconds, describe(error), job.id, claim.receipt]);
|
|
168
|
+
const remove = (job: Job, claim: Claim) => query(sql.remove, [job.id, claim.receipt]);
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* While a job runs, its lease is extended, as Laravel Cloud does on SQS: a slow job stays its runner's, and a dead
|
|
172
|
+
* runner's job is free a lease later. Returns the stop, which waits for the extension on its way: landing after a
|
|
173
|
+
* backoff, it would replace the backoff.
|
|
174
|
+
*/
|
|
175
|
+
function keepExtending(job: Job, claim: Claim, runner: Runner): () => Promise<unknown> {
|
|
176
|
+
const until = Date.now() + MAX_EXTEND * 1000;
|
|
177
|
+
let extending: Promise<unknown> = Promise.resolve();
|
|
178
|
+
const timer = setInterval(
|
|
179
|
+
() => {
|
|
180
|
+
if (Date.now() >= until) return clearInterval(timer);
|
|
181
|
+
extending = extending
|
|
182
|
+
.then(() => query(sql.extend, [lease, job.id, claim.receipt]))
|
|
183
|
+
.catch((e) => runner.report(e, job, claim.attempt));
|
|
184
|
+
},
|
|
185
|
+
(lease * 1000) / 3,
|
|
186
|
+
);
|
|
187
|
+
return () => {
|
|
188
|
+
clearInterval(timer);
|
|
189
|
+
return extending;
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
|
|
195
|
+
* (tries left: back off, and behind an outbox signal the retry), or done and discarded (delete the row).
|
|
196
|
+
*/
|
|
197
|
+
async function run(job: Job, claim: Claim, runner: Runner): Promise<keyof SweepResult> {
|
|
198
|
+
const stopExtending = keepExtending(job, claim, runner);
|
|
199
|
+
let outcome: JobOutcome;
|
|
200
|
+
try {
|
|
201
|
+
outcome = await runner
|
|
202
|
+
.run(job, {
|
|
203
|
+
attempt: claim.attempt,
|
|
204
|
+
fail: async (error) => {
|
|
205
|
+
await markFailed(job, claim, error);
|
|
206
|
+
},
|
|
207
|
+
})
|
|
208
|
+
.finally(stopExtending);
|
|
209
|
+
} catch (e) {
|
|
210
|
+
const seconds = backoff(claim.attempt);
|
|
211
|
+
await backOff(job, claim, seconds, e);
|
|
212
|
+
if (via) await signal([{ ...job, runAt: new Date(Date.now() + seconds * 1000).toISOString() }], runner);
|
|
213
|
+
return "retrying";
|
|
214
|
+
}
|
|
215
|
+
if (outcome !== "failed") await remove(job, claim);
|
|
216
|
+
return outcome;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Run a key's next jobs here, one by one, as they come free: after a job in the request, rather than leave them to a
|
|
221
|
+
* sweep (which runs them as they're due, one per claim), and for a consumer's signal behind an outbox. There, after
|
|
222
|
+
* `DRAIN` seconds the rest get one more signal.
|
|
223
|
+
*/
|
|
224
|
+
async function runKey(key: string, runner: Runner) {
|
|
225
|
+
const until = Date.now() + DRAIN * 1000;
|
|
226
|
+
for (;;) {
|
|
227
|
+
const receipt = crypto.randomUUID();
|
|
228
|
+
const [row] = await query(sql.claimNext, [receipt, lease, key]);
|
|
229
|
+
if (!row) return;
|
|
230
|
+
const job: Job = JSON.parse(String(row.job));
|
|
231
|
+
await run(job, { receipt, attempt: Number(row.attempts) }, runner);
|
|
232
|
+
if (via && Date.now() >= until) return signal([job], runner);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Behind an outbox, a consumer got a signal: run the row it names (with a `key`, the key's next jobs). The row is the
|
|
238
|
+
* truth, so a duplicate, a late one, or one whose row is gone or taken has nothing to do.
|
|
239
|
+
*/
|
|
240
|
+
async function consume(job: Job, runner: Runner) {
|
|
241
|
+
const key = keyOf(job);
|
|
242
|
+
if (key) return runKey(key, runner);
|
|
243
|
+
const receipt = crypto.randomUUID();
|
|
244
|
+
const [row] = await query(sql.claimOne, [receipt, lease, job.id]);
|
|
245
|
+
if (row) await run(JSON.parse(String(row.job)), { receipt, attempt: Number(row.attempts) }, runner);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Can `via` hold a signal until `at`? */
|
|
249
|
+
const canHold = (at: number) => via?.holds === true || (!!via?.holds && (at - Date.now()) / 1000 <= via.holds.max);
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Behind an outbox, every job stays a row and the queue gets a signal: whoever gets one runs the row from the table
|
|
253
|
+
* (`consume`). One for a later time goes out only if the queue can hold it; a sweep runs the rest. A signal that
|
|
254
|
+
* doesn't go out is reported and the rows wait for a sweep. The runner the queue gets runs signals too, for a queue
|
|
255
|
+
* that runs what it's sent itself.
|
|
256
|
+
*/
|
|
257
|
+
async function signal(jobs: Job[], runner: Runner) {
|
|
258
|
+
const signals: Job[] = [];
|
|
259
|
+
for (const job of jobs) {
|
|
260
|
+
if (!job.runAt) signals.push(job);
|
|
261
|
+
else if (canHold(Date.parse(job.runAt))) signals.push({ ...job, runAt: new Date(Date.parse(job.runAt) + SLACK).toISOString() });
|
|
262
|
+
}
|
|
263
|
+
if (!signals.length) return;
|
|
264
|
+
const consumer: Runner = {
|
|
265
|
+
...runner,
|
|
266
|
+
run: async (job) => {
|
|
267
|
+
await consume(job, runner);
|
|
268
|
+
return "done";
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
try {
|
|
272
|
+
await via!.deliver(signals, consumer);
|
|
273
|
+
} catch (e) {
|
|
274
|
+
for (const job of signals) runner.report(e, job);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
|
|
279
|
+
async function recordTicks(tx: unknown, ticks: Job[]): Promise<Set<unknown>> {
|
|
280
|
+
if (!ticks.length) return new Set();
|
|
281
|
+
const first = await database.get().query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
|
|
282
|
+
await database.get().query(tx, sql.pruneTicks, []);
|
|
283
|
+
return new Set(first.map((row) => row.id));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The first claim of a job just committed, by the request that queued it, unless a sweep took it meanwhile. */
|
|
287
|
+
async function claimNew(job: Job): Promise<Claim | undefined> {
|
|
288
|
+
const claim = { receipt: crypto.randomUUID(), attempt: 1 };
|
|
289
|
+
const rows = await query(sql.claimNew, [claim.receipt, lease, job.id]);
|
|
290
|
+
return rows.length ? claim : undefined;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
name,
|
|
295
|
+
retries: true, // a failed try backs off as a row
|
|
296
|
+
holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
|
|
297
|
+
replaces: true, // a waiting row is replaced in place; behind an outbox too, since every job stays a row
|
|
298
|
+
orders: true, // a key's jobs run from the table, in order; behind an outbox the queue only signals
|
|
299
|
+
queues: true, // a row's queue is in its job: a sweep takes the ones it's asked for, in that order
|
|
300
|
+
/** Takes the registry's database: it writes in the mutation's transaction. */
|
|
301
|
+
sql: true,
|
|
302
|
+
connect: (setup) => database.connect(setup),
|
|
303
|
+
/**
|
|
304
|
+
* Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
|
|
305
|
+
* request, or none when the request runs nothing (workers take it, or a signal, which the sweep's grace covers). Delayed:
|
|
306
|
+
* available from `runAt`. A cron's minute runs once: only ticks nobody recorded yet.
|
|
307
|
+
*/
|
|
308
|
+
async enqueue(tx, jobs) {
|
|
309
|
+
const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
|
|
310
|
+
const kept = jobs.filter((j) => j.kind !== "cron" || firstTicks.has(j.id));
|
|
311
|
+
const rows = (await Promise.all(kept.map(async (j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, unique: (await storedUniqueKey(j)) ?? null, order: (j.kind === "delivery" && j.key) || null }))))
|
|
312
|
+
// in key order, so two transactions with the same unique keys lock them in the same order and can't deadlock
|
|
313
|
+
.sort((a, b) => byText(a.unique ?? "", b.unique ?? ""));
|
|
314
|
+
if (rows.length) await database.get().query(tx, sql.insert, [via || leaves(kept) ? 0 : PICKUP, JSON.stringify(rows)]);
|
|
315
|
+
},
|
|
316
|
+
/**
|
|
317
|
+
* After commit, in this request. Behind an outbox: one signal per job, and one per key. Left to workers: wake this
|
|
318
|
+
* process's, if any (others poll). Otherwise each job due now is claimed just before it runs, so a slow or dead one
|
|
319
|
+
* doesn't spend the others' attempt; what isn't claimed yet when the process dies is a sweep's, as a first try.
|
|
320
|
+
*/
|
|
321
|
+
async deliver(jobs, runner) {
|
|
322
|
+
if (via) {
|
|
323
|
+
const keys = new Set<string>();
|
|
324
|
+
const firsts = jobs.filter((job) => {
|
|
325
|
+
const key = keyOf(job);
|
|
326
|
+
if (!key) return true;
|
|
327
|
+
if (keys.has(key)) return false;
|
|
328
|
+
keys.add(key);
|
|
329
|
+
return true;
|
|
330
|
+
});
|
|
331
|
+
return signal(firsts, runner);
|
|
332
|
+
}
|
|
333
|
+
const due = jobs.filter((j) => !j.runAt);
|
|
334
|
+
if (leaves(jobs)) {
|
|
335
|
+
if (due.length) database.workers().wake(due.length);
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
for (const job of due) {
|
|
339
|
+
try {
|
|
340
|
+
const claim = await claimNew(job);
|
|
341
|
+
if (!claim) continue;
|
|
342
|
+
await run(job, claim, runner);
|
|
343
|
+
const key = keyOf(job);
|
|
344
|
+
if (key) await runKey(key, runner); // its key's next ones, rather than leave them to a sweep
|
|
345
|
+
} catch (e) {
|
|
346
|
+
runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
/**
|
|
351
|
+
* What's due (retries, delayed jobs, what a crash left behind), claimed one at a time, so every claim gets a full
|
|
352
|
+
* lease. Behind an outbox, only rows `PICKUP` seconds past due: until then they're their signal's.
|
|
353
|
+
*/
|
|
354
|
+
async sweep(runner, { limit = 100, queues } = {}) {
|
|
355
|
+
const result: SweepResult = { done: 0, failed: 0, discarded: 0, retrying: 0 };
|
|
356
|
+
// in the order given: each claim takes the first queue with a job due, as a worker listing queues does
|
|
357
|
+
const order = queues?.length ? queues : [""];
|
|
358
|
+
for (let i = 0; i < limit; i++) {
|
|
359
|
+
const receipt = crypto.randomUUID();
|
|
360
|
+
let row: Record<string, unknown> | undefined;
|
|
361
|
+
for (const queue of order) {
|
|
362
|
+
[row] = await query(sql.claimDue, [receipt, lease, via ? PICKUP : 0, queue]);
|
|
363
|
+
if (row) break;
|
|
364
|
+
}
|
|
365
|
+
if (!row) break;
|
|
366
|
+
const job: Job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
|
|
367
|
+
const attempt = Number(row.attempts);
|
|
368
|
+
try {
|
|
369
|
+
result[await run(job, { receipt, attempt }, runner)]++;
|
|
370
|
+
} catch (e) {
|
|
371
|
+
runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return result;
|
|
375
|
+
},
|
|
376
|
+
/** Failed rows only: a pending one belongs to its runner or a sweep, and resetting it could run it twice at once. */
|
|
377
|
+
async retry(id) {
|
|
378
|
+
return (await query(sql.retry, [id])).length > 0;
|
|
379
|
+
},
|
|
380
|
+
...(via ? { consume } : {}),
|
|
381
|
+
failed: failedRows.failed,
|
|
382
|
+
forget: failedRows.forget,
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Failed rows, newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page
|
|
388
|
+
* skips none. One row past the limit says there's another page.
|
|
389
|
+
*/
|
|
390
|
+
type Query = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
|
|
391
|
+
|
|
392
|
+
async function listFailed(sql: JobsSql, query: Query, { source, scope, limit, cursor }: FailedQuery) {
|
|
393
|
+
const [at, after] = cursor === undefined ? ["", ""] : cursorOf(cursor);
|
|
394
|
+
const matches = scope?.map(({ path, value }) => {
|
|
395
|
+
if (path.some((key) => !key || key.includes('"'))) throw new Error(`[logic-sdk] jobs.failed({ scope }) can't match the field ${JSON.stringify(path.join("."))}.`);
|
|
396
|
+
return { path, jsonPath: `$${path.map((key) => `."${key}"`).join("")}`, value };
|
|
397
|
+
});
|
|
398
|
+
const found = await query(sql.failed, [source ?? "", matches ? JSON.stringify(matches) : "", at, after, limit + 1]);
|
|
399
|
+
const page = found.slice(0, limit);
|
|
400
|
+
const last = page.at(-1);
|
|
401
|
+
return {
|
|
402
|
+
rows: page.map((row): FailedRow => ({
|
|
403
|
+
id: String(row.id),
|
|
404
|
+
job: JSON.parse(String(row.job)), // JSON text, on every driver
|
|
405
|
+
error: String(row.last_error ?? ""),
|
|
406
|
+
failedAt: new Date(/^\d+$/.test(String(row.failed_at)) ? Number(row.failed_at) : Date.parse(String(row.failed_at))).toISOString(), // SQLite: ms; Postgres: ISO text
|
|
407
|
+
})),
|
|
408
|
+
cursor: found.length > limit && last ? JSON.stringify([String(last.failed_at), String(last.id)]) : null,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
|
|
414
|
+
* `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
|
|
415
|
+
*/
|
|
416
|
+
export function failedStore(sql: JobsSql): FailedJobs {
|
|
417
|
+
const database = registryDatabase("failedJobs()");
|
|
418
|
+
const query = (text: string, params: unknown[]) => database.get().query(database.get().db, text, params);
|
|
419
|
+
return {
|
|
420
|
+
name: "failedJobs()",
|
|
421
|
+
sql: true,
|
|
422
|
+
connect: (setup) => database.connect(setup),
|
|
423
|
+
...rowsOfFailed(sql, query),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Failed rows in the jobs table: kept, listed, taken back for a retry, forgotten. A waiting or running row is never touched. */
|
|
428
|
+
function rowsOfFailed(sql: JobsSql, query: Query) {
|
|
429
|
+
return {
|
|
430
|
+
async fail(job: Job, error: unknown) {
|
|
431
|
+
await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
|
|
432
|
+
},
|
|
433
|
+
/**
|
|
434
|
+
* Newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page skips none.
|
|
435
|
+
* One row past the limit says there's another page.
|
|
436
|
+
*/
|
|
437
|
+
failed: (q: FailedQuery) => listFailed(sql, query, q),
|
|
438
|
+
async take(id: string): Promise<Job | undefined> {
|
|
439
|
+
const [row] = await query(sql.take, [id]);
|
|
440
|
+
return row ? JSON.parse(String(row.job)) : undefined;
|
|
441
|
+
},
|
|
442
|
+
async forget(id: string) {
|
|
443
|
+
return (await query(sql.forget, [id])).length > 0;
|
|
444
|
+
},
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** A `failed` page's cursor: the last row's `failed_at` (as the database gave it) and id. */
|
|
449
|
+
function cursorOf(cursor: string): [string, string] {
|
|
450
|
+
let parsed: unknown;
|
|
451
|
+
try {
|
|
452
|
+
parsed = JSON.parse(cursor);
|
|
453
|
+
} catch {
|
|
454
|
+
parsed = undefined;
|
|
455
|
+
}
|
|
456
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || !parsed.every((part) => typeof part === "string" && part))
|
|
457
|
+
throw new Error(`[logic-sdk] jobs.failed({ cursor }) takes the cursor of the page before (got ${JSON.stringify(cursor)}).`);
|
|
458
|
+
return parsed as [string, string];
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Not `localeCompare`: processes with another locale would lock in another order. */
|
|
462
|
+
const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
463
|
+
const describe = (e: unknown) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
|
package/src/ai.ts
CHANGED
|
@@ -1,62 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { isDomainError, type Caller, type FnIn, type FnOut, type ForFunctions, type PublishableFn, type ScopeOfFn } from "./index.ts";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
|
|
6
|
-
* `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
|
|
7
|
-
*/
|
|
8
|
-
export type AIMeta = ForFunctions<{
|
|
9
|
-
ai?: {
|
|
10
|
-
/** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
|
|
11
|
-
description?: string;
|
|
12
|
-
};
|
|
13
|
-
}>;
|
|
14
|
-
|
|
15
|
-
export interface AIToolOptions {
|
|
16
|
-
/** Overrides `meta.ai.description` for this tool. */
|
|
17
|
-
description?: string;
|
|
18
|
-
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
19
|
-
onError?: (error: unknown) => void;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
|
|
23
|
-
const aiMeta = (fn: { meta?: Readonly<Record<string, unknown>> }) => fn.meta?.ai as { description?: string } | undefined;
|
|
24
|
-
|
|
25
|
-
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
26
|
-
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
|
|
30
|
-
* and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
|
|
31
|
-
* `authorize`: the model acts for someone else.
|
|
32
|
-
*
|
|
33
|
-
* ```ts
|
|
34
|
-
* const caller = registry.as(await scopeFrom(request));
|
|
35
|
-
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
36
|
-
* ```
|
|
37
|
-
*
|
|
38
|
-
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
39
|
-
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
40
|
-
*/
|
|
41
|
-
export function toAITool<F extends PublishableFn>(
|
|
42
|
-
caller: Caller<ScopeOfFn<F>>,
|
|
43
|
-
fn: F,
|
|
44
|
-
options: AIToolOptions = {},
|
|
45
|
-
): Tool<FnIn<F>, FnOut<F>> {
|
|
46
|
-
if (!fn.authorize) throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
47
|
-
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
48
|
-
return tool({
|
|
49
|
-
description: options.description ?? aiMeta(fn)?.description,
|
|
50
|
-
inputSchema: fn.input ?? noInput,
|
|
51
|
-
outputSchema: fn.output,
|
|
52
|
-
async execute(input, { abortSignal }) {
|
|
53
|
-
try {
|
|
54
|
-
return await caller.run(fn, input, { signal: abortSignal });
|
|
55
|
-
} catch (e) {
|
|
56
|
-
if (isDomainError(e)) throw e;
|
|
57
|
-
onError(e);
|
|
58
|
-
throw new Error("internal_error");
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
|
-
}) as Tool<FnIn<F>, FnOut<F>>;
|
|
62
|
-
}
|
|
1
|
+
export { toAITool, type AIMeta, type AIToolOptions } from "./integrations/ai.ts";
|
package/src/cloudflare.ts
CHANGED
|
@@ -1,107 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
/** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
|
|
5
|
-
export interface QueueBinding {
|
|
6
|
-
sendBatch(messages: Iterable<{ body: Job; delaySeconds?: number }>): Promise<unknown>;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
/** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
|
|
10
|
-
export interface QueueBatch {
|
|
11
|
-
readonly messages: readonly {
|
|
12
|
-
readonly body: Job;
|
|
13
|
-
readonly attempts: number;
|
|
14
|
-
ack(): void;
|
|
15
|
-
retry(options?: { delaySeconds?: number }): void;
|
|
16
|
-
}[];
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
// Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
|
|
20
|
-
const MAX_MESSAGES = 100;
|
|
21
|
-
const MAX_BATCH_BYTES = 256_000;
|
|
22
|
-
const MAX_MESSAGE_BYTES = 128_000;
|
|
23
|
-
/** Cloudflare counts about this much metadata per message toward the limits. */
|
|
24
|
-
const OVERHEAD_BYTES = 100;
|
|
25
|
-
/** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
|
|
26
|
-
const MAX_DELAY = 86_400;
|
|
27
|
-
const encoder = new TextEncoder();
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
|
|
31
|
-
* them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
|
|
32
|
-
* Run them with `handleQueue(registry, batch)` in your consumer.
|
|
33
|
-
*/
|
|
34
|
-
export function cloudflareQueue(queue: QueueBinding): JobsAdapter {
|
|
35
|
-
return {
|
|
36
|
-
holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
|
|
37
|
-
async deliver(jobs) {
|
|
38
|
-
for (const batch of batches(jobs)) await queue.sendBatch(batch);
|
|
39
|
-
},
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
|
|
44
|
-
function* batches(jobs: Job[]) {
|
|
45
|
-
const sized = jobs.map((body) => {
|
|
46
|
-
const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
|
|
47
|
-
if (size > MAX_MESSAGE_BYTES)
|
|
48
|
-
throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
|
|
49
|
-
return { body, size };
|
|
50
|
-
});
|
|
51
|
-
let batch: { body: Job; delaySeconds?: number }[] = [];
|
|
52
|
-
let bytes = 0;
|
|
53
|
-
for (const { body, size } of sized) {
|
|
54
|
-
if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
|
|
55
|
-
yield batch;
|
|
56
|
-
batch = [];
|
|
57
|
-
bytes = 0;
|
|
58
|
-
}
|
|
59
|
-
batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
|
|
60
|
-
bytes += size;
|
|
61
|
-
}
|
|
62
|
-
if (batch.length) yield batch;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const secondsUntil = (iso: string) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
|
|
69
|
-
* retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
|
|
70
|
-
* its own, so one failure doesn't redeliver the batch.
|
|
71
|
-
*
|
|
72
|
-
* ```ts
|
|
73
|
-
* async queue(batch, env, ctx) {
|
|
74
|
-
* await handleQueue(makeRegistry(env, ctx), batch);
|
|
75
|
-
* },
|
|
76
|
-
* ```
|
|
77
|
-
*/
|
|
78
|
-
export async function handleQueue(registry: { jobs: Pick<Jobs, "run"> }, batch: QueueBatch): Promise<void> {
|
|
79
|
-
for (const message of batch.messages) {
|
|
80
|
-
try {
|
|
81
|
-
await registry.jobs.run(message.body, { attempt: message.attempts });
|
|
82
|
-
message.ack();
|
|
83
|
-
} catch {
|
|
84
|
-
// already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
|
|
85
|
-
message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
|
|
92
|
-
* delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
|
|
93
|
-
* 1 = Sunday, so write them as names (`MON`) in both places.
|
|
94
|
-
*
|
|
95
|
-
* ```ts
|
|
96
|
-
* async scheduled(controller, env, ctx) {
|
|
97
|
-
* await handleScheduled(makeRegistry(env, ctx), controller);
|
|
98
|
-
* },
|
|
99
|
-
* ```
|
|
100
|
-
*/
|
|
101
|
-
export async function handleScheduled(
|
|
102
|
-
registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
|
|
103
|
-
controller: { readonly scheduledTime: number },
|
|
104
|
-
): Promise<void> {
|
|
105
|
-
await registry.jobs.tick(new Date(controller.scheduledTime));
|
|
106
|
-
await registry.jobs.sweep();
|
|
107
|
-
}
|
|
1
|
+
export { cloudflareQueue, type QueueBinding } from "./adapters/cloudflare-queue.ts";
|
|
2
|
+
export { handleQueue, handleScheduled, type QueueBatch } from "./hosts/cloudflare.ts";
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { InProcess, JobsAdapter } from "./types.ts";
|
|
2
|
+
import { RUNS_NOW } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
/** The last job of each key, in this process: the next one starts after it. */
|
|
5
|
+
const lastOfKey = new Map<string, Promise<unknown>>();
|
|
6
|
+
|
|
7
|
+
const IN_PROCESS: InProcess = {
|
|
8
|
+
[RUNS_NOW]: true,
|
|
9
|
+
name: "inProcess()",
|
|
10
|
+
orders: true,
|
|
11
|
+
queues: true, // nothing waits, so there's nothing to keep apart
|
|
12
|
+
async deliver(jobs, { run }) {
|
|
13
|
+
for (const job of jobs) {
|
|
14
|
+
// one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
|
|
15
|
+
const once = () => run({ ...job, attempts: 1 });
|
|
16
|
+
const key = job.kind === "delivery" ? job.key : undefined;
|
|
17
|
+
if (!key) {
|
|
18
|
+
await once();
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const mine = (lastOfKey.get(key) ?? Promise.resolve()).then(once);
|
|
22
|
+
const settled = mine.catch(() => {});
|
|
23
|
+
lastOfKey.set(key, settled);
|
|
24
|
+
try {
|
|
25
|
+
await mine;
|
|
26
|
+
} finally {
|
|
27
|
+
if (lastOfKey.get(key) === settled) lastOfKey.delete(key);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
|
|
34
|
+
* hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
|
|
35
|
+
*/
|
|
36
|
+
export const inProcess = (): InProcess => IN_PROCESS;
|
|
37
|
+
/** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
|
|
38
|
+
export const runsNow = (adapter: JobsAdapter) => RUNS_NOW in adapter;
|