logic-sdk 0.3.0 → 0.5.0
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 +47 -22
- package/dist/ai.d.ts +16 -29
- package/dist/ai.js +13 -24
- package/dist/cloudflare.d.ts +55 -0
- package/dist/cloudflare.js +85 -0
- package/dist/drizzle/pg.d.ts +237 -0
- package/dist/drizzle/pg.js +67 -0
- package/dist/drizzle/sqlite.d.ts +242 -0
- package/dist/drizzle/sqlite.js +194 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +45 -0
- package/dist/fetch.d.ts +15 -18
- package/dist/fetch.js +18 -55
- package/dist/index.d.ts +80 -443
- package/dist/index.js +261 -229
- package/dist/jobs.d.ts +44 -0
- package/dist/jobs.js +252 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +76 -0
- package/dist/orpc.d.ts +10 -20
- package/dist/orpc.js +19 -28
- package/dist/pg-boss.d.ts +55 -0
- package/dist/pg-boss.js +211 -0
- package/dist/postgres.d.ts +28 -0
- package/dist/postgres.js +82 -0
- package/dist/schedule.d.ts +23 -0
- package/dist/schedule.js +109 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.js +65 -0
- package/dist/stored-jobs.d.ts +64 -0
- package/dist/stored-jobs.js +188 -0
- package/dist/testing.d.ts +51 -15
- package/dist/testing.js +198 -46
- package/dist/types.d.ts +653 -0
- package/dist/types.js +6 -0
- package/package.json +45 -7
- package/skills/logic-sdk/SKILL.md +114 -0
- package/src/ai.ts +29 -51
- package/src/cloudflare.ts +107 -0
- package/src/drizzle/pg.ts +111 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +422 -572
- package/src/jobs.ts +296 -0
- package/src/node.ts +99 -0
- package/src/orpc.ts +24 -43
- package/src/pg-boss.ts +242 -0
- package/src/postgres.ts +90 -0
- package/src/schedule.ts +129 -0
- package/src/sqlite.ts +74 -0
- package/src/stored-jobs.ts +260 -0
- package/src/testing.ts +253 -56
- package/src/types.ts +683 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- package/src/drizzle.ts +0 -39
package/dist/pg-boss.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// pg-boss runs on Node (`pg`, `node:events`), so this subpath may too; the core stays runtime-neutral.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { sql } from "drizzle-orm";
|
|
5
|
+
import { fromDrizzle } from "pg-boss";
|
|
6
|
+
import { replaceKeyOf } from "./index.js";
|
|
7
|
+
import { startTicking } from "./node.js";
|
|
8
|
+
/** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
|
|
9
|
+
const PREFIX = "logic-sdk.";
|
|
10
|
+
/** A listener's or cron's queue: `logic-sdk.notifications.send`. */
|
|
11
|
+
const queueName = (id) => `${PREFIX}${id}`;
|
|
12
|
+
/** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
|
|
13
|
+
const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
|
|
14
|
+
/** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
|
|
15
|
+
const queueOf = (job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
|
|
16
|
+
/** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
|
|
17
|
+
const queueConfig = (queue) => ({ ...queue, retryBackoff: true });
|
|
18
|
+
/** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
|
|
19
|
+
const tuningOf = (meta) => meta?.pgBoss;
|
|
20
|
+
// A UUID of our own, so the v5 ids below can't collide with anyone else's.
|
|
21
|
+
const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
|
|
22
|
+
/**
|
|
23
|
+
* The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
|
|
24
|
+
* minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
|
|
25
|
+
*/
|
|
26
|
+
export function pgBossId(id) {
|
|
27
|
+
const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
|
|
28
|
+
hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
|
|
29
|
+
hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
|
|
30
|
+
const hex = hash.toString("hex", 0, 16);
|
|
31
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
|
|
35
|
+
* never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
|
|
36
|
+
* left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
|
|
37
|
+
* at pickup. A last try that throws is `deadletter`, so it never uses the spare.
|
|
38
|
+
*/
|
|
39
|
+
const rowOf = (job, replaceKey) => ({
|
|
40
|
+
id: pgBossId(job.id),
|
|
41
|
+
data: job,
|
|
42
|
+
startAfter: job.runAt,
|
|
43
|
+
retryLimit: job.attempts,
|
|
44
|
+
retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
|
|
45
|
+
singletonKey: replaceKey,
|
|
46
|
+
});
|
|
47
|
+
// SAFETY: `check` requires a database adapter. Only `drizzleAdapter`'s (Postgres) transactions run pg-boss's SQL: another
|
|
48
|
+
// adapter fails at the first enqueue. Any adapter's `query` is for after 0.5.0 (pg-boss passes arrays and JSON).
|
|
49
|
+
const inTx = (tx) => fromDrizzle(tx, sql);
|
|
50
|
+
/**
|
|
51
|
+
* Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
|
|
52
|
+
* like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
|
|
53
|
+
* `await boss.start()` first.
|
|
54
|
+
*
|
|
55
|
+
* ```ts
|
|
56
|
+
* const boss = new PgBoss(process.env.DATABASE_URL!);
|
|
57
|
+
* boss.on("error", console.error);
|
|
58
|
+
* const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export function pgBoss(boss) {
|
|
62
|
+
let database;
|
|
63
|
+
const queueOptions = new Map();
|
|
64
|
+
/**
|
|
65
|
+
* pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
|
|
66
|
+
* new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
|
|
67
|
+
* on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
|
|
68
|
+
*/
|
|
69
|
+
async function inQueue(name, write) {
|
|
70
|
+
try {
|
|
71
|
+
await write();
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND"))
|
|
75
|
+
throw error;
|
|
76
|
+
await boss.createQueue(name, queueConfig(queueOptions.get(name)));
|
|
77
|
+
await write();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
|
|
82
|
+
* a job in `retry` has started, and isn't touched.
|
|
83
|
+
*/
|
|
84
|
+
async function replaceWaiting(db, keys) {
|
|
85
|
+
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
86
|
+
for (const key of [...new Set(keys)].sort()) {
|
|
87
|
+
// one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
|
|
88
|
+
await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
|
|
89
|
+
// a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
|
|
90
|
+
const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
|
|
91
|
+
if (!locked.length)
|
|
92
|
+
continue;
|
|
93
|
+
const queued = await boss.findJobs(CALLS_QUEUE, { key, queued: true, db });
|
|
94
|
+
const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
|
|
95
|
+
if (waiting.length)
|
|
96
|
+
await boss.deleteJob(CALLS_QUEUE, waiting, { db });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
holds: true, // `startAfter`, however far ahead
|
|
101
|
+
replaces: true,
|
|
102
|
+
/** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
103
|
+
check({ listeners, database: given }) {
|
|
104
|
+
if (!given)
|
|
105
|
+
throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
|
|
106
|
+
database = given;
|
|
107
|
+
for (const l of listeners)
|
|
108
|
+
queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
109
|
+
},
|
|
110
|
+
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
111
|
+
async enqueue(tx, jobs) {
|
|
112
|
+
const db = inTx(tx);
|
|
113
|
+
for (const [name, list] of Map.groupBy(jobs, queueOf)) {
|
|
114
|
+
const keys = list.map(replaceKeyOf).filter((key) => key !== undefined);
|
|
115
|
+
await inQueue(name, async () => {
|
|
116
|
+
if (keys.length)
|
|
117
|
+
await replaceWaiting(db, keys);
|
|
118
|
+
await boss.insert(name, list.map((job) => rowOf(job, replaceKeyOf(job))), { db });
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
/** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
|
|
123
|
+
async deliver() { },
|
|
124
|
+
/**
|
|
125
|
+
* A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
|
|
126
|
+
* it has run, so it's no longer a call a newer one replaces.
|
|
127
|
+
*/
|
|
128
|
+
async retry(id) {
|
|
129
|
+
// its queue: the listener's or cron's (the id's prefix), or the calls queue. Looked up first: inside the
|
|
130
|
+
// transaction, a lookup on pg-boss's own connection would wait for it on PGlite.
|
|
131
|
+
const at = id.lastIndexOf("@");
|
|
132
|
+
if (at < 0)
|
|
133
|
+
return false; // not a job id
|
|
134
|
+
const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
|
|
135
|
+
const queues = await boss.getQueues(names);
|
|
136
|
+
if (!database || !queues.length)
|
|
137
|
+
return false;
|
|
138
|
+
const uuid = pgBossId(id);
|
|
139
|
+
return database.transaction(async (tx) => {
|
|
140
|
+
const db = inTx(tx);
|
|
141
|
+
for (const { name } of queues) {
|
|
142
|
+
// failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
|
|
143
|
+
const { affected } = await boss.retry(name, uuid, { db });
|
|
144
|
+
if (!affected)
|
|
145
|
+
continue;
|
|
146
|
+
const [failed] = await boss.findJobs(name, { id: uuid, db });
|
|
147
|
+
if (!failed)
|
|
148
|
+
continue;
|
|
149
|
+
// as new: retry count 0, and its retries again
|
|
150
|
+
await boss.deleteJob(name, uuid, { db });
|
|
151
|
+
await boss.insert(name, [rowOf(failed.data)], { db });
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
});
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
161
|
+
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
162
|
+
*
|
|
163
|
+
* ```ts
|
|
164
|
+
* await boss.start();
|
|
165
|
+
* await work(registry, boss);
|
|
166
|
+
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export async function work(registry, boss, options = {}) {
|
|
170
|
+
const { listeners, crons } = registry.definitions;
|
|
171
|
+
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
172
|
+
const queues = [
|
|
173
|
+
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
174
|
+
...crons.map((c) => ({ name: queueName(c.id), tuning: options.crons })),
|
|
175
|
+
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
176
|
+
];
|
|
177
|
+
/** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
|
|
178
|
+
const settle = async (job) => {
|
|
179
|
+
let reason;
|
|
180
|
+
const fail = async (error) => {
|
|
181
|
+
reason = error; // kept by pg-boss as the failed job's output
|
|
182
|
+
};
|
|
183
|
+
try {
|
|
184
|
+
const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
|
|
185
|
+
if (outcome === "failed")
|
|
186
|
+
return { id: job.id, status: "deadletter", output: reason };
|
|
187
|
+
return { id: job.id, status: "completed" };
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
for (const { name, tuning } of queues) {
|
|
194
|
+
const config = queueConfig(tuning?.queue);
|
|
195
|
+
const { partition: _createOnly, ...updatable } = config;
|
|
196
|
+
await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
|
|
197
|
+
await boss.updateQueue(name, updatable);
|
|
198
|
+
await boss.work(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
|
|
199
|
+
}
|
|
200
|
+
// a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
|
|
201
|
+
// They never get a try that could report, so say so here
|
|
202
|
+
const ours = new Set(queues.map((q) => q.name));
|
|
203
|
+
for (const q of await boss.getQueues())
|
|
204
|
+
if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
|
|
205
|
+
onError(new Error(`[logic-sdk] pg-boss queue ${q.name} has ${q.queuedCount} job(s) and no listener or cron here (renamed or removed?). Give it its old id back, or delete the queue.`));
|
|
206
|
+
if (!crons.length)
|
|
207
|
+
return;
|
|
208
|
+
// ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
|
|
209
|
+
const stop = startTicking(registry, { sweepEvery: 0, onError });
|
|
210
|
+
boss.once("stopped", () => void stop());
|
|
211
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { JobsAdapter, SqlDatabase } from "./index.ts";
|
|
3
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
4
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n last_error text,\n failed_at timestamptz,\n replace_key text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\n";
|
|
6
|
+
/**
|
|
7
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
8
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
9
|
+
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
10
|
+
* its row being deleted runs it again.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
|
|
14
|
+
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
|
|
18
|
+
/**
|
|
19
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
20
|
+
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
21
|
+
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
22
|
+
* so a job can run twice, even at once.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The jobs table on Postgres, in SQL. With Drizzle, import from `logic-sdk/drizzle/pg` instead: the same two
|
|
2
|
+
// functions, plus the table for your schema.
|
|
3
|
+
import { storedJobs } from "./stored-jobs.js";
|
|
4
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
+
export const jobsSchema = `
|
|
6
|
+
CREATE TABLE logic_jobs (
|
|
7
|
+
id text PRIMARY KEY,
|
|
8
|
+
job jsonb NOT NULL,
|
|
9
|
+
status text NOT NULL DEFAULT 'pending',
|
|
10
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
11
|
+
available_at timestamptz NOT NULL DEFAULT now(),
|
|
12
|
+
receipt text,
|
|
13
|
+
last_error text,
|
|
14
|
+
failed_at timestamptz,
|
|
15
|
+
replace_key text,
|
|
16
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
17
|
+
);
|
|
18
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
19
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
20
|
+
CREATE TABLE logic_cron_runs (
|
|
21
|
+
id text PRIMARY KEY,
|
|
22
|
+
ran_at timestamptz NOT NULL DEFAULT now()
|
|
23
|
+
);
|
|
24
|
+
`;
|
|
25
|
+
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
26
|
+
const ids = (n) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
|
|
27
|
+
const mine = (n) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
28
|
+
const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
|
|
29
|
+
const statements = {
|
|
30
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
|
|
31
|
+
insert: `
|
|
32
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
33
|
+
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
|
|
34
|
+
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
35
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
36
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
|
|
37
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
38
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
39
|
+
claimNew: `
|
|
40
|
+
UPDATE logic_jobs SET attempts = 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
41
|
+
WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
42
|
+
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
43
|
+
claimDue: `
|
|
44
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
45
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
46
|
+
RETURNING job::text AS job, attempts`,
|
|
47
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
48
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2 WHERE ${mine(3)}`,
|
|
49
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now() WHERE ${mine(2)}`,
|
|
50
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
51
|
+
// its receipt goes, so the runner that lost it can't finish the new run. Its key goes: it has run, so it's no longer
|
|
52
|
+
// a call a newer one replaces (and one may be waiting with it)
|
|
53
|
+
retry: `
|
|
54
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
55
|
+
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
56
|
+
fail: `
|
|
57
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
58
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
62
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
63
|
+
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
64
|
+
* its row being deleted runs it again.
|
|
65
|
+
*
|
|
66
|
+
* ```ts
|
|
67
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
|
|
68
|
+
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
|
|
72
|
+
/**
|
|
73
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
74
|
+
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
75
|
+
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
76
|
+
* so a job can run twice, even at once.
|
|
77
|
+
*
|
|
78
|
+
* ```ts
|
|
79
|
+
* jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Five-field cron expressions (`minute hour day-of-month month day-of-week`), matched against one minute in a time zone.
|
|
3
|
+
* Lists, ranges and steps (`1,15`, `9-17`, `*\/5`, `1-30/5`), month and weekday names, `7` as Sunday. Days follow
|
|
4
|
+
* Vixie cron: when both day fields are restricted, either one matching is enough.
|
|
5
|
+
*/
|
|
6
|
+
export interface Schedule {
|
|
7
|
+
minute: Set<number>;
|
|
8
|
+
hour: Set<number>;
|
|
9
|
+
day: Set<number>;
|
|
10
|
+
month: Set<number>;
|
|
11
|
+
weekday: Set<number>;
|
|
12
|
+
/** Restricted day fields (not starting with `*`): both restricted means day OR weekday. */
|
|
13
|
+
dayRestricted: boolean;
|
|
14
|
+
weekdayRestricted: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function parseSchedule(expression: string): Schedule;
|
|
17
|
+
/**
|
|
18
|
+
* Is `date`'s minute due in `timeZone`? Wall-clock matching, like Laravel: a time skipped when clocks go forward doesn't
|
|
19
|
+
* run, and one that happens twice when they go back runs twice.
|
|
20
|
+
*/
|
|
21
|
+
export declare function isDue(schedule: Schedule, date: Date, timeZone?: string): boolean;
|
|
22
|
+
/** Checks a time zone name, so a typo fails at startup, not on the first tick. */
|
|
23
|
+
export declare function assertTimeZone(timeZone: string): void;
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
2
|
+
const WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
3
|
+
const FIELDS = {
|
|
4
|
+
minute: { name: "minute", min: 0, max: 59 },
|
|
5
|
+
hour: { name: "hour", min: 0, max: 23 },
|
|
6
|
+
day: { name: "day of month", min: 1, max: 31 },
|
|
7
|
+
month: { name: "month", min: 1, max: 12, names: MONTHS },
|
|
8
|
+
weekday: { name: "day of week", min: 0, max: 7, names: WEEKDAYS },
|
|
9
|
+
};
|
|
10
|
+
export function parseSchedule(expression) {
|
|
11
|
+
const parts = expression.trim().split(/\s+/);
|
|
12
|
+
if (parts.length !== 5)
|
|
13
|
+
throw new Error(`[logic-sdk] cron schedule "${expression}" needs five fields (minute hour day month weekday), like "0 9 * * 1".`);
|
|
14
|
+
const [minute = "", hour = "", day = "", month = "", weekday = ""] = parts;
|
|
15
|
+
const weekdays = parseField(weekday, FIELDS.weekday, expression);
|
|
16
|
+
if (weekdays.delete(7))
|
|
17
|
+
weekdays.add(0); // 7 is Sunday too
|
|
18
|
+
return {
|
|
19
|
+
minute: parseField(minute, FIELDS.minute, expression),
|
|
20
|
+
hour: parseField(hour, FIELDS.hour, expression),
|
|
21
|
+
day: parseField(day, FIELDS.day, expression),
|
|
22
|
+
month: parseField(month, FIELDS.month, expression),
|
|
23
|
+
weekday: weekdays,
|
|
24
|
+
dayRestricted: !day.startsWith("*"),
|
|
25
|
+
weekdayRestricted: !weekday.startsWith("*"),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function parseField(part, field, expression) {
|
|
29
|
+
const fail = () => new Error(`[logic-sdk] cron schedule "${expression}" has an invalid ${field.name}: "${part}".`);
|
|
30
|
+
const value = (token) => {
|
|
31
|
+
const index = field.names?.indexOf(token.toLowerCase()) ?? -1;
|
|
32
|
+
const n = index >= 0 ? index + field.min : /^\d+$/.test(token) ? Number(token) : NaN;
|
|
33
|
+
if (!(n >= field.min && n <= field.max))
|
|
34
|
+
throw fail();
|
|
35
|
+
return n;
|
|
36
|
+
};
|
|
37
|
+
const values = new Set();
|
|
38
|
+
for (const item of part.split(",")) {
|
|
39
|
+
const [range = "", stepText, extra] = item.split("/");
|
|
40
|
+
if (extra !== undefined || range === "")
|
|
41
|
+
throw fail();
|
|
42
|
+
if (stepText !== undefined && !/^\d+$/.test(stepText))
|
|
43
|
+
throw fail();
|
|
44
|
+
const step = stepText === undefined ? 1 : Number(stepText);
|
|
45
|
+
if (step < 1)
|
|
46
|
+
throw fail();
|
|
47
|
+
let from;
|
|
48
|
+
let to;
|
|
49
|
+
if (range === "*")
|
|
50
|
+
[from, to] = [field.min, field.max];
|
|
51
|
+
else {
|
|
52
|
+
const [a = "", b, more] = range.split("-");
|
|
53
|
+
if (more !== undefined)
|
|
54
|
+
throw fail();
|
|
55
|
+
// a step needs `*` or a range: `5/15` means different things in different crons
|
|
56
|
+
if (b === undefined && stepText !== undefined)
|
|
57
|
+
throw fail();
|
|
58
|
+
from = value(a);
|
|
59
|
+
to = b === undefined ? from : value(b);
|
|
60
|
+
if (from > to)
|
|
61
|
+
throw fail();
|
|
62
|
+
}
|
|
63
|
+
for (let n = from; n <= to; n += step)
|
|
64
|
+
values.add(n);
|
|
65
|
+
}
|
|
66
|
+
return values;
|
|
67
|
+
}
|
|
68
|
+
const formatters = new Map();
|
|
69
|
+
/** The wall clock in `timeZone`. Throws a RangeError for an unknown zone. */
|
|
70
|
+
function wallClock(date, timeZone) {
|
|
71
|
+
let format = formatters.get(timeZone);
|
|
72
|
+
if (!format) {
|
|
73
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
74
|
+
timeZone,
|
|
75
|
+
hourCycle: "h23",
|
|
76
|
+
month: "numeric",
|
|
77
|
+
day: "numeric",
|
|
78
|
+
hour: "numeric",
|
|
79
|
+
minute: "numeric",
|
|
80
|
+
weekday: "short",
|
|
81
|
+
});
|
|
82
|
+
formatters.set(timeZone, format);
|
|
83
|
+
}
|
|
84
|
+
const parts = {};
|
|
85
|
+
for (const { type, value } of format.formatToParts(date))
|
|
86
|
+
parts[type] = value;
|
|
87
|
+
return {
|
|
88
|
+
minute: Number(parts.minute),
|
|
89
|
+
hour: Number(parts.hour),
|
|
90
|
+
day: Number(parts.day),
|
|
91
|
+
month: Number(parts.month),
|
|
92
|
+
weekday: WEEKDAYS.indexOf((parts.weekday ?? "").toLowerCase()),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Is `date`'s minute due in `timeZone`? Wall-clock matching, like Laravel: a time skipped when clocks go forward doesn't
|
|
97
|
+
* run, and one that happens twice when they go back runs twice.
|
|
98
|
+
*/
|
|
99
|
+
export function isDue(schedule, date, timeZone = "UTC") {
|
|
100
|
+
const t = wallClock(date, timeZone);
|
|
101
|
+
const day = schedule.day.has(t.day);
|
|
102
|
+
const weekday = schedule.weekday.has(t.weekday);
|
|
103
|
+
const dayOk = schedule.dayRestricted && schedule.weekdayRestricted ? day || weekday : day && weekday;
|
|
104
|
+
return dayOk && schedule.minute.has(t.minute) && schedule.hour.has(t.hour) && schedule.month.has(t.month);
|
|
105
|
+
}
|
|
106
|
+
/** Checks a time zone name, so a typo fails at startup, not on the first tick. */
|
|
107
|
+
export function assertTimeZone(timeZone) {
|
|
108
|
+
wallClock(new Date(0), timeZone);
|
|
109
|
+
}
|
package/dist/sqlite.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { JobsAdapter, SqlDatabase } from "./index.ts";
|
|
3
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
4
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n last_error text,\n failed_at integer,\n replace_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\n";
|
|
6
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
7
|
+
export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
|
|
8
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
9
|
+
export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
package/dist/sqlite.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// The jobs table on SQLite (3.42 or later, for `unixepoch('subsec')`), in SQL. With Drizzle, import from
|
|
2
|
+
// `logic-sdk/drizzle/sqlite` instead: the same two functions, plus the table for your schema. Times are whole milliseconds since 1970, on SQLite's clock.
|
|
3
|
+
// Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
|
|
4
|
+
import { storedJobs } from "./stored-jobs.js";
|
|
5
|
+
const now = `cast(unixepoch('subsec') * 1000 as integer)`;
|
|
6
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
7
|
+
export const jobsSchema = `
|
|
8
|
+
CREATE TABLE logic_jobs (
|
|
9
|
+
id text PRIMARY KEY NOT NULL,
|
|
10
|
+
job text NOT NULL,
|
|
11
|
+
status text NOT NULL DEFAULT 'pending',
|
|
12
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
13
|
+
available_at integer NOT NULL DEFAULT (${now}),
|
|
14
|
+
receipt text,
|
|
15
|
+
last_error text,
|
|
16
|
+
failed_at integer,
|
|
17
|
+
replace_key text,
|
|
18
|
+
created_at integer NOT NULL DEFAULT (${now})
|
|
19
|
+
);
|
|
20
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
21
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
22
|
+
CREATE TABLE logic_cron_runs (
|
|
23
|
+
id text PRIMARY KEY NOT NULL,
|
|
24
|
+
ran_at integer NOT NULL DEFAULT (${now})
|
|
25
|
+
);
|
|
26
|
+
`;
|
|
27
|
+
const ids = "(SELECT value FROM json_each(?))";
|
|
28
|
+
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
29
|
+
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
30
|
+
const statements = {
|
|
31
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
|
|
32
|
+
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
|
|
33
|
+
insert: `
|
|
34
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
35
|
+
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
|
|
36
|
+
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
37
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
38
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
39
|
+
RETURNING id`,
|
|
40
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
41
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
42
|
+
claimNew: `
|
|
43
|
+
UPDATE logic_jobs SET attempts = 1, receipt = ?, available_at = ${inSeconds}
|
|
44
|
+
WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
45
|
+
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
46
|
+
claimDue: `
|
|
47
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, available_at = ${inSeconds}
|
|
48
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
|
|
49
|
+
RETURNING job, attempts`,
|
|
50
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
51
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ? WHERE ${mine} RETURNING id`,
|
|
52
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now} WHERE ${mine} RETURNING id`,
|
|
53
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
54
|
+
retry: `
|
|
55
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
56
|
+
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
57
|
+
fail: `
|
|
58
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|
|
59
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
|
|
60
|
+
RETURNING id`,
|
|
61
|
+
};
|
|
62
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
63
|
+
export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
|
|
64
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
65
|
+
export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type JobsAdapter, type Runner, type SqlDatabase, type SweepResult } from "./index.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
|
|
4
|
+
* lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
|
|
5
|
+
* the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
|
|
6
|
+
*/
|
|
7
|
+
export interface JobsSql {
|
|
8
|
+
/** `(pickup, rows)`: rows is JSON `[{ id, job, at, key }]`, `at` in epoch ms or null (due now, a sweep's after `pickup` seconds). A waiting row with the same `key` becomes the new one. */
|
|
9
|
+
insert: string;
|
|
10
|
+
/** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
|
|
11
|
+
recordTicks: string;
|
|
12
|
+
/** `()`: forgets ticks older than a day. */
|
|
13
|
+
pruneTicks: string;
|
|
14
|
+
/** `(receipt, lease, ids)`: the first claim, of rows nobody claimed. Returns `id`. */
|
|
15
|
+
claimNew: string;
|
|
16
|
+
/** `(receipt, lease)`: claims the one row due first. Returns `job` (JSON text) and `attempts`. */
|
|
17
|
+
claimDue: string;
|
|
18
|
+
/** `(lease, ids, receipt)`, on rows this receipt still owns, like the three below. */
|
|
19
|
+
extend: string;
|
|
20
|
+
/** `(seconds, error, ids, receipt)` */
|
|
21
|
+
backOff: string;
|
|
22
|
+
/** `(error, ids, receipt)` */
|
|
23
|
+
markFailed: string;
|
|
24
|
+
/** `(ids, receipt)` */
|
|
25
|
+
remove: string;
|
|
26
|
+
/** `(id)`: a failed row back in line. Returns `id`. */
|
|
27
|
+
retry: string;
|
|
28
|
+
/** `(id, job, error)`: a failed row, new or over the one there. */
|
|
29
|
+
fail: string;
|
|
30
|
+
}
|
|
31
|
+
export interface DatabaseQueueOptions {
|
|
32
|
+
/**
|
|
33
|
+
* Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
|
|
34
|
+
* job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
|
|
35
|
+
* longer than that.
|
|
36
|
+
*/
|
|
37
|
+
lease?: number;
|
|
38
|
+
/** Seconds to wait after a failed try. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
|
|
39
|
+
backoff?: (attempt: number) => number;
|
|
40
|
+
}
|
|
41
|
+
export interface OutboxOptions {
|
|
42
|
+
/** Seconds a send owns its jobs: how soon one that crashed is sent again. Default 300. */
|
|
43
|
+
lease?: number;
|
|
44
|
+
/** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
|
|
45
|
+
backoff?: (attempt: number) => number;
|
|
46
|
+
/**
|
|
47
|
+
* Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
|
|
48
|
+
* are its `attempts`.
|
|
49
|
+
*/
|
|
50
|
+
maxAttempts?: number;
|
|
51
|
+
}
|
|
52
|
+
/** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
|
|
53
|
+
export interface StoredJobs extends JobsAdapter {
|
|
54
|
+
/** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
|
|
55
|
+
sweep(runner: Runner, options?: {
|
|
56
|
+
limit?: number;
|
|
57
|
+
}): Promise<SweepResult>;
|
|
58
|
+
/** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
|
|
59
|
+
retry(id: string): Promise<boolean>;
|
|
60
|
+
}
|
|
61
|
+
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
|
|
62
|
+
/** Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. */
|
|
63
|
+
export declare const defaultBackoff: (attempt: number) => number;
|
|
64
|
+
export declare function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxOptions, via?: JobsAdapter): StoredJobs;
|