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
package/dist/adapters/pg-boss.js
DELETED
|
@@ -1,180 +0,0 @@
|
|
|
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 {} from "pg-boss";
|
|
5
|
-
import { storedReplaceKey } from "../core/jobs.js";
|
|
6
|
-
/** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
|
|
7
|
-
export const PREFIX = "logic-sdk.";
|
|
8
|
-
/** A listener's or cron's queue: `logic-sdk.notifications.send`. */
|
|
9
|
-
export const queueName = (id) => `${PREFIX}${id}`;
|
|
10
|
-
/** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
|
|
11
|
-
export const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
|
|
12
|
-
/** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
|
|
13
|
-
const queueOf = (job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
|
|
14
|
-
/** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
|
|
15
|
-
export const queueConfig = (queue) => ({ ...queue, retryBackoff: true });
|
|
16
|
-
/** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
|
|
17
|
-
export const tuningOf = (meta) => meta?.pgBoss;
|
|
18
|
-
// A UUID of our own, so the v5 ids below can't collide with anyone else's.
|
|
19
|
-
const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
|
|
20
|
-
/**
|
|
21
|
-
* 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
|
|
22
|
-
* minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
|
|
23
|
-
*/
|
|
24
|
-
export function pgBossId(id) {
|
|
25
|
-
const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
|
|
26
|
-
hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
|
|
27
|
-
hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
|
|
28
|
-
const hex = hash.toString("hex", 0, 16);
|
|
29
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
|
|
33
|
-
* never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
|
|
34
|
-
* left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
|
|
35
|
-
* at pickup. A last try that throws is `deadletter`, so it never uses the spare.
|
|
36
|
-
*/
|
|
37
|
-
const rowOf = (job, replaceKey) => ({
|
|
38
|
-
id: pgBossId(job.id),
|
|
39
|
-
data: job,
|
|
40
|
-
startAfter: job.runAt,
|
|
41
|
-
retryLimit: job.attempts,
|
|
42
|
-
retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
|
|
43
|
-
singletonKey: replaceKey,
|
|
44
|
-
});
|
|
45
|
-
export function pgBoss(boss) {
|
|
46
|
-
let database;
|
|
47
|
-
/** pg-boss's SQL on your mutation's transaction, through your database adapter's `query`: any ORM that runs SQL. */
|
|
48
|
-
const inTx = (tx) => ({
|
|
49
|
-
executeSql: async (text, values = []) => {
|
|
50
|
-
const rows = await database.query(tx, text, values);
|
|
51
|
-
return { rows };
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
const queueOptions = new Map();
|
|
55
|
-
/**
|
|
56
|
-
* pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
|
|
57
|
-
* new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
|
|
58
|
-
* on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
|
|
59
|
-
*/
|
|
60
|
-
async function inQueue(name, write) {
|
|
61
|
-
try {
|
|
62
|
-
await write();
|
|
63
|
-
}
|
|
64
|
-
catch (error) {
|
|
65
|
-
if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND"))
|
|
66
|
-
throw error;
|
|
67
|
-
await boss.createQueue(name, queueConfig(queueOptions.get(name)));
|
|
68
|
-
await write();
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
|
|
73
|
-
* a job in `retry` has started, and isn't touched.
|
|
74
|
-
*/
|
|
75
|
-
async function replaceWaiting(db, keys) {
|
|
76
|
-
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
77
|
-
for (const key of [...new Set(keys)].sort()) {
|
|
78
|
-
// one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
|
|
79
|
-
await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
|
|
80
|
-
// a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
|
|
81
|
-
const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
|
|
82
|
-
if (!locked.length)
|
|
83
|
-
continue;
|
|
84
|
-
const queued = await boss.findJobs(CALLS_QUEUE, { key, queued: true, db });
|
|
85
|
-
const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
|
|
86
|
-
if (waiting.length)
|
|
87
|
-
await boss.deleteJob(CALLS_QUEUE, waiting, { db });
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
return {
|
|
91
|
-
name: "pgBoss(boss)",
|
|
92
|
-
retries: true, // retryLimit, stamped from the job's attempts
|
|
93
|
-
sql: true, // pg-boss inserts its jobs with your database adapter's `query`, in your transaction
|
|
94
|
-
holds: true, // `startAfter`, however far ahead
|
|
95
|
-
replaces: true,
|
|
96
|
-
/** Takes the registry's database: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
97
|
-
connect({ listeners, crons, sql }) {
|
|
98
|
-
database = sql;
|
|
99
|
-
for (const l of listeners)
|
|
100
|
-
queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
101
|
-
for (const c of crons)
|
|
102
|
-
queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
|
|
103
|
-
},
|
|
104
|
-
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
105
|
-
async enqueue(tx, jobs) {
|
|
106
|
-
const db = inTx(tx);
|
|
107
|
-
for (const [name, list] of Map.groupBy(jobs, queueOf)) {
|
|
108
|
-
const keyed = await Promise.all(list.map(async (job) => ({ job, key: await storedReplaceKey(job) })));
|
|
109
|
-
const keys = keyed.map(({ key }) => key).filter((key) => key !== undefined);
|
|
110
|
-
await inQueue(name, async () => {
|
|
111
|
-
if (keys.length)
|
|
112
|
-
await replaceWaiting(db, keys);
|
|
113
|
-
await boss.insert(name, keyed.map(({ job, key }) => rowOf(job, key)), { db });
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
},
|
|
117
|
-
/** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
|
|
118
|
-
async deliver() { },
|
|
119
|
-
/**
|
|
120
|
-
* A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
|
|
121
|
-
* it has run, so it's no longer a call a newer one replaces.
|
|
122
|
-
*/
|
|
123
|
-
async retry(id) {
|
|
124
|
-
const queues = await queuesOf(id);
|
|
125
|
-
if (!database || !queues.length)
|
|
126
|
-
return false;
|
|
127
|
-
const uuid = pgBossId(id);
|
|
128
|
-
return database.transaction(async (tx) => {
|
|
129
|
-
const db = inTx(tx);
|
|
130
|
-
for (const { name } of queues) {
|
|
131
|
-
// failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
|
|
132
|
-
const { affected } = await boss.retry(name, uuid, { db });
|
|
133
|
-
if (!affected)
|
|
134
|
-
continue;
|
|
135
|
-
const [failed] = await boss.findJobs(name, { id: uuid, db });
|
|
136
|
-
if (!failed)
|
|
137
|
-
continue;
|
|
138
|
-
// as new: retry count 0, and its retries again
|
|
139
|
-
await boss.deleteJob(name, uuid, { db });
|
|
140
|
-
await boss.insert(name, [rowOf(failed.data)], { db });
|
|
141
|
-
return true;
|
|
142
|
-
}
|
|
143
|
-
return false;
|
|
144
|
-
});
|
|
145
|
-
},
|
|
146
|
-
/** pg-boss keeps failed jobs in its own tables, one queue at a time, with no state filter: list them there. */
|
|
147
|
-
async failed() {
|
|
148
|
-
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.");
|
|
149
|
-
},
|
|
150
|
-
/** A failed job, deleted. A waiting, running or retrying one is left alone. */
|
|
151
|
-
async forget(id) {
|
|
152
|
-
const queues = await queuesOf(id);
|
|
153
|
-
if (!database || !queues.length)
|
|
154
|
-
return false;
|
|
155
|
-
const uuid = pgBossId(id);
|
|
156
|
-
return database.transaction(async (tx) => {
|
|
157
|
-
const db = inTx(tx);
|
|
158
|
-
for (const { name } of queues) {
|
|
159
|
-
const [found] = await boss.findJobs(name, { id: uuid, db });
|
|
160
|
-
if (found?.state !== "failed")
|
|
161
|
-
continue;
|
|
162
|
-
await boss.deleteJob(name, uuid, { db });
|
|
163
|
-
return true;
|
|
164
|
-
}
|
|
165
|
-
return false;
|
|
166
|
-
});
|
|
167
|
-
},
|
|
168
|
-
};
|
|
169
|
-
/**
|
|
170
|
-
* A job id's queues: its listener's or cron's (the id's prefix), and the calls queue. Looked up before any
|
|
171
|
-
* transaction: inside one, a lookup on pg-boss's own connection would wait for it on PGlite.
|
|
172
|
-
*/
|
|
173
|
-
async function queuesOf(id) {
|
|
174
|
-
const at = id.lastIndexOf("@");
|
|
175
|
-
if (at < 0)
|
|
176
|
-
return []; // not a job id
|
|
177
|
-
const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
|
|
178
|
-
return boss.getQueues(names);
|
|
179
|
-
}
|
|
180
|
-
}
|
package/dist/hosts/pg-boss.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import type { PgBoss } from "pg-boss";
|
|
2
|
-
import { type PgBossTuning } from "../adapters/pg-boss.ts";
|
|
3
|
-
import type { Jobs, Registry } from "../core/types.ts";
|
|
4
|
-
export interface PgBossWorkOptions {
|
|
5
|
-
/** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
|
|
6
|
-
calls?: PgBossTuning;
|
|
7
|
-
/** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
|
|
8
|
-
onError?: (error: unknown) => void;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
12
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
13
|
-
*
|
|
14
|
-
* ```ts
|
|
15
|
-
* await boss.start();
|
|
16
|
-
* await work(registry, boss);
|
|
17
|
-
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
export declare function work(registry: Pick<Registry, "definitions"> & {
|
|
21
|
-
jobs: Pick<Jobs, "run" | "tick" | "sweep">;
|
|
22
|
-
}, boss: PgBoss, options?: PgBossWorkOptions): Promise<void>;
|
package/dist/hosts/pg-boss.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { CALLS_QUEUE, PREFIX, queueConfig, queueName, tuningOf } from "../adapters/pg-boss.js";
|
|
2
|
-
import { startTicking } from "./node.js";
|
|
3
|
-
/**
|
|
4
|
-
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
5
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
6
|
-
*
|
|
7
|
-
* ```ts
|
|
8
|
-
* await boss.start();
|
|
9
|
-
* await work(registry, boss);
|
|
10
|
-
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
11
|
-
* ```
|
|
12
|
-
*/
|
|
13
|
-
export async function work(registry, boss, options = {}) {
|
|
14
|
-
const { listeners, crons } = registry.definitions;
|
|
15
|
-
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
16
|
-
const queues = [
|
|
17
|
-
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
18
|
-
...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
|
|
19
|
-
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
20
|
-
];
|
|
21
|
-
/** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
|
|
22
|
-
const settle = async (job) => {
|
|
23
|
-
let reason;
|
|
24
|
-
const fail = async (error) => {
|
|
25
|
-
reason = error; // kept by pg-boss as the failed job's output
|
|
26
|
-
};
|
|
27
|
-
try {
|
|
28
|
-
const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
|
|
29
|
-
if (outcome === "failed")
|
|
30
|
-
return { id: job.id, status: "deadletter", output: reason };
|
|
31
|
-
return { id: job.id, status: "completed" };
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
for (const { name, tuning } of queues) {
|
|
38
|
-
const config = queueConfig(tuning?.queue);
|
|
39
|
-
const { partition: _createOnly, ...updatable } = config;
|
|
40
|
-
await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
|
|
41
|
-
await boss.updateQueue(name, updatable);
|
|
42
|
-
await boss.work(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
|
|
43
|
-
}
|
|
44
|
-
// a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
|
|
45
|
-
// They never get a try that could report, so say so here
|
|
46
|
-
const ours = new Set(queues.map((q) => q.name));
|
|
47
|
-
for (const q of await boss.getQueues())
|
|
48
|
-
if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
|
|
49
|
-
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.`));
|
|
50
|
-
if (!crons.length)
|
|
51
|
-
return;
|
|
52
|
-
// ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
|
|
53
|
-
const stop = startTicking(registry, { sweepEvery: 0, onError });
|
|
54
|
-
boss.once("stopped", () => void stop());
|
|
55
|
-
}
|
package/dist/pg-boss.d.ts
DELETED
package/dist/pg-boss.js
DELETED
package/src/adapters/pg-boss.ts
DELETED
|
@@ -1,195 +0,0 @@
|
|
|
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
|
-
}
|
package/src/hosts/pg-boss.ts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
// `work()`, the pg-boss worker: its queues and names are the adapter's (adapters/pg-boss.ts).
|
|
2
|
-
import type { JobResult, PgBoss } from "pg-boss";
|
|
3
|
-
import { CALLS_QUEUE, PREFIX, queueConfig, queueName, tuningOf, type PgBossTuning } from "../adapters/pg-boss.ts";
|
|
4
|
-
import type { Job, Jobs, Registry } from "../core/types.ts";
|
|
5
|
-
import { startTicking } from "./node.ts";
|
|
6
|
-
|
|
7
|
-
export interface PgBossWorkOptions {
|
|
8
|
-
/** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
|
|
9
|
-
calls?: PgBossTuning;
|
|
10
|
-
/** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
|
|
11
|
-
onError?: (error: unknown) => void;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
16
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
17
|
-
*
|
|
18
|
-
* ```ts
|
|
19
|
-
* await boss.start();
|
|
20
|
-
* await work(registry, boss);
|
|
21
|
-
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
export async function work(
|
|
25
|
-
registry: Pick<Registry, "definitions"> & { jobs: Pick<Jobs, "run" | "tick" | "sweep"> },
|
|
26
|
-
boss: PgBoss,
|
|
27
|
-
options: PgBossWorkOptions = {},
|
|
28
|
-
): Promise<void> {
|
|
29
|
-
const { listeners, crons } = registry.definitions;
|
|
30
|
-
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
31
|
-
const queues: { name: string; tuning: PgBossTuning | undefined }[] = [
|
|
32
|
-
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
33
|
-
...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
|
|
34
|
-
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
35
|
-
];
|
|
36
|
-
|
|
37
|
-
/** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
|
|
38
|
-
const settle = async (job: { id: string; data: Job; retryCount: number }): Promise<JobResult> => {
|
|
39
|
-
let reason: unknown;
|
|
40
|
-
const fail = async (error: unknown) => {
|
|
41
|
-
reason = error; // kept by pg-boss as the failed job's output
|
|
42
|
-
};
|
|
43
|
-
try {
|
|
44
|
-
const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
|
|
45
|
-
if (outcome === "failed") return { id: job.id, status: "deadletter", output: reason };
|
|
46
|
-
return { id: job.id, status: "completed" };
|
|
47
|
-
} catch (error) {
|
|
48
|
-
return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
|
|
49
|
-
}
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
for (const { name, tuning } of queues) {
|
|
53
|
-
const config = queueConfig(tuning?.queue);
|
|
54
|
-
const { partition: _createOnly, ...updatable } = config;
|
|
55
|
-
await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
|
|
56
|
-
await boss.updateQueue(name, updatable);
|
|
57
|
-
await boss.work<Job>(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
|
|
61
|
-
// They never get a try that could report, so say so here
|
|
62
|
-
const ours = new Set(queues.map((q) => q.name));
|
|
63
|
-
for (const q of await boss.getQueues())
|
|
64
|
-
if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
|
|
65
|
-
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.`));
|
|
66
|
-
|
|
67
|
-
if (!crons.length) return;
|
|
68
|
-
// ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
|
|
69
|
-
const stop = startTicking(registry, { sweepEvery: 0, onError });
|
|
70
|
-
boss.once("stopped", () => void stop());
|
|
71
|
-
}
|
package/src/pg-boss.ts
DELETED