logic-sdk 0.7.2 → 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 +2 -3
- package/dist/adapters/cloudflare-queue.d.ts +3 -2
- package/dist/adapters/cloudflare-queue.js +14 -4
- package/dist/adapters/drizzle-pg.d.ts +31 -1
- package/dist/adapters/drizzle-pg.js +14 -5
- package/dist/adapters/drizzle-sqlite.d.ts +17 -1
- package/dist/adapters/drizzle-sqlite.js +11 -4
- package/dist/adapters/postgres.d.ts +9 -8
- package/dist/adapters/postgres.js +43 -19
- package/dist/adapters/sqlite.d.ts +1 -1
- package/dist/adapters/sqlite.js +32 -12
- package/dist/adapters/stored-jobs.d.ts +27 -19
- package/dist/adapters/stored-jobs.js +157 -61
- package/dist/core/in-process.js +23 -3
- package/dist/core/jobs.d.ts +12 -6
- package/dist/core/jobs.js +158 -17
- package/dist/core/registry.d.ts +39 -3
- package/dist/core/registry.js +23 -11
- package/dist/core/testing.js +3 -1
- package/dist/core/types.d.ts +96 -34
- package/dist/hosts/cloudflare.d.ts +5 -4
- package/dist/hosts/cloudflare.js +5 -4
- package/dist/hosts/node.d.ts +25 -15
- package/dist/hosts/node.js +61 -34
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/package.json +1 -11
- package/skills/logic-sdk/SKILL.md +4 -4
- package/src/adapters/cloudflare-queue.ts +13 -4
- package/src/adapters/drizzle-pg.ts +14 -5
- package/src/adapters/drizzle-sqlite.ts +11 -4
- package/src/adapters/postgres.ts +43 -19
- package/src/adapters/sqlite.ts +32 -12
- package/src/adapters/stored-jobs.ts +174 -74
- package/src/core/in-process.ts +22 -2
- package/src/core/jobs.ts +146 -19
- package/src/core/registry.ts +62 -14
- package/src/core/testing.ts +3 -1
- package/src/core/types.ts +93 -30
- package/src/hosts/cloudflare.ts +5 -4
- package/src/hosts/node.ts +73 -46
- package/src/index.ts +3 -1
- package/src/node.ts +1 -1
- package/dist/adapters/pg-boss.d.ts +0 -45
- package/dist/adapters/pg-boss.js +0 -180
- package/dist/hosts/pg-boss.d.ts +0 -22
- package/dist/hosts/pg-boss.js +0 -55
- package/dist/pg-boss.d.ts +0 -2
- package/dist/pg-boss.js +0 -2
- package/src/adapters/pg-boss.ts +0 -195
- package/src/hosts/pg-boss.ts +0 -71
- package/src/pg-boss.ts +0 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Jobs in the registry's database, written in the mutation's transaction: run from there (databaseQueue), or kept
|
|
2
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
3
|
// the database adapter's `query`, so this file knows no ORM and no driver.
|
|
4
|
-
import { defaultBackoff,
|
|
5
|
-
import type { AdapterSetup, FailedJobs, FailedQuery, FailedRow, Job, JobOutcome, JobsAdapter, Runner, SqlDatabase, SweepResult } from "../core/types.ts";
|
|
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
6
|
|
|
7
7
|
/**
|
|
8
8
|
* The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
|
|
@@ -10,23 +10,33 @@ import type { AdapterSetup, FailedJobs, FailedQuery, FailedRow, Job, JobOutcome,
|
|
|
10
10
|
* the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
|
|
11
11
|
*/
|
|
12
12
|
export interface JobsSql {
|
|
13
|
-
/**
|
|
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
|
+
*/
|
|
14
17
|
insert: string;
|
|
15
18
|
/** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
|
|
16
19
|
recordTicks: string;
|
|
17
20
|
/** `()`: forgets ticks older than a day. */
|
|
18
21
|
pruneTicks: string;
|
|
19
|
-
/** `(receipt, lease,
|
|
22
|
+
/** `(receipt, lease, id)`: the first claim, of a row nobody claimed. Returns `id`. */
|
|
20
23
|
claimNew: string;
|
|
21
|
-
/**
|
|
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
|
+
*/
|
|
22
28
|
claimDue: string;
|
|
23
|
-
/** `(
|
|
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. */
|
|
24
34
|
extend: string;
|
|
25
|
-
/** `(seconds, error,
|
|
35
|
+
/** `(seconds, error, id, receipt)` */
|
|
26
36
|
backOff: string;
|
|
27
|
-
/** `(error,
|
|
37
|
+
/** `(error, id, receipt)` */
|
|
28
38
|
markFailed: string;
|
|
29
|
-
/** `(
|
|
39
|
+
/** `(id, receipt)` */
|
|
30
40
|
remove: string;
|
|
31
41
|
/** `(id)`: a failed row back in line. Returns `id`. */
|
|
32
42
|
retry: string;
|
|
@@ -44,22 +54,37 @@ export interface JobsSql {
|
|
|
44
54
|
take: string;
|
|
45
55
|
}
|
|
46
56
|
|
|
47
|
-
/**
|
|
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
|
+
*/
|
|
48
61
|
const PICKUP = 30;
|
|
49
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
|
+
|
|
50
66
|
/**
|
|
51
|
-
* Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer,
|
|
52
|
-
*
|
|
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.
|
|
53
69
|
*/
|
|
54
70
|
const MAX_EXTEND = 15 * 60;
|
|
55
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
|
+
|
|
56
81
|
/** Who owns a job while it runs. */
|
|
57
82
|
interface Claim {
|
|
58
83
|
receipt: string;
|
|
59
84
|
attempt: number;
|
|
60
85
|
}
|
|
61
86
|
|
|
62
|
-
export interface
|
|
87
|
+
export interface OutboxOptions {
|
|
63
88
|
/**
|
|
64
89
|
* Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
|
|
65
90
|
* job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
|
|
@@ -70,19 +95,19 @@ export interface DatabaseQueueOptions {
|
|
|
70
95
|
backoff?: (attempt: number) => number;
|
|
71
96
|
}
|
|
72
97
|
|
|
73
|
-
|
|
74
|
-
export interface OutboxOptions extends DatabaseQueueOptions {
|
|
98
|
+
export interface DatabaseQueueOptions extends OutboxOptions {
|
|
75
99
|
/**
|
|
76
|
-
*
|
|
77
|
-
*
|
|
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.
|
|
78
103
|
*/
|
|
79
|
-
|
|
104
|
+
runIn?: "request" | "worker";
|
|
80
105
|
}
|
|
81
106
|
|
|
82
107
|
/** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
|
|
83
108
|
export interface StoredJobs extends JobsAdapter {
|
|
84
109
|
/** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
|
|
85
|
-
sweep(runner: Runner, options?:
|
|
110
|
+
sweep(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
|
|
86
111
|
/** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
|
|
87
112
|
retry(id: string): Promise<boolean>;
|
|
88
113
|
/** A page of failed rows, newest first. */
|
|
@@ -98,12 +123,17 @@ export interface StoredJobs extends JobsAdapter {
|
|
|
98
123
|
*/
|
|
99
124
|
function registryDatabase(name: string) {
|
|
100
125
|
let database: SqlDatabase | undefined;
|
|
126
|
+
let workers: AdapterSetup["workers"] = { takes: () => false, wake: () => {} };
|
|
101
127
|
return {
|
|
102
|
-
connect(
|
|
128
|
+
connect(setup: AdapterSetup) {
|
|
129
|
+
const { sql } = setup;
|
|
103
130
|
if (database && sql && database.db !== sql.db)
|
|
104
131
|
throw new Error(`[logic-sdk] ${name} is already connected to another registry's database: call it once per registry.`);
|
|
105
132
|
database = sql;
|
|
133
|
+
workers = setup.workers;
|
|
106
134
|
},
|
|
135
|
+
/** The loops running jobs in this process (`work()`). */
|
|
136
|
+
workers: () => workers,
|
|
107
137
|
get(): SqlDatabase {
|
|
108
138
|
if (!database) throw new Error(`[logic-sdk] ${name} isn't connected: pass it to createRegistry.`);
|
|
109
139
|
return database;
|
|
@@ -111,24 +141,31 @@ function registryDatabase(name: string) {
|
|
|
111
141
|
};
|
|
112
142
|
}
|
|
113
143
|
|
|
114
|
-
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it
|
|
115
|
-
export function storedJobs(sql: JobsSql, options:
|
|
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 {
|
|
116
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.`);
|
|
117
150
|
const database = registryDatabase(name);
|
|
118
151
|
const lease = options.lease ?? 300;
|
|
119
|
-
const maxAttempts = options.maxAttempts ?? 10;
|
|
120
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));
|
|
121
159
|
/** Outside a mutation: on the database itself. */
|
|
122
160
|
const query = (text: string, params: unknown[]) => database.get().query(database.get().db, text, params);
|
|
123
161
|
const list = (ids: string[]) => JSON.stringify(ids);
|
|
124
162
|
|
|
125
163
|
// These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
|
|
126
|
-
// newer runner's work
|
|
127
|
-
// receipt, not attempt number: `retry(id)` starts those again at 1.
|
|
164
|
+
// newer runner's work. By receipt, not attempt number: `retry(id)` starts those again at 1.
|
|
128
165
|
const failedRows = rowsOfFailed(sql, query);
|
|
129
|
-
const markFailed = (
|
|
130
|
-
const backOff = (
|
|
131
|
-
const remove = (
|
|
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]);
|
|
132
169
|
|
|
133
170
|
/**
|
|
134
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
|
|
@@ -142,7 +179,7 @@ export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapt
|
|
|
142
179
|
() => {
|
|
143
180
|
if (Date.now() >= until) return clearInterval(timer);
|
|
144
181
|
extending = extending
|
|
145
|
-
.then(() => query(sql.extend, [lease,
|
|
182
|
+
.then(() => query(sql.extend, [lease, job.id, claim.receipt]))
|
|
146
183
|
.catch((e) => runner.report(e, job, claim.attempt));
|
|
147
184
|
},
|
|
148
185
|
(lease * 1000) / 3,
|
|
@@ -155,7 +192,7 @@ export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapt
|
|
|
155
192
|
|
|
156
193
|
/**
|
|
157
194
|
* Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
|
|
158
|
-
* (tries left: back off), or done and discarded (delete the row).
|
|
195
|
+
* (tries left: back off, and behind an outbox signal the retry), or done and discarded (delete the row).
|
|
159
196
|
*/
|
|
160
197
|
async function run(job: Job, claim: Claim, runner: Runner): Promise<keyof SweepResult> {
|
|
161
198
|
const stopExtending = keepExtending(job, claim, runner);
|
|
@@ -165,34 +202,77 @@ export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapt
|
|
|
165
202
|
.run(job, {
|
|
166
203
|
attempt: claim.attempt,
|
|
167
204
|
fail: async (error) => {
|
|
168
|
-
await markFailed(
|
|
205
|
+
await markFailed(job, claim, error);
|
|
169
206
|
},
|
|
170
207
|
})
|
|
171
208
|
.finally(stopExtending);
|
|
172
209
|
} catch (e) {
|
|
173
|
-
|
|
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);
|
|
174
213
|
return "retrying";
|
|
175
214
|
}
|
|
176
|
-
if (outcome !== "failed") await remove(
|
|
215
|
+
if (outcome !== "failed") await remove(job, claim);
|
|
177
216
|
return outcome;
|
|
178
217
|
}
|
|
179
218
|
|
|
180
|
-
/**
|
|
181
|
-
|
|
182
|
-
|
|
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
|
+
};
|
|
183
271
|
try {
|
|
184
|
-
await
|
|
272
|
+
await via!.deliver(signals, consumer);
|
|
185
273
|
} catch (e) {
|
|
186
|
-
for (const job of
|
|
187
|
-
if (claim.attempt >= maxAttempts) {
|
|
188
|
-
await markFailed(ids, claim, e);
|
|
189
|
-
return "failed";
|
|
190
|
-
}
|
|
191
|
-
await backOff(ids, claim, e);
|
|
192
|
-
return "retrying";
|
|
274
|
+
for (const job of signals) runner.report(e, job);
|
|
193
275
|
}
|
|
194
|
-
await remove(ids, claim);
|
|
195
|
-
return "done";
|
|
196
276
|
}
|
|
197
277
|
|
|
198
278
|
/** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
|
|
@@ -203,69 +283,90 @@ export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapt
|
|
|
203
283
|
return new Set(first.map((row) => row.id));
|
|
204
284
|
}
|
|
205
285
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
/** The first claim of jobs just committed, by the request that queued them: the ones no sweep took meanwhile. */
|
|
209
|
-
async function claimNew(jobs: Job[]): Promise<{ claim: Claim; won: Job[] }> {
|
|
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> {
|
|
210
288
|
const claim = { receipt: crypto.randomUUID(), attempt: 1 };
|
|
211
|
-
const rows = await query(sql.claimNew, [claim.receipt, lease,
|
|
212
|
-
|
|
213
|
-
return { claim, won: jobs.filter((j) => ids.has(j.id)) }; // in emit order: RETURNING has none
|
|
289
|
+
const rows = await query(sql.claimNew, [claim.receipt, lease, job.id]);
|
|
290
|
+
return rows.length ? claim : undefined;
|
|
214
291
|
}
|
|
215
292
|
|
|
216
293
|
return {
|
|
217
294
|
name,
|
|
218
295
|
retries: true, // a failed try backs off as a row
|
|
219
296
|
holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
|
|
220
|
-
replaces: true, // a waiting row is replaced in place;
|
|
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
|
|
221
300
|
/** Takes the registry's database: it writes in the mutation's transaction. */
|
|
222
301
|
sql: true,
|
|
223
302
|
connect: (setup) => database.connect(setup),
|
|
224
303
|
/**
|
|
225
304
|
* Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
|
|
226
|
-
* request
|
|
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.
|
|
227
307
|
*/
|
|
228
308
|
async enqueue(tx, jobs) {
|
|
229
309
|
const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
|
|
230
310
|
const kept = jobs.filter((j) => j.kind !== "cron" || firstTicks.has(j.id));
|
|
231
|
-
const rows = (await Promise.all(kept.map(async (j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null,
|
|
232
|
-
// in key order, so two transactions
|
|
233
|
-
.sort((a, b) => byText(a.
|
|
234
|
-
if (rows.length) await database.get().query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
|
|
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)]);
|
|
235
315
|
},
|
|
236
316
|
/**
|
|
237
|
-
* After commit, in this request
|
|
238
|
-
*
|
|
239
|
-
* is a sweep's, as a first try.
|
|
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.
|
|
240
320
|
*/
|
|
241
321
|
async deliver(jobs, runner) {
|
|
242
|
-
const due = jobs.filter((j) => !j.runAt);
|
|
243
|
-
if (!due.length) return;
|
|
244
322
|
if (via) {
|
|
245
|
-
const
|
|
246
|
-
|
|
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);
|
|
247
336
|
return;
|
|
248
337
|
}
|
|
249
338
|
for (const job of due) {
|
|
250
339
|
try {
|
|
251
|
-
const
|
|
252
|
-
if (
|
|
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
|
|
253
345
|
} catch (e) {
|
|
254
346
|
runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
|
|
255
347
|
}
|
|
256
348
|
}
|
|
257
349
|
},
|
|
258
|
-
/**
|
|
259
|
-
|
|
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 } = {}) {
|
|
260
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 : [""];
|
|
261
358
|
for (let i = 0; i < limit; i++) {
|
|
262
359
|
const receipt = crypto.randomUUID();
|
|
263
|
-
|
|
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
|
+
}
|
|
264
365
|
if (!row) break;
|
|
265
366
|
const job: Job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
|
|
266
367
|
const attempt = Number(row.attempts);
|
|
267
368
|
try {
|
|
268
|
-
result[await
|
|
369
|
+
result[await run(job, { receipt, attempt }, runner)]++;
|
|
269
370
|
} catch (e) {
|
|
270
371
|
runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
|
|
271
372
|
}
|
|
@@ -276,8 +377,7 @@ export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapt
|
|
|
276
377
|
async retry(id) {
|
|
277
378
|
return (await query(sql.retry, [id])).length > 0;
|
|
278
379
|
},
|
|
279
|
-
|
|
280
|
-
fail: failedRows.fail,
|
|
380
|
+
...(via ? { consume } : {}),
|
|
281
381
|
failed: failedRows.failed,
|
|
282
382
|
forget: failedRows.forget,
|
|
283
383
|
};
|
package/src/core/in-process.ts
CHANGED
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
import type { InProcess, JobsAdapter } from "./types.ts";
|
|
2
2
|
import { RUNS_NOW } from "./types.ts";
|
|
3
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
|
+
|
|
4
7
|
const IN_PROCESS: InProcess = {
|
|
5
8
|
[RUNS_NOW]: true,
|
|
6
9
|
name: "inProcess()",
|
|
10
|
+
orders: true,
|
|
11
|
+
queues: true, // nothing waits, so there's nothing to keep apart
|
|
7
12
|
async deliver(jobs, { run }) {
|
|
8
|
-
|
|
9
|
-
|
|
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
|
+
}
|
|
10
30
|
},
|
|
11
31
|
};
|
|
12
32
|
/**
|