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
|
@@ -70,15 +70,15 @@ export const cancel = mutation({
|
|
|
70
70
|
7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
|
|
71
71
|
8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error: nested mutations share the caller's transaction, so a caught failure fails the commit with an error naming both. Work over many rows where each must commit or fail alone (a cron over every account) `ctx.run`s the mutation per row inside `try`/`catch`, from a cron's handler or an action: never from a mutation.
|
|
72
72
|
9. **Need the result? `run` it. Just a consequence? `emit`** and let the owning module react in its `listeners.ts`.
|
|
73
|
-
10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners.
|
|
73
|
+
10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners. When jobs for the same thing must not overlap and must keep their order (a conversation's messages), give it `key: (p) => p.conversationId` (on `inProcess()`, `databaseQueue()` and `outbox(...)`; refused on Cloudflare alone; never with `unique` on the same listener). When only the latest state matters ("X changed, recompute X"), `unique: (p) => p.productId` with a `delay` drops the events that arrive while one job waits: its handler must read current state, never the payload's data. `timeout: 30` stops a try that hangs: pass `ctx.signal` to `fetch` and AI calls. To undo or flag what a listener started once its last try failed, give it `failed: async (ctx, payload, error) => { await ctx.run(orders.flagReceipt, { orderId: payload.orderId }) }` (crons: `failed(ctx, error)`), not a branch in `onError`. Slow work that must not delay the rest goes in a queue: `jobs: { queues: ["mail", "reports"] }` once, `queue: "reports"` on the listener, cron or `ctx.schedule`, and `work(registry, { queues: ["mail", "default"] })` per worker, first queue first (Cloudflare: `cloudflareQueue({ default: env.JOBS, reports: env.REPORTS })`).
|
|
74
74
|
11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). `ctx.emit` returns the event it queued (`{ id, name, payload, occurredAt }`): a row written in the same mutation can carry `event.id`, the id listeners see as `ctx.event.id`. They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, pass the whole scope for that call: `ctx.run(fn, input, { scope: { ...ctx.scope, actor: system } })`. It's never merged, so it's always one of your scope's variants.
|
|
75
75
|
12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
|
|
76
76
|
13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
|
|
77
77
|
14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
|
|
78
78
|
15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
|
|
79
|
-
16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database: { adapter: database }, jobs: { adapter: databaseQueue(), scope: { store, load } } })` (your database is the queue
|
|
80
|
-
17. **Scheduled work is a `cron`,** a listener for the clock, exported from the module: `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(fn) } })`, where `scope` is a system variant of the app's own `Scope` (its own `kind` and the job's name, never built from a request; the library defines no scope fields) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. The handler gets an action's ctx plus `ctx.cron` (`scheduledAt`: the minute the run is for; `attempt`), and `ctx.scope` typed as the declared scope; every `ctx.run` checks that function's policy against it. Name a cron after its work, like a listener (`sendDigest`); one that runs shared work, after when it runs (`nightly`). A retry reruns the whole handler: make it idempotent, and put all-or-nothing work in one `ctx.run(mutation)`. `meta` like a listener's
|
|
81
|
-
18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). It returns nothing, and there's no cancel: your row is the truth. Cancelling a booking writes `status: "cancelled"`, and the function checks its reason when it runs, in the same transaction as its effect (`update ... where status = 'confirmed' and reminder_sent_at is null returning id`; nothing returned, so `return`). Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: true`: a newer call to the same function with the same input replaces the waiting one, so it doesn't run twice. Keep the input to ids (`{ bookingId }`), so it names one thing. To run it as someone else, pass the whole scope: `{ at, scope: { kind: "system", job: "tasks.wake", organization } }`. It needs `jobs: { adapter: databaseQueue(), scope: { store, load } }
|
|
79
|
+
16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database: { adapter: database }, jobs: { adapter: databaseQueue(), scope: { store, load } } })` (your database is the queue; export `jobsTable` from the schema and sweep from a cron trigger, or on Node and Bun run `work(registry)` from `logic-sdk/node` in the server's entry: it takes the jobs requests commit, so they answer first, and never pass `waitUntil` there; with slow jobs, `databaseQueue({ runIn: "worker" })` and `work(registry, { concurrency })` in worker processes, so web requests only write rows), `outbox(cloudflareQueue(env.JOBS))` when another queue runs them (every job stays a row and the queue carries signals; the queue alone works too, and can lose a job on a crash). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe (`inProcess()` refuses attempts above 1: it runs each job once), and `delay: 60` (seconds) to run it later.
|
|
80
|
+
17. **Scheduled work is a `cron`,** a listener for the clock, exported from the module: `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(fn) } })`, where `scope` is a system variant of the app's own `Scope` (its own `kind` and the job's name, never built from a request; the library defines no scope fields) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. The handler gets an action's ctx plus `ctx.cron` (`scheduledAt`: the minute the run is for; `attempt`), and `ctx.scope` typed as the declared scope; every `ctx.run` checks that function's policy against it. Name a cron after its work, like a listener (`sendDigest`); one that runs shared work, after when it runs (`nightly`). A retry reruns the whole handler: make it idempotent, and put all-or-nothing work in one `ctx.run(mutation)`. `meta` like a listener's. On Node, `work(registry)` from `logic-sdk/node` ticks them (`await stop()` on SIGTERM); on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)` (every cron due that minute) or `t.jobs.perform(cron, { at })` (that one, due or not).
|
|
81
|
+
18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). It returns nothing, and there's no cancel: your row is the truth. Cancelling a booking writes `status: "cancelled"`, and the function checks its reason when it runs, in the same transaction as its effect (`update ... where status = 'confirmed' and reminder_sent_at is null returning id`; nothing returned, so `return`). Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: true`: a newer call to the same function with the same input replaces the waiting one, so it doesn't run twice. Keep the input to ids (`{ bookingId }`), so it names one thing. To run it as someone else, pass the whole scope: `{ at, scope: { kind: "system", job: "tasks.wake", organization } }`. It needs `jobs: { adapter: databaseQueue(), scope: { store, load } }` or an `outbox` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
|
|
82
82
|
19. **Failed jobs and run-now are for operators,** outside functions, in scripts and staff routes you guard with your own policy: `registry.jobs.failed({ source: "emails.send", scope: { organizationId }, cursor })` (newest first; `scope` matches what `store` saved), then `retry(id)` or `forget(id)` each (a queue on its own keeps them in `jobs: { failed: failedJobs() }`); `registry.jobs.invoke(orders.sendDigest)` runs a cron now (`{ at }` for a missed minute). A user never retries a job: what they want again is a mutation that checks your row and emits again.
|
|
83
83
|
|
|
84
84
|
## Tests
|
|
@@ -18,15 +18,24 @@ const encoder = new TextEncoder();
|
|
|
18
18
|
/**
|
|
19
19
|
* Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
|
|
20
20
|
* them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
|
|
21
|
-
* Run them with `handleQueue(registry, batch)` in your consumer.
|
|
21
|
+
* Run them with `handleQueue(registry, batch)` in your consumer. With `jobs.queues`, one binding per queue, `"default"`
|
|
22
|
+
* included: `cloudflareQueue({ default: env.JOBS, mail: env.MAIL })`.
|
|
22
23
|
*/
|
|
23
|
-
export function cloudflareQueue(queue: QueueBinding): JobsAdapter {
|
|
24
|
+
export function cloudflareQueue(queue: QueueBinding | Readonly<Record<string, QueueBinding>>): JobsAdapter {
|
|
25
|
+
const one = typeof queue.sendBatch === "function";
|
|
26
|
+
const bindings = (one ? { default: queue } : queue) as Readonly<Record<string, QueueBinding>>;
|
|
24
27
|
return {
|
|
25
|
-
name: "cloudflareQueue(queue)",
|
|
28
|
+
name: one ? "cloudflareQueue(queue)" : `cloudflareQueue({ ${Object.keys(bindings).join(", ")} })`,
|
|
26
29
|
retries: true, // handleQueue retries a message with a backoff
|
|
27
30
|
holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
|
|
31
|
+
...(one ? {} : { queues: Object.keys(bindings) }),
|
|
28
32
|
async deliver(jobs) {
|
|
29
|
-
|
|
33
|
+
const byQueue = Map.groupBy(jobs, (job) => job.queue ?? "default");
|
|
34
|
+
for (const [name, some] of byQueue) {
|
|
35
|
+
const binding = bindings[name];
|
|
36
|
+
if (!binding) throw new Error(`[logic-sdk] cloudflareQueue has no binding for queue ${JSON.stringify(name)}.`);
|
|
37
|
+
for (const batch of batches(some)) await binding.sendBatch(batch);
|
|
38
|
+
}
|
|
30
39
|
},
|
|
31
40
|
};
|
|
32
41
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { sql, type SQL } from "drizzle-orm";
|
|
2
|
-
import { index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
2
|
+
import { bigserial, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3
3
|
import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
|
|
4
4
|
import { causes } from "../core/errors.ts";
|
|
5
5
|
|
|
@@ -84,14 +84,23 @@ export const jobsTable = pgTable(
|
|
|
84
84
|
/** The last failure, with its stack. */
|
|
85
85
|
lastError: text("last_error"),
|
|
86
86
|
failedAt: timestamp("failed_at", { withTimezone: true }),
|
|
87
|
-
/**
|
|
88
|
-
|
|
87
|
+
/**
|
|
88
|
+
* One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
|
|
89
|
+
* call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
|
|
90
|
+
*/
|
|
91
|
+
uniqueKey: text("unique_key"),
|
|
92
|
+
/** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, by `seq`. */
|
|
93
|
+
orderKey: text("order_key"),
|
|
94
|
+
/** The insert order, for `orderKey`. */
|
|
95
|
+
seq: bigserial("seq", { mode: "number" }).notNull(),
|
|
89
96
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
90
97
|
},
|
|
91
98
|
(t) => [
|
|
92
99
|
index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
|
|
93
|
-
// one waiting
|
|
94
|
-
uniqueIndex("
|
|
100
|
+
// one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
101
|
+
uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql`status = 'pending' and attempts = 0`),
|
|
102
|
+
// a key's open rows, for the first of each
|
|
103
|
+
index("logic_jobs_order").on(t.orderKey, t.seq).where(sql`status = 'pending'`),
|
|
95
104
|
// `registry.jobs.failed()` pages newest first by (failed_at, id)
|
|
96
105
|
index("logic_jobs_failed").on(t.failedAt, t.id).where(sql`status = 'failed'`),
|
|
97
106
|
],
|
|
@@ -213,14 +213,21 @@ export const jobsTable = sqliteTable(
|
|
|
213
213
|
/** The last failure, with its stack. */
|
|
214
214
|
lastError: text("last_error"),
|
|
215
215
|
failedAt: integer("failed_at", { mode: "timestamp_ms" }),
|
|
216
|
-
/**
|
|
217
|
-
|
|
216
|
+
/**
|
|
217
|
+
* One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
|
|
218
|
+
* call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
|
|
219
|
+
*/
|
|
220
|
+
uniqueKey: text("unique_key"),
|
|
221
|
+
/** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, in insert order (`rowid`). */
|
|
222
|
+
orderKey: text("order_key"),
|
|
218
223
|
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
219
224
|
},
|
|
220
225
|
(t) => [
|
|
221
226
|
index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
|
|
222
|
-
// one waiting
|
|
223
|
-
uniqueIndex("
|
|
227
|
+
// one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
228
|
+
uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql`status = 'pending' and attempts = 0`),
|
|
229
|
+
// a key's open rows, for the first of each
|
|
230
|
+
index("logic_jobs_order").on(t.orderKey).where(sql`status = 'pending'`),
|
|
224
231
|
// `registry.jobs.failed()` pages newest first by (failed_at, id)
|
|
225
232
|
index("logic_jobs_failed").on(t.failedAt, t.id).where(sql`status = 'failed'`),
|
|
226
233
|
],
|
package/src/adapters/postgres.ts
CHANGED
|
@@ -15,11 +15,14 @@ CREATE TABLE logic_jobs (
|
|
|
15
15
|
claimed_at timestamptz,
|
|
16
16
|
last_error text,
|
|
17
17
|
failed_at timestamptz,
|
|
18
|
-
|
|
18
|
+
unique_key text,
|
|
19
|
+
order_key text,
|
|
20
|
+
seq bigserial NOT NULL,
|
|
19
21
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
20
22
|
);
|
|
21
23
|
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
22
|
-
CREATE UNIQUE INDEX
|
|
24
|
+
CREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;
|
|
25
|
+
CREATE INDEX logic_jobs_order ON logic_jobs (order_key, seq) WHERE status = 'pending';
|
|
23
26
|
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
24
27
|
CREATE TABLE logic_cron_runs (
|
|
25
28
|
id text PRIMARY KEY,
|
|
@@ -29,27 +32,47 @@ CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
|
29
32
|
`;
|
|
30
33
|
|
|
31
34
|
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
32
|
-
const
|
|
33
|
-
const mine = (n: number) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
35
|
+
const mine = (n: number) => `id = $${n} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
34
36
|
const inSeconds = (n: number) => `now() + make_interval(secs => $${n}::float8)`;
|
|
37
|
+
/**
|
|
38
|
+
* A row may run when it has started already (one per key: a retry backing off), or when no other open row of its key
|
|
39
|
+
* started or came before it (`seq`, the insert order). A failed row put back by `retry(id)` waits behind one that started.
|
|
40
|
+
*/
|
|
41
|
+
const firstOfKey = `(order_key IS NULL OR attempts > 0 OR NOT EXISTS (
|
|
42
|
+
SELECT 1 FROM logic_jobs o WHERE o.order_key = logic_jobs.order_key AND o.status = 'pending' AND o.id <> logic_jobs.id AND (o.seq < logic_jobs.seq OR o.attempts > 0)))`;
|
|
35
43
|
|
|
36
44
|
const statements: JobsSql = {
|
|
37
|
-
//
|
|
45
|
+
// a waiting row with this key: a call replaces it (its id, job and time: Oban's `replace`), a unique delivery is
|
|
46
|
+
// dropped. Postgres locks the row either way, so it can't start before this transaction ends and miss its change
|
|
38
47
|
insert: `
|
|
39
|
-
INSERT INTO logic_jobs (id, job, available_at,
|
|
40
|
-
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'
|
|
48
|
+
INSERT INTO logic_jobs (id, job, available_at, unique_key, order_key)
|
|
49
|
+
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'unique', r->>'order'
|
|
41
50
|
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
42
|
-
ON CONFLICT (
|
|
43
|
-
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
51
|
+
ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
|
|
52
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
53
|
+
WHERE excluded.job->>'kind' = 'call'`,
|
|
44
54
|
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
45
55
|
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
46
56
|
claimNew: `
|
|
47
57
|
UPDATE logic_jobs SET attempts = 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
48
|
-
WHERE id
|
|
58
|
+
WHERE id = $3 AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
|
|
49
59
|
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
50
60
|
claimDue: `
|
|
51
61
|
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()
|
|
62
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() - make_interval(secs => $3::float8) AND ${firstOfKey}
|
|
63
|
+
AND coalesce(nullif($4::text, ''), coalesce(job ->> 'queue', 'default')) = coalesce(job ->> 'queue', 'default') ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
64
|
+
RETURNING job::text AS job, attempts`,
|
|
65
|
+
// the row a queue's signal names, if it's due. It waits for a transaction holding the row (a replace) rather than
|
|
66
|
+
// skip it: there's no other row to take
|
|
67
|
+
claimOne: `
|
|
68
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
69
|
+
WHERE id = $3 AND status = 'pending' AND available_at <= now()
|
|
70
|
+
RETURNING job::text AS job, attempts`,
|
|
71
|
+
// due, or never tried and waiting only for its turn (not for a `delay`): no need to wait for a sweep
|
|
72
|
+
claimNext: `
|
|
73
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
74
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND order_key = $3 AND (available_at <= now() OR (attempts = 0 AND job->>'runAt' IS NULL))
|
|
75
|
+
AND ${firstOfKey} ORDER BY seq LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
53
76
|
RETURNING job::text AS job, attempts`,
|
|
54
77
|
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
55
78
|
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2, claimed_at = NULL WHERE ${mine(3)}`,
|
|
@@ -58,7 +81,7 @@ const statements: JobsSql = {
|
|
|
58
81
|
// 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
82
|
// a call a newer one replaces (and one may be waiting with it)
|
|
60
83
|
retry: `
|
|
61
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = now(), last_error = NULL, failed_at = NULL,
|
|
84
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = now(), last_error = NULL, failed_at = NULL, unique_key = NULL
|
|
62
85
|
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
63
86
|
fail: `
|
|
64
87
|
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
@@ -83,21 +106,22 @@ const statements: JobsSql = {
|
|
|
83
106
|
/**
|
|
84
107
|
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
85
108
|
* 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
|
|
87
|
-
* its row being deleted runs it again.
|
|
109
|
+
* is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
|
|
110
|
+
* behind. With `runIn: "worker"`, requests only write rows and workers in other processes run them. At least once: a crash between a job finishing and its row being deleted runs it again.
|
|
88
111
|
*
|
|
89
112
|
* ```ts
|
|
90
113
|
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
91
|
-
*
|
|
114
|
+
* work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
92
115
|
* ```
|
|
93
116
|
*/
|
|
94
117
|
export const databaseQueue = (options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, options);
|
|
95
118
|
|
|
96
119
|
/**
|
|
97
|
-
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction,
|
|
98
|
-
* until
|
|
99
|
-
* one
|
|
100
|
-
*
|
|
120
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, and stay
|
|
121
|
+
* rows until they're done: the queue gets a signal per job (per key, for a listener's `key`), and the consumer that gets
|
|
122
|
+
* one runs the row from the table and records how it went there. So tries, failed rows and a key's order are the
|
|
123
|
+
* table's, as with `databaseQueue`. A failed try gets a new signal for when its backoff ends; what no signal covers, the
|
|
124
|
+
* sweep runs 30 seconds past due. At least once: a consumer that dies after the work leaves the row to run again.
|
|
101
125
|
*
|
|
102
126
|
* ```ts
|
|
103
127
|
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
package/src/adapters/sqlite.ts
CHANGED
|
@@ -18,11 +18,13 @@ CREATE TABLE logic_jobs (
|
|
|
18
18
|
claimed_at integer,
|
|
19
19
|
last_error text,
|
|
20
20
|
failed_at integer,
|
|
21
|
-
|
|
21
|
+
unique_key text,
|
|
22
|
+
order_key text,
|
|
22
23
|
created_at integer NOT NULL DEFAULT (${now})
|
|
23
24
|
);
|
|
24
25
|
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
25
|
-
CREATE UNIQUE INDEX
|
|
26
|
+
CREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;
|
|
27
|
+
CREATE INDEX logic_jobs_order ON logic_jobs (order_key) WHERE status = 'pending';
|
|
26
28
|
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
27
29
|
CREATE TABLE logic_cron_runs (
|
|
28
30
|
id text PRIMARY KEY NOT NULL,
|
|
@@ -31,36 +33,54 @@ CREATE TABLE logic_cron_runs (
|
|
|
31
33
|
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
32
34
|
`;
|
|
33
35
|
|
|
34
|
-
const
|
|
35
|
-
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
36
|
+
const mine = `id = ? AND receipt = ? AND status = 'pending'`;
|
|
36
37
|
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
38
|
+
/**
|
|
39
|
+
* A row may run when it has started already (one per key: a retry backing off), or when no other open row of its key
|
|
40
|
+
* started or came before it (`rowid`, the insert order). A failed row put back by `retry(id)` waits behind one that started.
|
|
41
|
+
*/
|
|
42
|
+
const firstOfKey = `(order_key IS NULL OR attempts > 0 OR NOT EXISTS (
|
|
43
|
+
SELECT 1 FROM logic_jobs o WHERE o.order_key = logic_jobs.order_key AND o.status = 'pending' AND o.id <> logic_jobs.id AND (o.rowid < logic_jobs.rowid OR o.attempts > 0)))`;
|
|
37
44
|
|
|
38
45
|
const statements: JobsSql = {
|
|
39
|
-
//
|
|
40
|
-
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON
|
|
46
|
+
// a waiting row with this key: a call replaces it (its id, job and time: Oban's `replace`), a unique delivery is
|
|
47
|
+
// dropped. `json_each.key` is the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON
|
|
48
|
+
// CONFLICT from a join's ON
|
|
41
49
|
insert: `
|
|
42
|
-
INSERT INTO logic_jobs (id, job, available_at,
|
|
43
|
-
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> '
|
|
50
|
+
INSERT INTO logic_jobs (id, job, available_at, unique_key, order_key)
|
|
51
|
+
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'unique', value ->> 'order'
|
|
44
52
|
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
45
|
-
ON CONFLICT (
|
|
53
|
+
ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
|
|
46
54
|
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
55
|
+
WHERE excluded.job ->> 'kind' = 'call'
|
|
47
56
|
RETURNING id`,
|
|
48
57
|
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
49
58
|
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
50
59
|
claimNew: `
|
|
51
60
|
UPDATE logic_jobs SET attempts = 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
52
|
-
WHERE id
|
|
61
|
+
WHERE id = ? AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
|
|
53
62
|
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
54
63
|
claimDue: `
|
|
55
64
|
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}
|
|
65
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} - cast(? * 1000 as integer) AND ${firstOfKey}
|
|
66
|
+
AND coalesce(nullif(?, ''), coalesce(job ->> 'queue', 'default')) = coalesce(job ->> 'queue', 'default') ORDER BY available_at LIMIT 1)
|
|
67
|
+
RETURNING job, attempts`,
|
|
68
|
+
claimOne: `
|
|
69
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
70
|
+
WHERE id = ? AND status = 'pending' AND available_at <= ${now}
|
|
71
|
+
RETURNING job, attempts`,
|
|
72
|
+
// due, or never tried and waiting only for its turn (not for a `delay`): no need to wait for a sweep
|
|
73
|
+
claimNext: `
|
|
74
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
75
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND order_key = ? AND (available_at <= ${now} OR (attempts = 0 AND job ->> 'runAt' IS NULL))
|
|
76
|
+
AND ${firstOfKey} ORDER BY rowid LIMIT 1)
|
|
57
77
|
RETURNING job, attempts`,
|
|
58
78
|
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
59
79
|
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ?, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
60
80
|
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now}, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
61
81
|
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
62
82
|
retry: `
|
|
63
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL,
|
|
83
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, unique_key = NULL
|
|
64
84
|
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
65
85
|
fail: `
|
|
66
86
|
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|