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.
Files changed (54) hide show
  1. package/README.md +2 -3
  2. package/dist/adapters/cloudflare-queue.d.ts +3 -2
  3. package/dist/adapters/cloudflare-queue.js +14 -4
  4. package/dist/adapters/drizzle-pg.d.ts +31 -1
  5. package/dist/adapters/drizzle-pg.js +14 -5
  6. package/dist/adapters/drizzle-sqlite.d.ts +17 -1
  7. package/dist/adapters/drizzle-sqlite.js +11 -4
  8. package/dist/adapters/postgres.d.ts +9 -8
  9. package/dist/adapters/postgres.js +43 -19
  10. package/dist/adapters/sqlite.d.ts +1 -1
  11. package/dist/adapters/sqlite.js +32 -12
  12. package/dist/adapters/stored-jobs.d.ts +27 -19
  13. package/dist/adapters/stored-jobs.js +157 -61
  14. package/dist/core/in-process.js +23 -3
  15. package/dist/core/jobs.d.ts +12 -6
  16. package/dist/core/jobs.js +158 -17
  17. package/dist/core/registry.d.ts +39 -3
  18. package/dist/core/registry.js +23 -11
  19. package/dist/core/testing.js +3 -1
  20. package/dist/core/types.d.ts +96 -34
  21. package/dist/hosts/cloudflare.d.ts +5 -4
  22. package/dist/hosts/cloudflare.js +5 -4
  23. package/dist/hosts/node.d.ts +25 -15
  24. package/dist/hosts/node.js +61 -34
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +1 -1
  27. package/dist/node.d.ts +1 -1
  28. package/dist/node.js +1 -1
  29. package/package.json +1 -11
  30. package/skills/logic-sdk/SKILL.md +4 -4
  31. package/src/adapters/cloudflare-queue.ts +13 -4
  32. package/src/adapters/drizzle-pg.ts +14 -5
  33. package/src/adapters/drizzle-sqlite.ts +11 -4
  34. package/src/adapters/postgres.ts +43 -19
  35. package/src/adapters/sqlite.ts +32 -12
  36. package/src/adapters/stored-jobs.ts +174 -74
  37. package/src/core/in-process.ts +22 -2
  38. package/src/core/jobs.ts +146 -19
  39. package/src/core/registry.ts +62 -14
  40. package/src/core/testing.ts +3 -1
  41. package/src/core/types.ts +93 -30
  42. package/src/hosts/cloudflare.ts +5 -4
  43. package/src/hosts/node.ts +73 -46
  44. package/src/index.ts +3 -1
  45. package/src/node.ts +1 -1
  46. package/dist/adapters/pg-boss.d.ts +0 -45
  47. package/dist/adapters/pg-boss.js +0 -180
  48. package/dist/hosts/pg-boss.d.ts +0 -22
  49. package/dist/hosts/pg-boss.js +0 -55
  50. package/dist/pg-boss.d.ts +0 -2
  51. package/dist/pg-boss.js +0 -2
  52. package/src/adapters/pg-boss.ts +0 -195
  53. package/src/hosts/pg-boss.ts +0 -71
  54. package/src/pg-boss.ts +0 -2
package/README.md CHANGED
@@ -94,7 +94,7 @@ ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
94
94
 
95
95
  - **One transaction across modules.** A failure anywhere rolls back everything, even if someone catches it.
96
96
  - **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
97
- - **Jobs, four ways.** Your Postgres as the queue (`databaseQueue`), Cloudflare Queues alone, an outbox in front of a queue, or pg-boss. All but in-process can run a job twice, so make them idempotent.
97
+ - **Jobs, three ways.** Your Postgres or SQLite as the queue (`databaseQueue`, with `work()` as the worker on Node), Cloudflare Queues alone, or an outbox in front of a queue. All but in-process can run a job twice, so make them idempotent.
98
98
  - **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction: three tries, or `database: { adapter, transactionAttempts }`.
99
99
  - **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
100
100
  - **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
@@ -114,8 +114,7 @@ ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
114
114
  | `logic-sdk/drizzle/sqlite` | The same on SQLite: `drizzleAdapter(() => drizzle("app.db"))` |
115
115
  | `logic-sdk/sqlite` | `databaseQueue`, `outbox` and `failedJobs` on SQLite with any ORM |
116
116
  | `logic-sdk/cloudflare` | Cloudflare Queues and Cron Triggers |
117
- | `logic-sdk/pg-boss` | Jobs in pg-boss |
118
- | `logic-sdk/node` | `startTicking`: crons and sweeps in a long-running process |
117
+ | `logic-sdk/node` | `work(registry)`: a worker for jobs and crons in a long-running process |
119
118
  | `logic-sdk/fetch` | `toResponse`: a domain error as an HTTP response, for your own routes |
120
119
  | `logic-sdk/orpc` | `toORPCProcedure`: a function as an oRPC v2 procedure, for your router |
121
120
  | `logic-sdk/ai` | AI SDK tools: agents run your functions with the same rules |
@@ -9,6 +9,7 @@ export interface QueueBinding {
9
9
  /**
10
10
  * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
11
11
  * them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
12
- * Run them with `handleQueue(registry, batch)` in your consumer.
12
+ * Run them with `handleQueue(registry, batch)` in your consumer. With `jobs.queues`, one binding per queue, `"default"`
13
+ * included: `cloudflareQueue({ default: env.JOBS, mail: env.MAIL })`.
13
14
  */
14
- export declare function cloudflareQueue(queue: QueueBinding): JobsAdapter;
15
+ export declare function cloudflareQueue(queue: QueueBinding | Readonly<Record<string, QueueBinding>>): JobsAdapter;
@@ -10,16 +10,26 @@ const encoder = new TextEncoder();
10
10
  /**
11
11
  * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
12
12
  * them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
13
- * Run them with `handleQueue(registry, batch)` in your consumer.
13
+ * Run them with `handleQueue(registry, batch)` in your consumer. With `jobs.queues`, one binding per queue, `"default"`
14
+ * included: `cloudflareQueue({ default: env.JOBS, mail: env.MAIL })`.
14
15
  */
15
16
  export function cloudflareQueue(queue) {
17
+ const one = typeof queue.sendBatch === "function";
18
+ const bindings = (one ? { default: queue } : queue);
16
19
  return {
17
- name: "cloudflareQueue(queue)",
20
+ name: one ? "cloudflareQueue(queue)" : `cloudflareQueue({ ${Object.keys(bindings).join(", ")} })`,
18
21
  retries: true, // handleQueue retries a message with a backoff
19
22
  holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
23
+ ...(one ? {} : { queues: Object.keys(bindings) }),
20
24
  async deliver(jobs) {
21
- for (const batch of batches(jobs))
22
- await queue.sendBatch(batch);
25
+ const byQueue = Map.groupBy(jobs, (job) => job.queue ?? "default");
26
+ for (const [name, some] of byQueue) {
27
+ const binding = bindings[name];
28
+ if (!binding)
29
+ throw new Error(`[logic-sdk] cloudflareQueue has no binding for queue ${JSON.stringify(name)}.`);
30
+ for (const batch of batches(some))
31
+ await binding.sendBatch(batch);
32
+ }
23
33
  },
24
34
  };
25
35
  }
@@ -171,7 +171,7 @@ export declare const jobsTable: import("drizzle-orm/pg-core").PgTableWithColumns
171
171
  identity: undefined;
172
172
  generated: undefined;
173
173
  }>;
174
- replaceKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
174
+ uniqueKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
175
175
  name: string;
176
176
  tableName: "logic_jobs";
177
177
  dataType: "string";
@@ -186,6 +186,36 @@ export declare const jobsTable: import("drizzle-orm/pg-core").PgTableWithColumns
186
186
  identity: undefined;
187
187
  generated: undefined;
188
188
  }>;
189
+ orderKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
190
+ name: string;
191
+ tableName: "logic_jobs";
192
+ dataType: "string";
193
+ data: string;
194
+ driverParam: string;
195
+ notNull: false;
196
+ hasDefault: false;
197
+ isPrimaryKey: false;
198
+ isAutoincrement: false;
199
+ hasRuntimeDefault: false;
200
+ enumValues: undefined;
201
+ identity: undefined;
202
+ generated: undefined;
203
+ }>;
204
+ seq: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgBigSerial53Builder>, {
205
+ name: string;
206
+ tableName: "logic_jobs";
207
+ dataType: "number int53";
208
+ data: number;
209
+ driverParam: number;
210
+ notNull: true;
211
+ hasDefault: true;
212
+ isPrimaryKey: false;
213
+ isAutoincrement: false;
214
+ hasRuntimeDefault: false;
215
+ enumValues: undefined;
216
+ identity: undefined;
217
+ generated: undefined;
218
+ }>;
189
219
  createdAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
190
220
  name: string;
191
221
  tableName: "logic_jobs";
@@ -1,5 +1,5 @@
1
1
  import { 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 { causes } from "../core/errors.js";
4
4
  /**
5
5
  * Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
@@ -48,13 +48,22 @@ export const jobsTable = pgTable("logic_jobs", {
48
48
  /** The last failure, with its stack. */
49
49
  lastError: text("last_error"),
50
50
  failedAt: timestamp("failed_at", { withTimezone: true }),
51
- /** A scheduled call's `replace` key, `<function id>@<sha-256 of its input>`: a newer call with it replaces this row while it waits. */
52
- replaceKey: text("replace_key"),
51
+ /**
52
+ * One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
53
+ * call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
54
+ */
55
+ uniqueKey: text("unique_key"),
56
+ /** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, by `seq`. */
57
+ orderKey: text("order_key"),
58
+ /** The insert order, for `orderKey`. */
59
+ seq: bigserial("seq", { mode: "number" }).notNull(),
53
60
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
54
61
  }, (t) => [
55
62
  index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
56
- // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
57
- uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql `status = 'pending' and attempts = 0`),
63
+ // one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
64
+ uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql `status = 'pending' and attempts = 0`),
65
+ // a key's open rows, for the first of each
66
+ index("logic_jobs_order").on(t.orderKey, t.seq).where(sql `status = 'pending'`),
58
67
  // `registry.jobs.failed()` pages newest first by (failed_at, id)
59
68
  index("logic_jobs_failed").on(t.failedAt, t.id).where(sql `status = 'failed'`),
60
69
  ]);
@@ -177,7 +177,23 @@ export declare const jobsTable: import("drizzle-orm/sqlite-core").SQLiteTableWit
177
177
  identity: undefined;
178
178
  generated: undefined;
179
179
  }, {}>;
180
- replaceKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
180
+ uniqueKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
181
+ name: string;
182
+ tableName: "logic_jobs";
183
+ dataType: "string";
184
+ data: string;
185
+ driverParam: string;
186
+ notNull: false;
187
+ hasDefault: false;
188
+ isPrimaryKey: false;
189
+ isAutoincrement: false;
190
+ hasRuntimeDefault: false;
191
+ enumValues: [string, ...string[]];
192
+ baseColumn: never;
193
+ identity: undefined;
194
+ generated: undefined;
195
+ }, {}>;
196
+ orderKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
181
197
  name: string;
182
198
  tableName: "logic_jobs";
183
199
  dataType: "string";
@@ -178,13 +178,20 @@ export const jobsTable = sqliteTable("logic_jobs", {
178
178
  /** The last failure, with its stack. */
179
179
  lastError: text("last_error"),
180
180
  failedAt: integer("failed_at", { mode: "timestamp_ms" }),
181
- /** A scheduled call's `replace` key, `<function id>@<sha-256 of its input>`: a newer call with it replaces this row while it waits. */
182
- replaceKey: text("replace_key"),
181
+ /**
182
+ * One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
183
+ * call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
184
+ */
185
+ uniqueKey: text("unique_key"),
186
+ /** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, in insert order (`rowid`). */
187
+ orderKey: text("order_key"),
183
188
  createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
184
189
  }, (t) => [
185
190
  index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
186
- // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
187
- uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql `status = 'pending' and attempts = 0`),
191
+ // one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
192
+ uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql `status = 'pending' and attempts = 0`),
193
+ // a key's open rows, for the first of each
194
+ index("logic_jobs_order").on(t.orderKey).where(sql `status = 'pending'`),
188
195
  // `registry.jobs.failed()` pages newest first by (failed_at, id)
189
196
  index("logic_jobs_failed").on(t.failedAt, t.id).where(sql `status = 'failed'`),
190
197
  ]);
@@ -1,24 +1,25 @@
1
1
  import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
2
2
  import type { FailedJobs, JobsAdapter } from "../core/types.ts";
3
3
  /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
4
- export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n claimed_at timestamptz,\n last_error text,\n failed_at timestamptz,\n replace_key text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
4
+ export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n claimed_at timestamptz,\n last_error text,\n failed_at timestamptz,\n unique_key text,\n order_key text,\n seq bigserial NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_order ON logic_jobs (order_key, seq) WHERE status = 'pending';\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
5
5
  /**
6
6
  * Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
7
7
  * a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
8
- * is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
9
- * its row being deleted runs it again.
8
+ * is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
9
+ * 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.
10
10
  *
11
11
  * ```ts
12
12
  * const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
13
- * startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
13
+ * work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
14
14
  * ```
15
15
  */
16
16
  export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
17
17
  /**
18
- * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
19
- * until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
20
- * 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,
21
- * so a job can run twice, even at once.
18
+ * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, and stay
19
+ * rows until they're done: the queue gets a signal per job (per key, for a listener's `key`), and the consumer that gets
20
+ * one runs the row from the table and records how it went there. So tries, failed rows and a key's order are the
21
+ * table's, as with `databaseQueue`. A failed try gets a new signal for when its backoff ends; what no signal covers, the
22
+ * sweep runs 30 seconds past due. At least once: a consumer that dies after the work leaves the row to run again.
22
23
  *
23
24
  * ```ts
24
25
  * jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
@@ -13,11 +13,14 @@ CREATE TABLE logic_jobs (
13
13
  claimed_at timestamptz,
14
14
  last_error text,
15
15
  failed_at timestamptz,
16
- replace_key text,
16
+ unique_key text,
17
+ order_key text,
18
+ seq bigserial NOT NULL,
17
19
  created_at timestamptz NOT NULL DEFAULT now()
18
20
  );
19
21
  CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
20
- CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
22
+ CREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;
23
+ CREATE INDEX logic_jobs_order ON logic_jobs (order_key, seq) WHERE status = 'pending';
21
24
  CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
22
25
  CREATE TABLE logic_cron_runs (
23
26
  id text PRIMARY KEY,
@@ -26,26 +29,46 @@ CREATE TABLE logic_cron_runs (
26
29
  CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
27
30
  `;
28
31
  // `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
29
- const ids = (n) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
30
- const mine = (n) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
32
+ const mine = (n) => `id = $${n} AND receipt = $${n + 1} AND status = 'pending'`;
31
33
  const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
34
+ /**
35
+ * 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
36
+ * started or came before it (`seq`, the insert order). A failed row put back by `retry(id)` waits behind one that started.
37
+ */
38
+ const firstOfKey = `(order_key IS NULL OR attempts > 0 OR NOT EXISTS (
39
+ 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)))`;
32
40
  const statements = {
33
- // the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
41
+ // a waiting row with this key: a call replaces it (its id, job and time: Oban's `replace`), a unique delivery is
42
+ // dropped. Postgres locks the row either way, so it can't start before this transaction ends and miss its change
34
43
  insert: `
35
- INSERT INTO logic_jobs (id, job, available_at, replace_key)
36
- SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
44
+ INSERT INTO logic_jobs (id, job, available_at, unique_key, order_key)
45
+ SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'unique', r->>'order'
37
46
  FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
38
- ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
39
- DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
47
+ ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
48
+ DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
49
+ WHERE excluded.job->>'kind' = 'call'`,
40
50
  recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
41
51
  pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
42
52
  claimNew: `
43
53
  UPDATE logic_jobs SET attempts = 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
44
- WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
54
+ WHERE id = $3 AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
45
55
  // `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
46
56
  claimDue: `
47
57
  UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
48
- WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
58
+ WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() - make_interval(secs => $3::float8) AND ${firstOfKey}
59
+ AND coalesce(nullif($4::text, ''), coalesce(job ->> 'queue', 'default')) = coalesce(job ->> 'queue', 'default') ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
60
+ RETURNING job::text AS job, attempts`,
61
+ // the row a queue's signal names, if it's due. It waits for a transaction holding the row (a replace) rather than
62
+ // skip it: there's no other row to take
63
+ claimOne: `
64
+ UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
65
+ WHERE id = $3 AND status = 'pending' AND available_at <= now()
66
+ RETURNING job::text AS job, attempts`,
67
+ // due, or never tried and waiting only for its turn (not for a `delay`): no need to wait for a sweep
68
+ claimNext: `
69
+ UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
70
+ 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))
71
+ AND ${firstOfKey} ORDER BY seq LIMIT 1 FOR UPDATE SKIP LOCKED)
49
72
  RETURNING job::text AS job, attempts`,
50
73
  extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
51
74
  backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2, claimed_at = NULL WHERE ${mine(3)}`,
@@ -54,7 +77,7 @@ const statements = {
54
77
  // 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
55
78
  // a call a newer one replaces (and one may be waiting with it)
56
79
  retry: `
57
- 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
80
+ 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
58
81
  WHERE id = $1 AND status = 'failed' RETURNING id`,
59
82
  fail: `
60
83
  INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
@@ -78,20 +101,21 @@ const statements = {
78
101
  /**
79
102
  * Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
80
103
  * a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
81
- * is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
82
- * its row being deleted runs it again.
104
+ * is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
105
+ * 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.
83
106
  *
84
107
  * ```ts
85
108
  * const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
86
- * startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
109
+ * work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
87
110
  * ```
88
111
  */
89
112
  export const databaseQueue = (options = {}) => storedJobs(statements, options);
90
113
  /**
91
- * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
92
- * until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
93
- * 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,
94
- * so a job can run twice, even at once.
114
+ * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, and stay
115
+ * rows until they're done: the queue gets a signal per job (per key, for a listener's `key`), and the consumer that gets
116
+ * one runs the row from the table and records how it went there. So tries, failed rows and a key's order are the
117
+ * table's, as with `databaseQueue`. A failed try gets a new signal for when its backoff ends; what no signal covers, the
118
+ * sweep runs 30 seconds past due. At least once: a consumer that dies after the work leaves the row to run again.
95
119
  *
96
120
  * ```ts
97
121
  * jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
@@ -1,7 +1,7 @@
1
1
  import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
2
2
  import type { FailedJobs, JobsAdapter } from "../core/types.ts";
3
3
  /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
4
- export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n claimed_at integer,\n last_error text,\n failed_at integer,\n replace_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
4
+ export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n claimed_at integer,\n last_error text,\n failed_at integer,\n unique_key text,\n order_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_order ON logic_jobs (order_key) WHERE status = 'pending';\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
5
5
  /** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
6
6
  export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
7
7
  /** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
@@ -15,11 +15,13 @@ CREATE TABLE logic_jobs (
15
15
  claimed_at integer,
16
16
  last_error text,
17
17
  failed_at integer,
18
- replace_key text,
18
+ unique_key text,
19
+ order_key text,
19
20
  created_at integer NOT NULL DEFAULT (${now})
20
21
  );
21
22
  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 UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;
24
+ CREATE INDEX logic_jobs_order ON logic_jobs (order_key) WHERE status = 'pending';
23
25
  CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
24
26
  CREATE TABLE logic_cron_runs (
25
27
  id text PRIMARY KEY NOT NULL,
@@ -27,35 +29,53 @@ CREATE TABLE logic_cron_runs (
27
29
  );
28
30
  CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
29
31
  `;
30
- const ids = "(SELECT value FROM json_each(?))";
31
- const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
32
+ const mine = `id = ? AND receipt = ? AND status = 'pending'`;
32
33
  const inSeconds = `${now} + cast(? * 1000 as integer)`;
34
+ /**
35
+ * 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
36
+ * started or came before it (`rowid`, the insert order). A failed row put back by `retry(id)` waits behind one that started.
37
+ */
38
+ const firstOfKey = `(order_key IS NULL OR attempts > 0 OR NOT EXISTS (
39
+ 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)))`;
33
40
  const statements = {
34
- // the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
35
- // 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
+ // a waiting row with this key: a call replaces it (its id, job and time: Oban's `replace`), a unique delivery is
42
+ // dropped. `json_each.key` is the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON
43
+ // CONFLICT from a join's ON
36
44
  insert: `
37
- INSERT INTO logic_jobs (id, job, available_at, replace_key)
38
- SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
45
+ INSERT INTO logic_jobs (id, job, available_at, unique_key, order_key)
46
+ SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'unique', value ->> 'order'
39
47
  FROM json_each(?) WHERE true ORDER BY json_each.key
40
- ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
48
+ ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
41
49
  DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
50
+ WHERE excluded.job ->> 'kind' = 'call'
42
51
  RETURNING id`,
43
52
  recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
44
53
  pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
45
54
  claimNew: `
46
55
  UPDATE logic_jobs SET attempts = 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
47
- WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
56
+ WHERE id = ? AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
48
57
  // no row locks to skip: SQLite has one writer at a time, and this statement is one write
49
58
  claimDue: `
50
59
  UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
51
- WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
60
+ WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} - cast(? * 1000 as integer) AND ${firstOfKey}
61
+ AND coalesce(nullif(?, ''), coalesce(job ->> 'queue', 'default')) = coalesce(job ->> 'queue', 'default') ORDER BY available_at LIMIT 1)
62
+ RETURNING job, attempts`,
63
+ claimOne: `
64
+ UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
65
+ WHERE id = ? AND status = 'pending' AND available_at <= ${now}
66
+ RETURNING job, attempts`,
67
+ // due, or never tried and waiting only for its turn (not for a `delay`): no need to wait for a sweep
68
+ claimNext: `
69
+ UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
70
+ 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))
71
+ AND ${firstOfKey} ORDER BY rowid LIMIT 1)
52
72
  RETURNING job, attempts`,
53
73
  extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
54
74
  backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ?, claimed_at = NULL WHERE ${mine} RETURNING id`,
55
75
  markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now}, claimed_at = NULL WHERE ${mine} RETURNING id`,
56
76
  remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
57
77
  retry: `
58
- 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
78
+ 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
59
79
  WHERE id = ? AND status = 'failed' RETURNING id`,
60
80
  fail: `
61
81
  INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
@@ -1,27 +1,37 @@
1
- import type { FailedJobs, FailedQuery, FailedRow, JobsAdapter, Runner, SweepResult } from "../core/types.ts";
1
+ import type { FailedJobs, FailedQuery, FailedRow, JobsAdapter, Runner, SweepOptions, SweepResult } from "../core/types.ts";
2
2
  /**
3
3
  * The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
4
4
  * lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
5
5
  * the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
6
6
  */
7
7
  export interface JobsSql {
8
- /** `(pickup, rows)`: rows is JSON `[{ id, job, at, key }]`, `at` in epoch ms or null (due now, a sweep's after `pickup` seconds). A waiting row with the same `key` becomes the new one. */
8
+ /**
9
+ * `(pickup, rows)`: rows is JSON `[{ id, job, at, unique, order }]`, `at` in epoch ms or null (due now, a sweep's
10
+ * after `pickup` seconds). A waiting row with the same `unique` is replaced by a call, and kept over a delivery.
11
+ */
9
12
  insert: string;
10
13
  /** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
11
14
  recordTicks: string;
12
15
  /** `()`: forgets ticks older than a day. */
13
16
  pruneTicks: string;
14
- /** `(receipt, lease, ids)`: the first claim, of rows nobody claimed. Returns `id`. */
17
+ /** `(receipt, lease, id)`: the first claim, of a row nobody claimed. Returns `id`. */
15
18
  claimNew: string;
16
- /** `(receipt, lease)`: claims the one row due first. Returns `job` (JSON text) and `attempts`. */
19
+ /**
20
+ * `(receipt, lease, grace, queue)`: claims the one row due first (`grace` seconds ago) in `queue` (`''`: any; a job
21
+ * without one is in `"default"`), the first open one of its key. Returns `job` (JSON text) and `attempts`.
22
+ */
17
23
  claimDue: string;
18
- /** `(lease, ids, receipt)`, on rows this receipt still owns, like the three below. */
24
+ /** `(receipt, lease, id)`: claims the row a signal names, if it's due. Returns `job` and `attempts`. */
25
+ claimOne: string;
26
+ /** `(receipt, lease, order)`: claims the next row of a key, due or waiting only for its turn. Returns `job` and `attempts`. */
27
+ claimNext: string;
28
+ /** `(lease, id, receipt)`, on a row this receipt still owns, like the three below. */
19
29
  extend: string;
20
- /** `(seconds, error, ids, receipt)` */
30
+ /** `(seconds, error, id, receipt)` */
21
31
  backOff: string;
22
- /** `(error, ids, receipt)` */
32
+ /** `(error, id, receipt)` */
23
33
  markFailed: string;
24
- /** `(ids, receipt)` */
34
+ /** `(id, receipt)` */
25
35
  remove: string;
26
36
  /** `(id)`: a failed row back in line. Returns `id`. */
27
37
  retry: string;
@@ -38,7 +48,7 @@ export interface JobsSql {
38
48
  /** `(id)`: deletes a failed row. Returns `job` (JSON text). */
39
49
  take: string;
40
50
  }
41
- export interface DatabaseQueueOptions {
51
+ export interface OutboxOptions {
42
52
  /**
43
53
  * Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
44
54
  * job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
@@ -48,20 +58,18 @@ export interface DatabaseQueueOptions {
48
58
  /** Seconds to wait after a failed try. Default `defaultBackoff`, the curve Graphile Worker uses. */
49
59
  backoff?: (attempt: number) => number;
50
60
  }
51
- /** `lease` is how long a send owns its jobs, and `backoff` the wait after a failed send. */
52
- export interface OutboxOptions extends DatabaseQueueOptions {
61
+ export interface DatabaseQueueOptions extends OutboxOptions {
53
62
  /**
54
- * Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
55
- * are its `attempts`.
63
+ * Who runs a job due now. `"request"` (default): the request that committed it, right after commit (after the
64
+ * response, with `waitUntil`), unless `work(registry)` runs in this process: then that loop takes it, and the request
65
+ * answers at once. `"worker"`: workers in other processes run every job, and requests only write rows.
56
66
  */
57
- maxAttempts?: number;
67
+ runIn?: "request" | "worker";
58
68
  }
59
69
  /** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
60
70
  export interface StoredJobs extends JobsAdapter {
61
71
  /** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
62
- sweep(runner: Runner, options?: {
63
- limit?: number;
64
- }): Promise<SweepResult>;
72
+ sweep(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
65
73
  /** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
66
74
  retry(id: string): Promise<boolean>;
67
75
  /** A page of failed rows, newest first. */
@@ -72,8 +80,8 @@ export interface StoredJobs extends JobsAdapter {
72
80
  /** Delete a failed row. `false` when no failed row has that id. */
73
81
  forget(id: string): Promise<boolean>;
74
82
  }
75
- /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
76
- export declare function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapter): StoredJobs;
83
+ /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it, the queue carries signals. */
84
+ export declare function storedJobs(sql: JobsSql, options: DatabaseQueueOptions, via?: JobsAdapter): StoredJobs;
77
85
  /**
78
86
  * Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
79
87
  * `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.