logic-sdk 0.7.1 → 0.7.2
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 +7 -7
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- 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 +17 -0
- package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
- package/dist/{jobs.js → core/jobs.js} +152 -39
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +203 -40
- 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 +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -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/pg-boss.d.ts +2 -53
- package/dist/pg-boss.js +2 -213
- 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 -2
- package/skills/logic-sdk/SKILL.md +4 -3
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +152 -38
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +197 -40
- 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 +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +15 -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/pg-boss.ts +2 -241
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- /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,234 @@
|
|
|
1
|
+
import { sql, type SQL } from "drizzle-orm";
|
|
2
|
+
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
|
|
4
|
+
import { causes } from "../core/errors.ts";
|
|
5
|
+
|
|
6
|
+
/** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
|
|
7
|
+
interface SyncSqlite {
|
|
8
|
+
all<T>(query: SQL): T[];
|
|
9
|
+
run(query: SQL): unknown;
|
|
10
|
+
$client: { close(): unknown };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What mutations get: a connection of their own, inside the transaction the adapter opened. */
|
|
14
|
+
export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
|
|
15
|
+
|
|
16
|
+
/** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
|
|
17
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
|
|
18
|
+
|
|
19
|
+
/** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
|
|
20
|
+
export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
21
|
+
|
|
22
|
+
/** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
|
|
23
|
+
const BUSY_TIMEOUT = 5000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
27
|
+
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
28
|
+
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
29
|
+
*
|
|
30
|
+
* ```ts
|
|
31
|
+
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export function drizzleAdapter<Db extends SyncSqlite>(
|
|
35
|
+
open: () => Db,
|
|
36
|
+
): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>> {
|
|
37
|
+
const reader = open();
|
|
38
|
+
checkOpen(open, reader);
|
|
39
|
+
exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
|
|
40
|
+
exec(reader, "PRAGMA query_only = ON");
|
|
41
|
+
|
|
42
|
+
const takeTurn = turns();
|
|
43
|
+
const transaction = <T>(fn: (tx: DrizzleTx<Db>) => Promise<T>) =>
|
|
44
|
+
takeTurn(async (restartClock) => {
|
|
45
|
+
const tx = await begin(open, restartClock);
|
|
46
|
+
try {
|
|
47
|
+
const out = await fn(tx);
|
|
48
|
+
exec(tx, "COMMIT");
|
|
49
|
+
return out;
|
|
50
|
+
} catch (e) {
|
|
51
|
+
undo(tx, "ROLLBACK");
|
|
52
|
+
throw e;
|
|
53
|
+
} finally {
|
|
54
|
+
tx.$client.close();
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
db: reader,
|
|
60
|
+
transaction,
|
|
61
|
+
nest: (tx) => savepoints(tx),
|
|
62
|
+
retryable: isBusy,
|
|
63
|
+
// on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
|
|
64
|
+
query: async (client: Pick<SyncSqlite, "all">, text, params) =>
|
|
65
|
+
client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Transactions inside a transaction, as savepoints: the test registry's. */
|
|
70
|
+
function savepoints<Tx extends Pick<SyncSqlite, "all" | "run">>(tx: Tx): SqlDatabase<Tx, Tx> {
|
|
71
|
+
const takeTurn = turns();
|
|
72
|
+
return {
|
|
73
|
+
db: tx,
|
|
74
|
+
transaction: (fn) =>
|
|
75
|
+
takeTurn(async () => {
|
|
76
|
+
exec(tx, "SAVEPOINT logic_sdk");
|
|
77
|
+
try {
|
|
78
|
+
const out = await fn(tx);
|
|
79
|
+
exec(tx, "RELEASE logic_sdk");
|
|
80
|
+
return out;
|
|
81
|
+
} catch (e) {
|
|
82
|
+
undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
|
|
83
|
+
throw e;
|
|
84
|
+
}
|
|
85
|
+
}),
|
|
86
|
+
nest: savepoints,
|
|
87
|
+
query: async (client, text, params) => rowsOf(client, text, params),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const exec = (db: Pick<SyncSqlite, "run">, text: string) => db.run(sql.raw(text));
|
|
92
|
+
|
|
93
|
+
/** SQL text with `?` parameters as a Drizzle query. */
|
|
94
|
+
const toSql = (text: string, params: unknown[]) =>
|
|
95
|
+
sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
|
|
96
|
+
|
|
97
|
+
const rowsOf = (db: Pick<SyncSqlite, "all">, text: string, params: unknown[]) =>
|
|
98
|
+
db.all<Record<string, unknown>>(toSql(text, params));
|
|
99
|
+
|
|
100
|
+
/** SQLite rolls some failures back by itself (a full disk, `RAISE(ROLLBACK)`): then there's nothing to undo, and the error that did it is the one to report. */
|
|
101
|
+
function undo(db: Pick<SyncSqlite, "run">, ...statements: string[]) {
|
|
102
|
+
try {
|
|
103
|
+
for (const statement of statements) exec(db, statement);
|
|
104
|
+
} catch {}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
|
|
108
|
+
function checkOpen<Db extends SyncSqlite>(open: () => Db, reader: Db) {
|
|
109
|
+
const another = open();
|
|
110
|
+
if (another.$client === reader.$client)
|
|
111
|
+
throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
|
|
112
|
+
const [main] = another.all<{ file: string }>(sql`PRAGMA database_list`);
|
|
113
|
+
another.$client.close();
|
|
114
|
+
if (!main?.file)
|
|
115
|
+
throw new Error("[logic-sdk] drizzleAdapter needs SQLite on a disk: an in-memory database is a different one on each connection. Use a temporary file in tests.");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
|
|
120
|
+
* since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
|
|
121
|
+
*/
|
|
122
|
+
async function begin<Db extends SyncSqlite>(open: () => Db, restartClock: () => void): Promise<Db> {
|
|
123
|
+
const deadline = Date.now() + BUSY_TIMEOUT;
|
|
124
|
+
for (;;) {
|
|
125
|
+
restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
|
|
126
|
+
let tx: Db | undefined;
|
|
127
|
+
try {
|
|
128
|
+
tx = open();
|
|
129
|
+
exec(tx, "PRAGMA busy_timeout = 0");
|
|
130
|
+
exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
|
|
131
|
+
exec(tx, "BEGIN IMMEDIATE");
|
|
132
|
+
return tx;
|
|
133
|
+
} catch (e) {
|
|
134
|
+
tx?.$client.close();
|
|
135
|
+
if (!isBusy(e) || Date.now() >= deadline) throw e;
|
|
136
|
+
}
|
|
137
|
+
await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
|
|
143
|
+
* when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
|
|
144
|
+
*/
|
|
145
|
+
function turns() {
|
|
146
|
+
let last = Promise.resolve();
|
|
147
|
+
let startedAt = 0;
|
|
148
|
+
const restartClock = () => {
|
|
149
|
+
startedAt = Date.now();
|
|
150
|
+
};
|
|
151
|
+
return async <T>(work: (restartClock: () => void) => Promise<T>): Promise<T> => {
|
|
152
|
+
const arrived = Date.now();
|
|
153
|
+
const ahead = last;
|
|
154
|
+
const done = Promise.withResolvers<void>();
|
|
155
|
+
last = ahead.then(() => done.promise);
|
|
156
|
+
try {
|
|
157
|
+
const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
|
|
158
|
+
while (!(await settlesBy(ahead, giveUpAt()))) {
|
|
159
|
+
// the one ahead may have changed while we waited: the line moved
|
|
160
|
+
if (Date.now() >= giveUpAt()) throw new Error(HELD);
|
|
161
|
+
}
|
|
162
|
+
restartClock();
|
|
163
|
+
return await work(restartClock);
|
|
164
|
+
} finally {
|
|
165
|
+
done.resolve();
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const HELD =
|
|
171
|
+
"[logic-sdk] Waited 5 seconds for a transaction in this process, and SQLite writes one at a time. Does a mutation await registry.as(scope).run instead of ctx.run, or do slow work that belongs in an action? In tests, is a t.begin() still open?";
|
|
172
|
+
|
|
173
|
+
/** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
|
|
174
|
+
const settlesBy = (promise: Promise<void>, time: number) =>
|
|
175
|
+
new Promise<boolean>((resolve) => {
|
|
176
|
+
const timer = setTimeout(() => resolve(false), time - Date.now());
|
|
177
|
+
void promise.then(() => {
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
resolve(true);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
/** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
|
|
184
|
+
function isBusy(error: unknown): boolean {
|
|
185
|
+
for (const e of causes(error))
|
|
186
|
+
if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message))) return true;
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const now = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
194
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
195
|
+
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
196
|
+
*/
|
|
197
|
+
export const jobsTable = sqliteTable(
|
|
198
|
+
"logic_jobs",
|
|
199
|
+
{
|
|
200
|
+
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
201
|
+
id: text("id").primaryKey(),
|
|
202
|
+
job: text("job", { mode: "json" }).$type<Job>().notNull(),
|
|
203
|
+
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
204
|
+
status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
|
|
205
|
+
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
206
|
+
attempts: integer("attempts").notNull().default(0),
|
|
207
|
+
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
208
|
+
availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
209
|
+
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
210
|
+
receipt: text("receipt"),
|
|
211
|
+
/** When the claim that owns it started: set while a try runs, empty while it waits (first, or after a backoff). */
|
|
212
|
+
claimedAt: integer("claimed_at", { mode: "timestamp_ms" }),
|
|
213
|
+
/** The last failure, with its stack. */
|
|
214
|
+
lastError: text("last_error"),
|
|
215
|
+
failedAt: integer("failed_at", { mode: "timestamp_ms" }),
|
|
216
|
+
/** A scheduled call's `replace` key, `<function id>@<sha-256 of its input>`: a newer call with it replaces this row while it waits. */
|
|
217
|
+
replaceKey: text("replace_key"),
|
|
218
|
+
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
219
|
+
},
|
|
220
|
+
(t) => [
|
|
221
|
+
index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
|
|
222
|
+
// one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
223
|
+
uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
|
|
224
|
+
// `registry.jobs.failed()` pages newest first by (failed_at, id)
|
|
225
|
+
index("logic_jobs_failed").on(t.failedAt, t.id).where(sql`status = 'failed'`),
|
|
226
|
+
],
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
230
|
+
export const cronRunsTable = sqliteTable("logic_cron_runs", {
|
|
231
|
+
/** The cron job's id, `<cron id>@<minute>`. */
|
|
232
|
+
id: text("id").primaryKey(),
|
|
233
|
+
ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
234
|
+
}, (t) => [index("logic_cron_runs_ran_at").on(t.ranAt)]);
|
|
@@ -0,0 +1,195 @@
|
|
|
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 { type Db, type JobInsert, type PgBoss, type Queue, type WorkOptions } from "pg-boss";
|
|
5
|
+
import { storedReplaceKey } from "../core/jobs.ts";
|
|
6
|
+
import type { ForListeners, SqlDatabase, Job, JobsAdapter } from "../core/types.ts";
|
|
7
|
+
|
|
8
|
+
/** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
|
|
9
|
+
export interface PgBossTuning {
|
|
10
|
+
/** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
|
|
11
|
+
queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
|
|
12
|
+
/** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
|
|
13
|
+
worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
18
|
+
* `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
|
|
19
|
+
* listener's `attempts`, and the other adapters ignore it.
|
|
20
|
+
*/
|
|
21
|
+
export type PgBossMeta = ForListeners<{ pgBoss?: PgBossTuning }>;
|
|
22
|
+
|
|
23
|
+
/** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
|
|
24
|
+
export const PREFIX = "logic-sdk.";
|
|
25
|
+
/** A listener's or cron's queue: `logic-sdk.notifications.send`. */
|
|
26
|
+
export const queueName = (id: string) => `${PREFIX}${id}`;
|
|
27
|
+
/** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
|
|
28
|
+
export const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
|
|
29
|
+
|
|
30
|
+
/** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
|
|
31
|
+
const queueOf = (job: Job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
|
|
32
|
+
|
|
33
|
+
/** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
|
|
34
|
+
export const queueConfig = (queue: PgBossTuning["queue"]) => ({ ...queue, retryBackoff: true });
|
|
35
|
+
|
|
36
|
+
/** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
|
|
37
|
+
export const tuningOf = (meta: Readonly<Record<string, unknown>> | undefined) => meta?.pgBoss as PgBossTuning | undefined;
|
|
38
|
+
|
|
39
|
+
// A UUID of our own, so the v5 ids below can't collide with anyone else's.
|
|
40
|
+
const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 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
|
|
44
|
+
* minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
|
|
45
|
+
*/
|
|
46
|
+
export function pgBossId(id: string): string {
|
|
47
|
+
const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
|
|
48
|
+
hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
|
|
49
|
+
hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
|
|
50
|
+
const hex = hash.toString("hex", 0, 16);
|
|
51
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
|
|
56
|
+
* never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
|
|
57
|
+
* left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
|
|
58
|
+
* at pickup. A last try that throws is `deadletter`, so it never uses the spare.
|
|
59
|
+
*/
|
|
60
|
+
const rowOf = (job: Job, replaceKey?: string): JobInsert<Job> => ({
|
|
61
|
+
id: pgBossId(job.id),
|
|
62
|
+
data: job,
|
|
63
|
+
startAfter: job.runAt,
|
|
64
|
+
retryLimit: job.attempts,
|
|
65
|
+
retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
|
|
66
|
+
singletonKey: replaceKey,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
export function pgBoss(boss: PgBoss): JobsAdapter {
|
|
70
|
+
let database: SqlDatabase | undefined;
|
|
71
|
+
/** pg-boss's SQL on your mutation's transaction, through your database adapter's `query`: any ORM that runs SQL. */
|
|
72
|
+
const inTx = (tx: unknown): Db => ({
|
|
73
|
+
executeSql: async (text, values = []) => {
|
|
74
|
+
const rows = await database!.query(tx, text, values);
|
|
75
|
+
return { rows };
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
const queueOptions = new Map<string, PgBossTuning["queue"]>();
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
|
|
82
|
+
* new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
|
|
83
|
+
* on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
|
|
84
|
+
*/
|
|
85
|
+
async function inQueue(name: string, write: () => Promise<unknown>) {
|
|
86
|
+
try {
|
|
87
|
+
await write();
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND")) throw error;
|
|
90
|
+
await boss.createQueue(name, queueConfig(queueOptions.get(name)));
|
|
91
|
+
await write();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
|
|
97
|
+
* a job in `retry` has started, and isn't touched.
|
|
98
|
+
*/
|
|
99
|
+
async function replaceWaiting(db: Db, keys: string[]) {
|
|
100
|
+
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
101
|
+
for (const key of [...new Set(keys)].sort()) {
|
|
102
|
+
// one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
|
|
103
|
+
await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
|
|
104
|
+
// a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
|
|
105
|
+
const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
|
|
106
|
+
if (!locked.length) continue;
|
|
107
|
+
const queued = await boss.findJobs<Job>(CALLS_QUEUE, { key, queued: true, db });
|
|
108
|
+
const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
|
|
109
|
+
if (waiting.length) await boss.deleteJob(CALLS_QUEUE, waiting, { db });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
name: "pgBoss(boss)",
|
|
115
|
+
retries: true, // retryLimit, stamped from the job's attempts
|
|
116
|
+
sql: true, // pg-boss inserts its jobs with your database adapter's `query`, in your transaction
|
|
117
|
+
holds: true, // `startAfter`, however far ahead
|
|
118
|
+
replaces: true,
|
|
119
|
+
/** Takes the registry's database: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
120
|
+
connect({ listeners, crons, sql }) {
|
|
121
|
+
database = sql;
|
|
122
|
+
for (const l of listeners) queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
123
|
+
for (const c of crons) queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
|
|
124
|
+
},
|
|
125
|
+
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
126
|
+
async enqueue(tx, jobs) {
|
|
127
|
+
const db = inTx(tx);
|
|
128
|
+
for (const [name, list] of Map.groupBy(jobs, queueOf)) {
|
|
129
|
+
const keyed = await Promise.all(list.map(async (job) => ({ job, key: await storedReplaceKey(job) })));
|
|
130
|
+
const keys = keyed.map(({ key }) => key).filter((key) => key !== undefined);
|
|
131
|
+
await inQueue(name, async () => {
|
|
132
|
+
if (keys.length) await replaceWaiting(db, keys);
|
|
133
|
+
await boss.insert(name, keyed.map(({ job, key }) => rowOf(job, key)), { db });
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
/** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
|
|
138
|
+
async deliver() {},
|
|
139
|
+
/**
|
|
140
|
+
* A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
|
|
141
|
+
* it has run, so it's no longer a call a newer one replaces.
|
|
142
|
+
*/
|
|
143
|
+
async retry(id) {
|
|
144
|
+
const queues = await queuesOf(id);
|
|
145
|
+
if (!database || !queues.length) return false;
|
|
146
|
+
const uuid = pgBossId(id);
|
|
147
|
+
return database.transaction(async (tx) => {
|
|
148
|
+
const db = inTx(tx);
|
|
149
|
+
for (const { name } of queues) {
|
|
150
|
+
// failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
|
|
151
|
+
const { affected } = await boss.retry(name, uuid, { db });
|
|
152
|
+
if (!affected) continue;
|
|
153
|
+
const [failed] = await boss.findJobs<Job>(name, { id: uuid, db });
|
|
154
|
+
if (!failed) continue;
|
|
155
|
+
// as new: retry count 0, and its retries again
|
|
156
|
+
await boss.deleteJob(name, uuid, { db });
|
|
157
|
+
await boss.insert(name, [rowOf(failed.data)], { db });
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
return false;
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
/** pg-boss keeps failed jobs in its own tables, one queue at a time, with no state filter: list them there. */
|
|
164
|
+
async failed() {
|
|
165
|
+
throw new Error("[logic-sdk] pgBoss(boss) can't list failed jobs across queues: use boss.findJobs(queue) for one, and pgBossId(id) to match ids.");
|
|
166
|
+
},
|
|
167
|
+
/** A failed job, deleted. A waiting, running or retrying one is left alone. */
|
|
168
|
+
async forget(id) {
|
|
169
|
+
const queues = await queuesOf(id);
|
|
170
|
+
if (!database || !queues.length) return false;
|
|
171
|
+
const uuid = pgBossId(id);
|
|
172
|
+
return database.transaction(async (tx) => {
|
|
173
|
+
const db = inTx(tx);
|
|
174
|
+
for (const { name } of queues) {
|
|
175
|
+
const [found] = await boss.findJobs<Job>(name, { id: uuid, db });
|
|
176
|
+
if (found?.state !== "failed") continue;
|
|
177
|
+
await boss.deleteJob(name, uuid, { db });
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* A job id's queues: its listener's or cron's (the id's prefix), and the calls queue. Looked up before any
|
|
187
|
+
* transaction: inside one, a lookup on pg-boss's own connection would wait for it on PGlite.
|
|
188
|
+
*/
|
|
189
|
+
async function queuesOf(id: string) {
|
|
190
|
+
const at = id.lastIndexOf("@");
|
|
191
|
+
if (at < 0) return []; // not a job id
|
|
192
|
+
const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
|
|
193
|
+
return boss.getQueues(names);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
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 { failedStore, storedJobs, type DatabaseQueueOptions, type JobsSql, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
4
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
5
|
+
|
|
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,
|
|
10
|
+
job jsonb NOT NULL,
|
|
11
|
+
status text NOT NULL DEFAULT 'pending',
|
|
12
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
13
|
+
available_at timestamptz NOT NULL DEFAULT now(),
|
|
14
|
+
receipt text,
|
|
15
|
+
claimed_at timestamptz,
|
|
16
|
+
last_error text,
|
|
17
|
+
failed_at timestamptz,
|
|
18
|
+
replace_key text,
|
|
19
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
22
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
23
|
+
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
24
|
+
CREATE TABLE logic_cron_runs (
|
|
25
|
+
id text PRIMARY KEY,
|
|
26
|
+
ran_at timestamptz NOT NULL DEFAULT now()
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
32
|
+
const ids = (n: number) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
|
|
33
|
+
const mine = (n: number) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
34
|
+
const inSeconds = (n: number) => `now() + make_interval(secs => $${n}::float8)`;
|
|
35
|
+
|
|
36
|
+
const statements: JobsSql = {
|
|
37
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
|
|
38
|
+
insert: `
|
|
39
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
40
|
+
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
|
|
41
|
+
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
42
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
43
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
|
|
44
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
45
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
46
|
+
claimNew: `
|
|
47
|
+
UPDATE logic_jobs SET attempts = 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
48
|
+
WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
49
|
+
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
50
|
+
claimDue: `
|
|
51
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
52
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
53
|
+
RETURNING job::text AS job, attempts`,
|
|
54
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
55
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2, claimed_at = NULL WHERE ${mine(3)}`,
|
|
56
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now(), claimed_at = NULL WHERE ${mine(2)}`,
|
|
57
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
58
|
+
// 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
|
|
59
|
+
// a call a newer one replaces (and one may be waiting with it)
|
|
60
|
+
retry: `
|
|
61
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
62
|
+
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
63
|
+
fail: `
|
|
64
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
65
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
66
|
+
// field by field, as SQLite matches, so both databases agree; `failed_at` back as text to the microsecond, for the cursor
|
|
67
|
+
failed: `
|
|
68
|
+
WITH p AS (SELECT NULLIF($1, '') AS source, NULLIF($2, '') AS want, NULLIF($3, '')::timestamptz AS at, NULLIF($4, '') AS after_id)
|
|
69
|
+
SELECT j.id, j.job::text AS job, j.last_error, to_char(j.failed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS failed_at
|
|
70
|
+
FROM logic_jobs j, p
|
|
71
|
+
WHERE j.status = 'failed'
|
|
72
|
+
AND (p.source IS NULL OR coalesce(j.job ->> 'listener', j.job ->> 'cron', j.job ->> 'fn') = p.source)
|
|
73
|
+
AND (p.want IS NULL OR NOT EXISTS (
|
|
74
|
+
SELECT 1 FROM jsonb_array_elements(p.want::jsonb) AS w(m)
|
|
75
|
+
WHERE (coalesce(j.job -> 'scope', j.job #> '{envelope,scope}') #> ARRAY(SELECT jsonb_array_elements_text(w.m -> 'path'))) IS DISTINCT FROM (w.m -> 'value')))
|
|
76
|
+
AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
|
|
77
|
+
ORDER BY j.failed_at DESC, j.id DESC
|
|
78
|
+
LIMIT $5::int`,
|
|
79
|
+
forget: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
80
|
+
take: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING job::text AS job`,
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
85
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
86
|
+
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
87
|
+
* its row being deleted runs it again.
|
|
88
|
+
*
|
|
89
|
+
* ```ts
|
|
90
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
91
|
+
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
export const databaseQueue = (options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, options);
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
98
|
+
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
99
|
+
* 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,
|
|
100
|
+
* so a job can run twice, even at once.
|
|
101
|
+
*
|
|
102
|
+
* ```ts
|
|
103
|
+
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
export const outbox = (queue: JobsAdapter, options: OutboxOptions = {}): StoredJobs => storedJobs(statements, options, queue);
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
110
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
111
|
+
*/
|
|
112
|
+
export const failedJobs = (): FailedJobs => failedStore(statements);
|
|
@@ -0,0 +1,96 @@
|
|
|
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 { failedStore, storedJobs, type DatabaseQueueOptions, type JobsSql, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
5
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
6
|
+
|
|
7
|
+
const now = `cast(unixepoch('subsec') * 1000 as integer)`;
|
|
8
|
+
|
|
9
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
10
|
+
export const jobsSchema = `
|
|
11
|
+
CREATE TABLE logic_jobs (
|
|
12
|
+
id text PRIMARY KEY NOT NULL,
|
|
13
|
+
job text NOT NULL,
|
|
14
|
+
status text NOT NULL DEFAULT 'pending',
|
|
15
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
16
|
+
available_at integer NOT NULL DEFAULT (${now}),
|
|
17
|
+
receipt text,
|
|
18
|
+
claimed_at integer,
|
|
19
|
+
last_error text,
|
|
20
|
+
failed_at integer,
|
|
21
|
+
replace_key text,
|
|
22
|
+
created_at integer NOT NULL DEFAULT (${now})
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
25
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
26
|
+
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
27
|
+
CREATE TABLE logic_cron_runs (
|
|
28
|
+
id text PRIMARY KEY NOT NULL,
|
|
29
|
+
ran_at integer NOT NULL DEFAULT (${now})
|
|
30
|
+
);
|
|
31
|
+
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
const ids = "(SELECT value FROM json_each(?))";
|
|
35
|
+
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
36
|
+
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
37
|
+
|
|
38
|
+
const statements: JobsSql = {
|
|
39
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
|
|
40
|
+
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
|
|
41
|
+
insert: `
|
|
42
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
43
|
+
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
|
|
44
|
+
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
45
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
46
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
47
|
+
RETURNING id`,
|
|
48
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
49
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
50
|
+
claimNew: `
|
|
51
|
+
UPDATE logic_jobs SET attempts = 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
52
|
+
WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
53
|
+
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
54
|
+
claimDue: `
|
|
55
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
56
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
|
|
57
|
+
RETURNING job, attempts`,
|
|
58
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
59
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ?, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
60
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now}, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
61
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
62
|
+
retry: `
|
|
63
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
64
|
+
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
65
|
+
fail: `
|
|
66
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|
|
67
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
|
|
68
|
+
RETURNING id`,
|
|
69
|
+
// each field by its type and value: a missing one isn't null, and true isn't 1
|
|
70
|
+
failed: `
|
|
71
|
+
WITH p(source, want, at, after_id) AS (SELECT NULLIF(?, ''), NULLIF(?, ''), CAST(NULLIF(?, '') AS INTEGER), NULLIF(?, ''))
|
|
72
|
+
SELECT j.id, j.job, j.last_error, j.failed_at FROM logic_jobs j, p
|
|
73
|
+
WHERE j.status = 'failed'
|
|
74
|
+
AND (p.source IS NULL OR coalesce(j.job ->> '$.listener', j.job ->> '$.cron', j.job ->> '$.fn') = p.source)
|
|
75
|
+
AND (p.want IS NULL OR NOT EXISTS (
|
|
76
|
+
SELECT 1 FROM json_each(p.want) AS w
|
|
77
|
+
WHERE json_type(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_type(w.value, '$.value')
|
|
78
|
+
OR json_extract(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_extract(w.value, '$.value')))
|
|
79
|
+
AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
|
|
80
|
+
ORDER BY j.failed_at DESC, j.id DESC
|
|
81
|
+
LIMIT ?`,
|
|
82
|
+
forget: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
83
|
+
take: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING job`,
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
87
|
+
export const databaseQueue = (options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, options);
|
|
88
|
+
|
|
89
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
90
|
+
export const outbox = (queue: JobsAdapter, options: OutboxOptions = {}): StoredJobs => storedJobs(statements, options, queue);
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
94
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
95
|
+
*/
|
|
96
|
+
export const failedJobs = (): FailedJobs => failedStore(statements);
|