logic-sdk 0.7.1 → 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 (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -0,0 +1,108 @@
1
+ // The jobs table on SQLite (3.42 or later, for `unixepoch('subsec')`), in SQL. With Drizzle, import from
2
+ // `logic-sdk/drizzle/sqlite` instead: the same two functions, plus the table for your schema. Times are whole milliseconds since 1970, on SQLite's clock.
3
+ // Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
4
+ import { failedStore, storedJobs } from "./stored-jobs.js";
5
+ const now = `cast(unixepoch('subsec') * 1000 as integer)`;
6
+ /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
7
+ export const jobsSchema = `
8
+ CREATE TABLE logic_jobs (
9
+ id text PRIMARY KEY NOT NULL,
10
+ job text NOT NULL,
11
+ status text NOT NULL DEFAULT 'pending',
12
+ attempts integer NOT NULL DEFAULT 0,
13
+ available_at integer NOT NULL DEFAULT (${now}),
14
+ receipt text,
15
+ claimed_at integer,
16
+ last_error text,
17
+ failed_at integer,
18
+ unique_key text,
19
+ order_key text,
20
+ created_at integer NOT NULL DEFAULT (${now})
21
+ );
22
+ CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
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';
25
+ CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
26
+ CREATE TABLE logic_cron_runs (
27
+ id text PRIMARY KEY NOT NULL,
28
+ ran_at integer NOT NULL DEFAULT (${now})
29
+ );
30
+ CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
31
+ `;
32
+ const mine = `id = ? AND receipt = ? AND status = 'pending'`;
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)))`;
40
+ const statements = {
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
44
+ insert: `
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'
47
+ FROM json_each(?) WHERE true ORDER BY json_each.key
48
+ ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
49
+ DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
50
+ WHERE excluded.job ->> 'kind' = 'call'
51
+ RETURNING id`,
52
+ recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
53
+ pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
54
+ claimNew: `
55
+ UPDATE logic_jobs SET attempts = 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
56
+ WHERE id = ? AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
57
+ // no row locks to skip: SQLite has one writer at a time, and this statement is one write
58
+ claimDue: `
59
+ UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
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)
72
+ RETURNING job, attempts`,
73
+ extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
74
+ backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ?, claimed_at = NULL WHERE ${mine} RETURNING id`,
75
+ markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now}, claimed_at = NULL WHERE ${mine} RETURNING id`,
76
+ remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
77
+ retry: `
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
79
+ WHERE id = ? AND status = 'failed' RETURNING id`,
80
+ fail: `
81
+ INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
82
+ ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
83
+ RETURNING id`,
84
+ // each field by its type and value: a missing one isn't null, and true isn't 1
85
+ failed: `
86
+ WITH p(source, want, at, after_id) AS (SELECT NULLIF(?, ''), NULLIF(?, ''), CAST(NULLIF(?, '') AS INTEGER), NULLIF(?, ''))
87
+ SELECT j.id, j.job, j.last_error, j.failed_at FROM logic_jobs j, p
88
+ WHERE j.status = 'failed'
89
+ AND (p.source IS NULL OR coalesce(j.job ->> '$.listener', j.job ->> '$.cron', j.job ->> '$.fn') = p.source)
90
+ AND (p.want IS NULL OR NOT EXISTS (
91
+ SELECT 1 FROM json_each(p.want) AS w
92
+ WHERE json_type(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_type(w.value, '$.value')
93
+ OR json_extract(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_extract(w.value, '$.value')))
94
+ AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
95
+ ORDER BY j.failed_at DESC, j.id DESC
96
+ LIMIT ?`,
97
+ forget: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING id`,
98
+ take: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING job`,
99
+ };
100
+ /** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
101
+ export const databaseQueue = (options = {}) => storedJobs(statements, options);
102
+ /** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
103
+ export const outbox = (queue, options = {}) => storedJobs(statements, options, queue);
104
+ /**
105
+ * Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
106
+ * failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
107
+ */
108
+ export const failedJobs = () => failedStore(statements);
@@ -0,0 +1,89 @@
1
+ import type { FailedJobs, FailedQuery, FailedRow, JobsAdapter, Runner, SweepOptions, SweepResult } from "../core/types.ts";
2
+ /**
3
+ * The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
4
+ * lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
5
+ * the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
6
+ */
7
+ export interface JobsSql {
8
+ /**
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
+ */
12
+ insert: string;
13
+ /** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
14
+ recordTicks: string;
15
+ /** `()`: forgets ticks older than a day. */
16
+ pruneTicks: string;
17
+ /** `(receipt, lease, id)`: the first claim, of a row nobody claimed. Returns `id`. */
18
+ claimNew: string;
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
+ */
23
+ claimDue: string;
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. */
29
+ extend: string;
30
+ /** `(seconds, error, id, receipt)` */
31
+ backOff: string;
32
+ /** `(error, id, receipt)` */
33
+ markFailed: string;
34
+ /** `(id, receipt)` */
35
+ remove: string;
36
+ /** `(id)`: a failed row back in line. Returns `id`. */
37
+ retry: string;
38
+ /** `(id, job, error)`: a failed row, new or over the one there. */
39
+ fail: string;
40
+ /**
41
+ * `(source, matches, at, id, limit)`, `''` for "any": failed rows newest first, after the cursor row (`at`, `id`), each
42
+ * matching the source and every field in `matches` (JSON `[{ path, jsonPath, value }]`). Returns `id`, `job` (JSON
43
+ * text), `last_error` and `failed_at` (as `at` takes it back).
44
+ */
45
+ failed: string;
46
+ /** `(id)`: deletes a failed row. Returns `id`. */
47
+ forget: string;
48
+ /** `(id)`: deletes a failed row. Returns `job` (JSON text). */
49
+ take: string;
50
+ }
51
+ export interface OutboxOptions {
52
+ /**
53
+ * Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
54
+ * job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
55
+ * longer than that.
56
+ */
57
+ lease?: number;
58
+ /** Seconds to wait after a failed try. Default `defaultBackoff`, the curve Graphile Worker uses. */
59
+ backoff?: (attempt: number) => number;
60
+ }
61
+ export interface DatabaseQueueOptions extends OutboxOptions {
62
+ /**
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.
66
+ */
67
+ runIn?: "request" | "worker";
68
+ }
69
+ /** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
70
+ export interface StoredJobs extends JobsAdapter {
71
+ /** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
72
+ sweep(runner: Runner, options?: SweepOptions): Promise<SweepResult>;
73
+ /** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
74
+ retry(id: string): Promise<boolean>;
75
+ /** A page of failed rows, newest first. */
76
+ failed(query: FailedQuery): Promise<{
77
+ rows: FailedRow[];
78
+ cursor: string | null;
79
+ }>;
80
+ /** Delete a failed row. `false` when no failed row has that id. */
81
+ forget(id: string): Promise<boolean>;
82
+ }
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;
85
+ /**
86
+ * Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
87
+ * `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
88
+ */
89
+ export declare function failedStore(sql: JobsSql): FailedJobs;
@@ -0,0 +1,370 @@
1
+ // Jobs in the registry's database, written in the mutation's transaction: run from there (databaseQueue), or kept
2
+ // until a queue has them (outbox). The table's statements are SQL, one set per database (postgres.ts, sqlite.ts), and run through
3
+ // the database adapter's `query`, so this file knows no ORM and no driver.
4
+ import { defaultBackoff, storedUniqueKey } from "../core/jobs.js";
5
+ /**
6
+ * Seconds a job due now waits for the request that queued it before a sweep may take it (how soon a crash after
7
+ * commit is noticed). Behind an outbox, also how long past due a sweep leaves a row to its signal.
8
+ */
9
+ const PICKUP = 30;
10
+ /** A signal for a later time goes out this much later, so a clock ahead of the database's doesn't land it early. */
11
+ const SLACK = 1000;
12
+ /**
13
+ * Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer. Past it, a job that
14
+ * hangs is taken over like a crashed one. A longer job needs a `lease` that long.
15
+ */
16
+ const MAX_EXTEND = 15 * 60;
17
+ /**
18
+ * Seconds a queue consumer keeps running one key's jobs before it hands the rest to the next message: one busy key
19
+ * can't hold a consumer, and the messages behind it, until the platform stops it.
20
+ */
21
+ const DRAIN = 60;
22
+ /** A delivery's `key`: its jobs run one at a time, in insert order. */
23
+ const keyOf = (job) => (job.kind === "delivery" ? job.key : undefined);
24
+ /**
25
+ * The registry's database, taken at `createRegistry` (`sql: true`, so the core refuses one that doesn't run SQL): jobs
26
+ * are rows written in the mutation's transaction, so there's no other database they could go to. Laravel's `database`
27
+ * driver uses the app's connection too.
28
+ */
29
+ function registryDatabase(name) {
30
+ let database;
31
+ let workers = { takes: () => false, wake: () => { } };
32
+ return {
33
+ connect(setup) {
34
+ const { sql } = setup;
35
+ if (database && sql && database.db !== sql.db)
36
+ throw new Error(`[logic-sdk] ${name} is already connected to another registry's database: call it once per registry.`);
37
+ database = sql;
38
+ workers = setup.workers;
39
+ },
40
+ /** The loops running jobs in this process (`work()`). */
41
+ workers: () => workers,
42
+ get() {
43
+ if (!database)
44
+ throw new Error(`[logic-sdk] ${name} isn't connected: pass it to createRegistry.`);
45
+ return database;
46
+ },
47
+ };
48
+ }
49
+ /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it, the queue carries signals. */
50
+ export function storedJobs(sql, options, via) {
51
+ const name = via ? "outbox(queue)" : "databaseQueue()";
52
+ // its jobs would be signalled to a `deliver` that has nothing to do
53
+ if (via?.enqueue)
54
+ throw new Error(`[logic-sdk] outbox(queue) got a queue that writes its jobs in your transaction itself (it has \`enqueue\`): use it on its own, without an outbox.`);
55
+ const database = registryDatabase(name);
56
+ const lease = options.lease ?? 300;
57
+ const backoff = options.backoff ?? defaultBackoff;
58
+ const inWorker = options.runIn === "worker";
59
+ /**
60
+ * Whether this request leaves its jobs due now to workers: always with `runIn: "worker"`, and when a loop in this
61
+ * process takes every one of them. Asked the same way at insert and after commit, so the row is free for it at once.
62
+ */
63
+ const leaves = (jobs) => inWorker || jobs.filter((j) => !j.runAt).every((j) => database.workers().takes(j));
64
+ /** Outside a mutation: on the database itself. */
65
+ const query = (text, params) => database.get().query(database.get().db, text, params);
66
+ const list = (ids) => JSON.stringify(ids);
67
+ // These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
68
+ // newer runner's work. By receipt, not attempt number: `retry(id)` starts those again at 1.
69
+ const failedRows = rowsOfFailed(sql, query);
70
+ const markFailed = (job, claim, error) => query(sql.markFailed, [describe(error), job.id, claim.receipt]);
71
+ const backOff = (job, claim, seconds, error) => query(sql.backOff, [seconds, describe(error), job.id, claim.receipt]);
72
+ const remove = (job, claim) => query(sql.remove, [job.id, claim.receipt]);
73
+ /**
74
+ * While a job runs, its lease is extended, as Laravel Cloud does on SQS: a slow job stays its runner's, and a dead
75
+ * runner's job is free a lease later. Returns the stop, which waits for the extension on its way: landing after a
76
+ * backoff, it would replace the backoff.
77
+ */
78
+ function keepExtending(job, claim, runner) {
79
+ const until = Date.now() + MAX_EXTEND * 1000;
80
+ let extending = Promise.resolve();
81
+ const timer = setInterval(() => {
82
+ if (Date.now() >= until)
83
+ return clearInterval(timer);
84
+ extending = extending
85
+ .then(() => query(sql.extend, [lease, job.id, claim.receipt]))
86
+ .catch((e) => runner.report(e, job, claim.attempt));
87
+ }, (lease * 1000) / 3);
88
+ return () => {
89
+ clearInterval(timer);
90
+ return extending;
91
+ };
92
+ }
93
+ /**
94
+ * Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
95
+ * (tries left: back off, and behind an outbox signal the retry), or done and discarded (delete the row).
96
+ */
97
+ async function run(job, claim, runner) {
98
+ const stopExtending = keepExtending(job, claim, runner);
99
+ let outcome;
100
+ try {
101
+ outcome = await runner
102
+ .run(job, {
103
+ attempt: claim.attempt,
104
+ fail: async (error) => {
105
+ await markFailed(job, claim, error);
106
+ },
107
+ })
108
+ .finally(stopExtending);
109
+ }
110
+ catch (e) {
111
+ const seconds = backoff(claim.attempt);
112
+ await backOff(job, claim, seconds, e);
113
+ if (via)
114
+ await signal([{ ...job, runAt: new Date(Date.now() + seconds * 1000).toISOString() }], runner);
115
+ return "retrying";
116
+ }
117
+ if (outcome !== "failed")
118
+ await remove(job, claim);
119
+ return outcome;
120
+ }
121
+ /**
122
+ * Run a key's next jobs here, one by one, as they come free: after a job in the request, rather than leave them to a
123
+ * sweep (which runs them as they're due, one per claim), and for a consumer's signal behind an outbox. There, after
124
+ * `DRAIN` seconds the rest get one more signal.
125
+ */
126
+ async function runKey(key, runner) {
127
+ const until = Date.now() + DRAIN * 1000;
128
+ for (;;) {
129
+ const receipt = crypto.randomUUID();
130
+ const [row] = await query(sql.claimNext, [receipt, lease, key]);
131
+ if (!row)
132
+ return;
133
+ const job = JSON.parse(String(row.job));
134
+ await run(job, { receipt, attempt: Number(row.attempts) }, runner);
135
+ if (via && Date.now() >= until)
136
+ return signal([job], runner);
137
+ }
138
+ }
139
+ /**
140
+ * Behind an outbox, a consumer got a signal: run the row it names (with a `key`, the key's next jobs). The row is the
141
+ * truth, so a duplicate, a late one, or one whose row is gone or taken has nothing to do.
142
+ */
143
+ async function consume(job, runner) {
144
+ const key = keyOf(job);
145
+ if (key)
146
+ return runKey(key, runner);
147
+ const receipt = crypto.randomUUID();
148
+ const [row] = await query(sql.claimOne, [receipt, lease, job.id]);
149
+ if (row)
150
+ await run(JSON.parse(String(row.job)), { receipt, attempt: Number(row.attempts) }, runner);
151
+ }
152
+ /** Can `via` hold a signal until `at`? */
153
+ const canHold = (at) => via?.holds === true || (!!via?.holds && (at - Date.now()) / 1000 <= via.holds.max);
154
+ /**
155
+ * Behind an outbox, every job stays a row and the queue gets a signal: whoever gets one runs the row from the table
156
+ * (`consume`). One for a later time goes out only if the queue can hold it; a sweep runs the rest. A signal that
157
+ * doesn't go out is reported and the rows wait for a sweep. The runner the queue gets runs signals too, for a queue
158
+ * that runs what it's sent itself.
159
+ */
160
+ async function signal(jobs, runner) {
161
+ const signals = [];
162
+ for (const job of jobs) {
163
+ if (!job.runAt)
164
+ signals.push(job);
165
+ else if (canHold(Date.parse(job.runAt)))
166
+ signals.push({ ...job, runAt: new Date(Date.parse(job.runAt) + SLACK).toISOString() });
167
+ }
168
+ if (!signals.length)
169
+ return;
170
+ const consumer = {
171
+ ...runner,
172
+ run: async (job) => {
173
+ await consume(job, runner);
174
+ return "done";
175
+ },
176
+ };
177
+ try {
178
+ await via.deliver(signals, consumer);
179
+ }
180
+ catch (e) {
181
+ for (const job of signals)
182
+ runner.report(e, job);
183
+ }
184
+ }
185
+ /** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
186
+ async function recordTicks(tx, ticks) {
187
+ if (!ticks.length)
188
+ return new Set();
189
+ const first = await database.get().query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
190
+ await database.get().query(tx, sql.pruneTicks, []);
191
+ return new Set(first.map((row) => row.id));
192
+ }
193
+ /** The first claim of a job just committed, by the request that queued it, unless a sweep took it meanwhile. */
194
+ async function claimNew(job) {
195
+ const claim = { receipt: crypto.randomUUID(), attempt: 1 };
196
+ const rows = await query(sql.claimNew, [claim.receipt, lease, job.id]);
197
+ return rows.length ? claim : undefined;
198
+ }
199
+ return {
200
+ name,
201
+ retries: true, // a failed try backs off as a row
202
+ holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
203
+ replaces: true, // a waiting row is replaced in place; behind an outbox too, since every job stays a row
204
+ orders: true, // a key's jobs run from the table, in order; behind an outbox the queue only signals
205
+ queues: true, // a row's queue is in its job: a sweep takes the ones it's asked for, in that order
206
+ /** Takes the registry's database: it writes in the mutation's transaction. */
207
+ sql: true,
208
+ connect: (setup) => database.connect(setup),
209
+ /**
210
+ * Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
211
+ * request, or none when the request runs nothing (workers take it, or a signal, which the sweep's grace covers). Delayed:
212
+ * available from `runAt`. A cron's minute runs once: only ticks nobody recorded yet.
213
+ */
214
+ async enqueue(tx, jobs) {
215
+ const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
216
+ const kept = jobs.filter((j) => j.kind !== "cron" || firstTicks.has(j.id));
217
+ const rows = (await Promise.all(kept.map(async (j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, unique: (await storedUniqueKey(j)) ?? null, order: (j.kind === "delivery" && j.key) || null }))))
218
+ // in key order, so two transactions with the same unique keys lock them in the same order and can't deadlock
219
+ .sort((a, b) => byText(a.unique ?? "", b.unique ?? ""));
220
+ if (rows.length)
221
+ await database.get().query(tx, sql.insert, [via || leaves(kept) ? 0 : PICKUP, JSON.stringify(rows)]);
222
+ },
223
+ /**
224
+ * After commit, in this request. Behind an outbox: one signal per job, and one per key. Left to workers: wake this
225
+ * process's, if any (others poll). Otherwise each job due now is claimed just before it runs, so a slow or dead one
226
+ * doesn't spend the others' attempt; what isn't claimed yet when the process dies is a sweep's, as a first try.
227
+ */
228
+ async deliver(jobs, runner) {
229
+ if (via) {
230
+ const keys = new Set();
231
+ const firsts = jobs.filter((job) => {
232
+ const key = keyOf(job);
233
+ if (!key)
234
+ return true;
235
+ if (keys.has(key))
236
+ return false;
237
+ keys.add(key);
238
+ return true;
239
+ });
240
+ return signal(firsts, runner);
241
+ }
242
+ const due = jobs.filter((j) => !j.runAt);
243
+ if (leaves(jobs)) {
244
+ if (due.length)
245
+ database.workers().wake(due.length);
246
+ return;
247
+ }
248
+ for (const job of due) {
249
+ try {
250
+ const claim = await claimNew(job);
251
+ if (!claim)
252
+ continue;
253
+ await run(job, claim, runner);
254
+ const key = keyOf(job);
255
+ if (key)
256
+ await runKey(key, runner); // its key's next ones, rather than leave them to a sweep
257
+ }
258
+ catch (e) {
259
+ runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
260
+ }
261
+ }
262
+ },
263
+ /**
264
+ * What's due (retries, delayed jobs, what a crash left behind), claimed one at a time, so every claim gets a full
265
+ * lease. Behind an outbox, only rows `PICKUP` seconds past due: until then they're their signal's.
266
+ */
267
+ async sweep(runner, { limit = 100, queues } = {}) {
268
+ const result = { done: 0, failed: 0, discarded: 0, retrying: 0 };
269
+ // in the order given: each claim takes the first queue with a job due, as a worker listing queues does
270
+ const order = queues?.length ? queues : [""];
271
+ for (let i = 0; i < limit; i++) {
272
+ const receipt = crypto.randomUUID();
273
+ let row;
274
+ for (const queue of order) {
275
+ [row] = await query(sql.claimDue, [receipt, lease, via ? PICKUP : 0, queue]);
276
+ if (row)
277
+ break;
278
+ }
279
+ if (!row)
280
+ break;
281
+ const job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
282
+ const attempt = Number(row.attempts);
283
+ try {
284
+ result[await run(job, { receipt, attempt }, runner)]++;
285
+ }
286
+ catch (e) {
287
+ runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
288
+ }
289
+ }
290
+ return result;
291
+ },
292
+ /** Failed rows only: a pending one belongs to its runner or a sweep, and resetting it could run it twice at once. */
293
+ async retry(id) {
294
+ return (await query(sql.retry, [id])).length > 0;
295
+ },
296
+ ...(via ? { consume } : {}),
297
+ failed: failedRows.failed,
298
+ forget: failedRows.forget,
299
+ };
300
+ }
301
+ async function listFailed(sql, query, { source, scope, limit, cursor }) {
302
+ const [at, after] = cursor === undefined ? ["", ""] : cursorOf(cursor);
303
+ const matches = scope?.map(({ path, value }) => {
304
+ if (path.some((key) => !key || key.includes('"')))
305
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) can't match the field ${JSON.stringify(path.join("."))}.`);
306
+ return { path, jsonPath: `$${path.map((key) => `."${key}"`).join("")}`, value };
307
+ });
308
+ const found = await query(sql.failed, [source ?? "", matches ? JSON.stringify(matches) : "", at, after, limit + 1]);
309
+ const page = found.slice(0, limit);
310
+ const last = page.at(-1);
311
+ return {
312
+ rows: page.map((row) => ({
313
+ id: String(row.id),
314
+ job: JSON.parse(String(row.job)), // JSON text, on every driver
315
+ error: String(row.last_error ?? ""),
316
+ failedAt: new Date(/^\d+$/.test(String(row.failed_at)) ? Number(row.failed_at) : Date.parse(String(row.failed_at))).toISOString(), // SQLite: ms; Postgres: ISO text
317
+ })),
318
+ cursor: found.length > limit && last ? JSON.stringify([String(last.failed_at), String(last.id)]) : null,
319
+ };
320
+ }
321
+ /**
322
+ * Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
323
+ * `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
324
+ */
325
+ export function failedStore(sql) {
326
+ const database = registryDatabase("failedJobs()");
327
+ const query = (text, params) => database.get().query(database.get().db, text, params);
328
+ return {
329
+ name: "failedJobs()",
330
+ sql: true,
331
+ connect: (setup) => database.connect(setup),
332
+ ...rowsOfFailed(sql, query),
333
+ };
334
+ }
335
+ /** Failed rows in the jobs table: kept, listed, taken back for a retry, forgotten. A waiting or running row is never touched. */
336
+ function rowsOfFailed(sql, query) {
337
+ return {
338
+ async fail(job, error) {
339
+ await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
340
+ },
341
+ /**
342
+ * Newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page skips none.
343
+ * One row past the limit says there's another page.
344
+ */
345
+ failed: (q) => listFailed(sql, query, q),
346
+ async take(id) {
347
+ const [row] = await query(sql.take, [id]);
348
+ return row ? JSON.parse(String(row.job)) : undefined;
349
+ },
350
+ async forget(id) {
351
+ return (await query(sql.forget, [id])).length > 0;
352
+ },
353
+ };
354
+ }
355
+ /** A `failed` page's cursor: the last row's `failed_at` (as the database gave it) and id. */
356
+ function cursorOf(cursor) {
357
+ let parsed;
358
+ try {
359
+ parsed = JSON.parse(cursor);
360
+ }
361
+ catch {
362
+ parsed = undefined;
363
+ }
364
+ if (!Array.isArray(parsed) || parsed.length !== 2 || !parsed.every((part) => typeof part === "string" && part))
365
+ throw new Error(`[logic-sdk] jobs.failed({ cursor }) takes the cursor of the page before (got ${JSON.stringify(cursor)}).`);
366
+ return parsed;
367
+ }
368
+ /** Not `localeCompare`: processes with another locale would lock in another order. */
369
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
370
+ const describe = (e) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
package/dist/ai.d.ts CHANGED
@@ -1,32 +1 @@
1
- import { type Tool } from "ai";
2
- import { type Caller, type FnIn, type FnOut, type ForFunctions, type PublishableFn, type ScopeOfFn } from "./index.ts";
3
- /**
4
- * What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
5
- * `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
6
- */
7
- export type AIMeta = ForFunctions<{
8
- ai?: {
9
- /** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
10
- description?: string;
11
- };
12
- }>;
13
- export interface AIToolOptions {
14
- /** Overrides `meta.ai.description` for this tool. */
15
- description?: string;
16
- /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
17
- onError?: (error: unknown) => void;
18
- }
19
- /**
20
- * One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
21
- * and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
22
- * `authorize`: the model acts for someone else.
23
- *
24
- * ```ts
25
- * const caller = registry.as(await scopeFrom(request));
26
- * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
27
- * ```
28
- *
29
- * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
30
- * to `onError` and the model gets "internal_error", so internals never land in its context.
31
- */
32
- export declare function toAITool<F extends PublishableFn>(caller: Caller<ScopeOfFn<F>>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
1
+ export { toAITool, type AIMeta, type AIToolOptions } from "./integrations/ai.ts";
package/dist/ai.js CHANGED
@@ -1,40 +1 @@
1
- import { jsonSchema, tool } from "ai";
2
- import { isDomainError } from "./index.js";
3
- /** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
4
- const aiMeta = (fn) => fn.meta?.ai;
5
- /** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
6
- const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
7
- /**
8
- * One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
9
- * and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
10
- * `authorize`: the model acts for someone else.
11
- *
12
- * ```ts
13
- * const caller = registry.as(await scopeFrom(request));
14
- * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
15
- * ```
16
- *
17
- * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
18
- * to `onError` and the model gets "internal_error", so internals never land in its context.
19
- */
20
- export function toAITool(caller, fn, options = {}) {
21
- if (!fn.authorize)
22
- throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
23
- const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
24
- return tool({
25
- description: options.description ?? aiMeta(fn)?.description,
26
- inputSchema: fn.input ?? noInput,
27
- outputSchema: fn.output,
28
- async execute(input, { abortSignal }) {
29
- try {
30
- return await caller.run(fn, input, { signal: abortSignal });
31
- }
32
- catch (e) {
33
- if (isDomainError(e))
34
- throw e;
35
- onError(e);
36
- throw new Error("internal_error");
37
- }
38
- },
39
- });
40
- }
1
+ export { toAITool } from "./integrations/ai.js";