logic-sdk 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +9 -9
  2. package/dist/adapters/cloudflare-queue.d.ts +14 -0
  3. package/dist/adapters/cloudflare-queue.js +48 -0
  4. package/dist/adapters/drizzle-pg.d.ts +250 -0
  5. package/dist/adapters/drizzle-pg.js +69 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +257 -0
  7. package/dist/adapters/drizzle-sqlite.js +196 -0
  8. package/dist/adapters/pg-boss.d.ts +45 -0
  9. package/dist/adapters/pg-boss.js +180 -0
  10. package/dist/adapters/postgres.d.ts +32 -0
  11. package/dist/adapters/postgres.js +105 -0
  12. package/dist/adapters/sqlite.d.ts +13 -0
  13. package/dist/adapters/sqlite.js +88 -0
  14. package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
  15. package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
  16. package/dist/ai.d.ts +1 -32
  17. package/dist/ai.js +1 -40
  18. package/dist/cloudflare.d.ts +2 -55
  19. package/dist/cloudflare.js +2 -85
  20. package/dist/core/in-process.d.ts +9 -0
  21. package/dist/core/in-process.js +17 -0
  22. package/dist/core/jobs.d.ts +57 -0
  23. package/dist/{jobs.js → core/jobs.js} +161 -42
  24. package/dist/core/registry.d.ts +120 -0
  25. package/dist/core/registry.js +503 -0
  26. package/dist/core/testing.d.ts +75 -0
  27. package/dist/core/testing.js +230 -0
  28. package/dist/{types.d.ts → core/types.d.ts} +224 -49
  29. package/dist/drizzle/pg.d.ts +3 -236
  30. package/dist/drizzle/pg.js +2 -67
  31. package/dist/drizzle/sqlite.d.ts +3 -242
  32. package/dist/drizzle/sqlite.js +2 -194
  33. package/dist/fetch.d.ts +1 -19
  34. package/dist/fetch.js +1 -30
  35. package/dist/hosts/cloudflare.d.ts +42 -0
  36. package/dist/hosts/cloudflare.js +39 -0
  37. package/dist/hosts/node.d.ts +26 -0
  38. package/dist/hosts/node.js +76 -0
  39. package/dist/hosts/pg-boss.d.ts +22 -0
  40. package/dist/hosts/pg-boss.js +55 -0
  41. package/dist/index.d.ts +5 -124
  42. package/dist/index.js +4 -495
  43. package/dist/integrations/ai.d.ts +32 -0
  44. package/dist/integrations/ai.js +40 -0
  45. package/dist/integrations/fetch.d.ts +19 -0
  46. package/dist/integrations/fetch.js +30 -0
  47. package/dist/integrations/orpc.d.ts +22 -0
  48. package/dist/integrations/orpc.js +37 -0
  49. package/dist/node.d.ts +1 -26
  50. package/dist/node.js +1 -76
  51. package/dist/orpc.d.ts +1 -21
  52. package/dist/orpc.js +1 -37
  53. package/dist/pg-boss.d.ts +2 -55
  54. package/dist/pg-boss.js +2 -211
  55. package/dist/postgres.d.ts +2 -28
  56. package/dist/postgres.js +1 -82
  57. package/dist/sqlite.d.ts +2 -9
  58. package/dist/sqlite.js +1 -65
  59. package/dist/testing.d.ts +1 -67
  60. package/dist/testing.js +1 -214
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +7 -6
  63. package/src/adapters/cloudflare-queue.ts +56 -0
  64. package/src/adapters/drizzle-pg.ts +108 -0
  65. package/src/adapters/drizzle-sqlite.ts +234 -0
  66. package/src/adapters/pg-boss.ts +195 -0
  67. package/src/adapters/postgres.ts +112 -0
  68. package/src/adapters/sqlite.ts +96 -0
  69. package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
  70. package/src/ai.ts +1 -62
  71. package/src/cloudflare.ts +2 -107
  72. package/src/core/in-process.ts +18 -0
  73. package/src/{jobs.ts → core/jobs.ts} +166 -43
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +219 -46
  77. package/src/drizzle/pg.ts +3 -110
  78. package/src/drizzle/sqlite.ts +3 -236
  79. package/src/fetch.ts +1 -31
  80. package/src/hosts/cloudflare.ts +54 -0
  81. package/src/hosts/node.ts +99 -0
  82. package/src/hosts/pg-boss.ts +71 -0
  83. package/src/index.ts +17 -655
  84. package/src/integrations/ai.ts +63 -0
  85. package/src/integrations/fetch.ts +31 -0
  86. package/src/integrations/orpc.ts +47 -0
  87. package/src/node.ts +1 -99
  88. package/src/orpc.ts +1 -46
  89. package/src/pg-boss.ts +2 -242
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -288
  93. package/dist/jobs.d.ts +0 -44
  94. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  95. /package/dist/{errors.js → core/errors.js} +0 -0
  96. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  97. /package/dist/{schedule.js → core/schedule.js} +0 -0
  98. /package/dist/{types.js → core/types.js} +0 -0
  99. /package/src/{errors.ts → core/errors.ts} +0 -0
  100. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -0,0 +1,257 @@
1
+ import { type SQL } from "drizzle-orm";
2
+ import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
3
+ /** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
4
+ interface SyncSqlite {
5
+ all<T>(query: SQL): T[];
6
+ run(query: SQL): unknown;
7
+ $client: {
8
+ close(): unknown;
9
+ };
10
+ }
11
+ /** What mutations get: a connection of their own, inside the transaction the adapter opened. */
12
+ export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
13
+ /** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
14
+ export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
15
+ /** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
16
+ export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
17
+ /**
18
+ * Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
19
+ * `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
20
+ * ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
21
+ *
22
+ * ```ts
23
+ * const database = drizzleAdapter(() => drizzle("app.db"));
24
+ * ```
25
+ */
26
+ export declare function drizzleAdapter<Db extends SyncSqlite>(open: () => Db): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>>;
27
+ /**
28
+ * The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
29
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
30
+ * job; done rows are deleted, failed ones stay so you can query them and `retry` them.
31
+ */
32
+ export declare const jobsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
33
+ name: "logic_jobs";
34
+ schema: undefined;
35
+ columns: {
36
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
37
+ name: string;
38
+ tableName: "logic_jobs";
39
+ dataType: "string";
40
+ data: string;
41
+ driverParam: string;
42
+ notNull: true;
43
+ hasDefault: false;
44
+ isPrimaryKey: true;
45
+ isAutoincrement: false;
46
+ hasRuntimeDefault: false;
47
+ enumValues: [string, ...string[]];
48
+ baseColumn: never;
49
+ identity: undefined;
50
+ generated: undefined;
51
+ }, {}>;
52
+ job: import("drizzle-orm/sqlite-core").SQLiteColumn<{
53
+ name: string;
54
+ tableName: "logic_jobs";
55
+ dataType: "object json";
56
+ data: Job;
57
+ driverParam: string;
58
+ notNull: true;
59
+ hasDefault: false;
60
+ isPrimaryKey: false;
61
+ isAutoincrement: false;
62
+ hasRuntimeDefault: false;
63
+ enumValues: undefined;
64
+ baseColumn: never;
65
+ identity: undefined;
66
+ generated: undefined;
67
+ }, {}>;
68
+ status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
69
+ name: string;
70
+ tableName: "logic_jobs";
71
+ dataType: "string";
72
+ data: "failed" | "pending";
73
+ driverParam: string;
74
+ notNull: true;
75
+ hasDefault: true;
76
+ isPrimaryKey: false;
77
+ isAutoincrement: false;
78
+ hasRuntimeDefault: false;
79
+ enumValues: [string, ...string[]];
80
+ baseColumn: never;
81
+ identity: undefined;
82
+ generated: undefined;
83
+ }, {}>;
84
+ attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
85
+ name: string;
86
+ tableName: "logic_jobs";
87
+ dataType: "number int53";
88
+ data: number;
89
+ driverParam: number;
90
+ notNull: true;
91
+ hasDefault: true;
92
+ isPrimaryKey: false;
93
+ isAutoincrement: false;
94
+ hasRuntimeDefault: false;
95
+ enumValues: undefined;
96
+ baseColumn: never;
97
+ identity: undefined;
98
+ generated: undefined;
99
+ }, {}>;
100
+ availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
101
+ name: string;
102
+ tableName: "logic_jobs";
103
+ dataType: "object date";
104
+ data: Date;
105
+ driverParam: number;
106
+ notNull: true;
107
+ hasDefault: true;
108
+ isPrimaryKey: false;
109
+ isAutoincrement: false;
110
+ hasRuntimeDefault: false;
111
+ enumValues: undefined;
112
+ baseColumn: never;
113
+ identity: undefined;
114
+ generated: undefined;
115
+ }, {}>;
116
+ receipt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
117
+ name: string;
118
+ tableName: "logic_jobs";
119
+ dataType: "string";
120
+ data: string;
121
+ driverParam: string;
122
+ notNull: false;
123
+ hasDefault: false;
124
+ isPrimaryKey: false;
125
+ isAutoincrement: false;
126
+ hasRuntimeDefault: false;
127
+ enumValues: [string, ...string[]];
128
+ baseColumn: never;
129
+ identity: undefined;
130
+ generated: undefined;
131
+ }, {}>;
132
+ claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
133
+ name: string;
134
+ tableName: "logic_jobs";
135
+ dataType: "object date";
136
+ data: Date;
137
+ driverParam: number;
138
+ notNull: false;
139
+ hasDefault: false;
140
+ isPrimaryKey: false;
141
+ isAutoincrement: false;
142
+ hasRuntimeDefault: false;
143
+ enumValues: undefined;
144
+ baseColumn: never;
145
+ identity: undefined;
146
+ generated: undefined;
147
+ }, {}>;
148
+ lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
149
+ name: string;
150
+ tableName: "logic_jobs";
151
+ dataType: "string";
152
+ data: string;
153
+ driverParam: string;
154
+ notNull: false;
155
+ hasDefault: false;
156
+ isPrimaryKey: false;
157
+ isAutoincrement: false;
158
+ hasRuntimeDefault: false;
159
+ enumValues: [string, ...string[]];
160
+ baseColumn: never;
161
+ identity: undefined;
162
+ generated: undefined;
163
+ }, {}>;
164
+ failedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
165
+ name: string;
166
+ tableName: "logic_jobs";
167
+ dataType: "object date";
168
+ data: Date;
169
+ driverParam: number;
170
+ notNull: false;
171
+ hasDefault: false;
172
+ isPrimaryKey: false;
173
+ isAutoincrement: false;
174
+ hasRuntimeDefault: false;
175
+ enumValues: undefined;
176
+ baseColumn: never;
177
+ identity: undefined;
178
+ generated: undefined;
179
+ }, {}>;
180
+ replaceKey: 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
+ createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
197
+ name: string;
198
+ tableName: "logic_jobs";
199
+ dataType: "object date";
200
+ data: Date;
201
+ driverParam: number;
202
+ notNull: true;
203
+ hasDefault: true;
204
+ isPrimaryKey: false;
205
+ isAutoincrement: false;
206
+ hasRuntimeDefault: false;
207
+ enumValues: undefined;
208
+ baseColumn: never;
209
+ identity: undefined;
210
+ generated: undefined;
211
+ }, {}>;
212
+ };
213
+ dialect: 'sqlite';
214
+ isAlias: false;
215
+ }>;
216
+ /** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
217
+ export declare const cronRunsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
218
+ name: "logic_cron_runs";
219
+ schema: undefined;
220
+ columns: {
221
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
222
+ name: string;
223
+ tableName: "logic_cron_runs";
224
+ dataType: "string";
225
+ data: string;
226
+ driverParam: string;
227
+ notNull: true;
228
+ hasDefault: false;
229
+ isPrimaryKey: true;
230
+ isAutoincrement: false;
231
+ hasRuntimeDefault: false;
232
+ enumValues: [string, ...string[]];
233
+ baseColumn: never;
234
+ identity: undefined;
235
+ generated: undefined;
236
+ }, {}>;
237
+ ranAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
238
+ name: string;
239
+ tableName: "logic_cron_runs";
240
+ dataType: "object date";
241
+ data: Date;
242
+ driverParam: number;
243
+ notNull: true;
244
+ hasDefault: true;
245
+ isPrimaryKey: false;
246
+ isAutoincrement: false;
247
+ hasRuntimeDefault: false;
248
+ enumValues: undefined;
249
+ baseColumn: never;
250
+ identity: undefined;
251
+ generated: undefined;
252
+ }, {}>;
253
+ };
254
+ dialect: 'sqlite';
255
+ isAlias: false;
256
+ }>;
257
+ export {};
@@ -0,0 +1,196 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
3
+ import { causes } from "../core/errors.js";
4
+ /** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
5
+ const BUSY_TIMEOUT = 5000;
6
+ /**
7
+ * Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
8
+ * `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
9
+ * ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
10
+ *
11
+ * ```ts
12
+ * const database = drizzleAdapter(() => drizzle("app.db"));
13
+ * ```
14
+ */
15
+ export function drizzleAdapter(open) {
16
+ const reader = open();
17
+ checkOpen(open, reader);
18
+ exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
19
+ exec(reader, "PRAGMA query_only = ON");
20
+ const takeTurn = turns();
21
+ const transaction = (fn) => takeTurn(async (restartClock) => {
22
+ const tx = await begin(open, restartClock);
23
+ try {
24
+ const out = await fn(tx);
25
+ exec(tx, "COMMIT");
26
+ return out;
27
+ }
28
+ catch (e) {
29
+ undo(tx, "ROLLBACK");
30
+ throw e;
31
+ }
32
+ finally {
33
+ tx.$client.close();
34
+ }
35
+ });
36
+ return {
37
+ db: reader,
38
+ transaction,
39
+ nest: (tx) => savepoints(tx),
40
+ retryable: isBusy,
41
+ // on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
42
+ query: async (client, text, params) => client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
43
+ };
44
+ }
45
+ /** Transactions inside a transaction, as savepoints: the test registry's. */
46
+ function savepoints(tx) {
47
+ const takeTurn = turns();
48
+ return {
49
+ db: tx,
50
+ transaction: (fn) => takeTurn(async () => {
51
+ exec(tx, "SAVEPOINT logic_sdk");
52
+ try {
53
+ const out = await fn(tx);
54
+ exec(tx, "RELEASE logic_sdk");
55
+ return out;
56
+ }
57
+ catch (e) {
58
+ undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
59
+ throw e;
60
+ }
61
+ }),
62
+ nest: savepoints,
63
+ query: async (client, text, params) => rowsOf(client, text, params),
64
+ };
65
+ }
66
+ const exec = (db, text) => db.run(sql.raw(text));
67
+ /** SQL text with `?` parameters as a Drizzle query. */
68
+ const toSql = (text, params) => sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
69
+ const rowsOf = (db, text, params) => db.all(toSql(text, params));
70
+ /** SQLite rolls some failures back by itself (a full disk, `RAISE(ROLLBACK)`): then there's nothing to undo, and the error that did it is the one to report. */
71
+ function undo(db, ...statements) {
72
+ try {
73
+ for (const statement of statements)
74
+ exec(db, statement);
75
+ }
76
+ catch { }
77
+ }
78
+ /** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
79
+ function checkOpen(open, reader) {
80
+ const another = open();
81
+ if (another.$client === reader.$client)
82
+ throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
83
+ const [main] = another.all(sql `PRAGMA database_list`);
84
+ another.$client.close();
85
+ if (!main?.file)
86
+ throw new Error("[logic-sdk] drizzleAdapter needs SQLite on a disk: an in-memory database is a different one on each connection. Use a temporary file in tests.");
87
+ }
88
+ /**
89
+ * A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
90
+ * since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
91
+ */
92
+ async function begin(open, restartClock) {
93
+ const deadline = Date.now() + BUSY_TIMEOUT;
94
+ for (;;) {
95
+ restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
96
+ let tx;
97
+ try {
98
+ tx = open();
99
+ exec(tx, "PRAGMA busy_timeout = 0");
100
+ exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
101
+ exec(tx, "BEGIN IMMEDIATE");
102
+ return tx;
103
+ }
104
+ catch (e) {
105
+ tx?.$client.close();
106
+ if (!isBusy(e) || Date.now() >= deadline)
107
+ throw e;
108
+ }
109
+ await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
110
+ }
111
+ }
112
+ /**
113
+ * One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
114
+ * when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
115
+ */
116
+ function turns() {
117
+ let last = Promise.resolve();
118
+ let startedAt = 0;
119
+ const restartClock = () => {
120
+ startedAt = Date.now();
121
+ };
122
+ return async (work) => {
123
+ const arrived = Date.now();
124
+ const ahead = last;
125
+ const done = Promise.withResolvers();
126
+ last = ahead.then(() => done.promise);
127
+ try {
128
+ const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
129
+ while (!(await settlesBy(ahead, giveUpAt()))) {
130
+ // the one ahead may have changed while we waited: the line moved
131
+ if (Date.now() >= giveUpAt())
132
+ throw new Error(HELD);
133
+ }
134
+ restartClock();
135
+ return await work(restartClock);
136
+ }
137
+ finally {
138
+ done.resolve();
139
+ }
140
+ };
141
+ }
142
+ const HELD = "[logic-sdk] Waited 5 seconds for a transaction in this process, and SQLite writes one at a time. Does a mutation await registry.as(scope).run instead of ctx.run, or do slow work that belongs in an action? In tests, is a t.begin() still open?";
143
+ /** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
144
+ const settlesBy = (promise, time) => new Promise((resolve) => {
145
+ const timer = setTimeout(() => resolve(false), time - Date.now());
146
+ void promise.then(() => {
147
+ clearTimeout(timer);
148
+ resolve(true);
149
+ });
150
+ });
151
+ /** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
152
+ function isBusy(error) {
153
+ for (const e of causes(error))
154
+ if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message)))
155
+ return true;
156
+ return false;
157
+ }
158
+ const now = sql `(cast(unixepoch('subsec') * 1000 as integer))`;
159
+ /**
160
+ * The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
161
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
162
+ * job; done rows are deleted, failed ones stay so you can query them and `retry` them.
163
+ */
164
+ export const jobsTable = sqliteTable("logic_jobs", {
165
+ /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
166
+ id: text("id").primaryKey(),
167
+ job: text("job", { mode: "json" }).$type().notNull(),
168
+ /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
169
+ status: text("status").$type().notNull().default("pending"),
170
+ /** Incremented when a runner claims it, so a crash still uses an attempt. */
171
+ attempts: integer("attempts").notNull().default(0),
172
+ /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
173
+ availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
174
+ /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
175
+ receipt: text("receipt"),
176
+ /** When the claim that owns it started: set while a try runs, empty while it waits (first, or after a backoff). */
177
+ claimedAt: integer("claimed_at", { mode: "timestamp_ms" }),
178
+ /** The last failure, with its stack. */
179
+ lastError: text("last_error"),
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"),
183
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
184
+ }, (t) => [
185
+ 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`),
188
+ // `registry.jobs.failed()` pages newest first by (failed_at, id)
189
+ index("logic_jobs_failed").on(t.failedAt, t.id).where(sql `status = 'failed'`),
190
+ ]);
191
+ /** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
192
+ export const cronRunsTable = sqliteTable("logic_cron_runs", {
193
+ /** The cron job's id, `<cron id>@<minute>`. */
194
+ id: text("id").primaryKey(),
195
+ ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
196
+ }, (t) => [index("logic_cron_runs_ran_at").on(t.ranAt)]);
@@ -0,0 +1,45 @@
1
+ import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
2
+ import type { ForListeners, JobsAdapter } from "../core/types.ts";
3
+ /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
4
+ export interface PgBossTuning {
5
+ /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
6
+ queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
7
+ /** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
8
+ worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
9
+ }
10
+ /**
11
+ * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
12
+ * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
13
+ * listener's `attempts`, and the other adapters ignore it.
14
+ */
15
+ export type PgBossMeta = ForListeners<{
16
+ pgBoss?: PgBossTuning;
17
+ }>;
18
+ /** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
19
+ export declare const PREFIX = "logic-sdk.";
20
+ /** A listener's or cron's queue: `logic-sdk.notifications.send`. */
21
+ export declare const queueName: (id: string) => string;
22
+ /** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
23
+ export declare const CALLS_QUEUE = "logic-sdk.calls";
24
+ /** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
25
+ export declare const queueConfig: (queue: PgBossTuning["queue"]) => {
26
+ expireInSeconds?: number;
27
+ retentionSeconds?: number;
28
+ deleteAfterSeconds?: number;
29
+ retryDelay?: number;
30
+ retryDelayMax?: number;
31
+ partition?: boolean;
32
+ deadLetter?: string;
33
+ warningQueueSize?: number;
34
+ heartbeatSeconds?: number;
35
+ notify?: boolean;
36
+ retryBackoff: boolean;
37
+ };
38
+ /** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
39
+ export declare const tuningOf: (meta: Readonly<Record<string, unknown>> | undefined) => PgBossTuning | undefined;
40
+ /**
41
+ * The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
42
+ * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
43
+ */
44
+ export declare function pgBossId(id: string): string;
45
+ export declare function pgBoss(boss: PgBoss): JobsAdapter;
@@ -0,0 +1,180 @@
1
+ /// <reference types="node" />
2
+ // pg-boss runs on Node (`pg`, `node:events`), so this subpath may too; the core stays runtime-neutral.
3
+ import { createHash } from "node:crypto";
4
+ import {} from "pg-boss";
5
+ import { storedReplaceKey } from "../core/jobs.js";
6
+ /** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
7
+ export const PREFIX = "logic-sdk.";
8
+ /** A listener's or cron's queue: `logic-sdk.notifications.send`. */
9
+ export const queueName = (id) => `${PREFIX}${id}`;
10
+ /** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
11
+ export const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
12
+ /** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
13
+ const queueOf = (job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
14
+ /** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
15
+ export const queueConfig = (queue) => ({ ...queue, retryBackoff: true });
16
+ /** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
17
+ export const tuningOf = (meta) => meta?.pgBoss;
18
+ // A UUID of our own, so the v5 ids below can't collide with anyone else's.
19
+ const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
20
+ /**
21
+ * The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
22
+ * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
23
+ */
24
+ export function pgBossId(id) {
25
+ const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
26
+ hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
27
+ hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
28
+ const hex = hash.toString("hex", 0, 16);
29
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
30
+ }
31
+ /**
32
+ * A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
33
+ * never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
34
+ * left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
35
+ * at pickup. A last try that throws is `deadletter`, so it never uses the spare.
36
+ */
37
+ const rowOf = (job, replaceKey) => ({
38
+ id: pgBossId(job.id),
39
+ data: job,
40
+ startAfter: job.runAt,
41
+ retryLimit: job.attempts,
42
+ retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
43
+ singletonKey: replaceKey,
44
+ });
45
+ export function pgBoss(boss) {
46
+ let database;
47
+ /** pg-boss's SQL on your mutation's transaction, through your database adapter's `query`: any ORM that runs SQL. */
48
+ const inTx = (tx) => ({
49
+ executeSql: async (text, values = []) => {
50
+ const rows = await database.query(tx, text, values);
51
+ return { rows };
52
+ },
53
+ });
54
+ const queueOptions = new Map();
55
+ /**
56
+ * pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
57
+ * new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
58
+ * on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
59
+ */
60
+ async function inQueue(name, write) {
61
+ try {
62
+ await write();
63
+ }
64
+ catch (error) {
65
+ if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND"))
66
+ throw error;
67
+ await boss.createQueue(name, queueConfig(queueOptions.get(name)));
68
+ await write();
69
+ }
70
+ }
71
+ /**
72
+ * The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
73
+ * a job in `retry` has started, and isn't touched.
74
+ */
75
+ async function replaceWaiting(db, keys) {
76
+ // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
77
+ for (const key of [...new Set(keys)].sort()) {
78
+ // one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
79
+ await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
80
+ // a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
81
+ const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
82
+ if (!locked.length)
83
+ continue;
84
+ const queued = await boss.findJobs(CALLS_QUEUE, { key, queued: true, db });
85
+ const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
86
+ if (waiting.length)
87
+ await boss.deleteJob(CALLS_QUEUE, waiting, { db });
88
+ }
89
+ }
90
+ return {
91
+ name: "pgBoss(boss)",
92
+ retries: true, // retryLimit, stamped from the job's attempts
93
+ sql: true, // pg-boss inserts its jobs with your database adapter's `query`, in your transaction
94
+ holds: true, // `startAfter`, however far ahead
95
+ replaces: true,
96
+ /** Takes the registry's database: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
97
+ connect({ listeners, crons, sql }) {
98
+ database = sql;
99
+ for (const l of listeners)
100
+ queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
101
+ for (const c of crons)
102
+ queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
103
+ },
104
+ /** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
105
+ async enqueue(tx, jobs) {
106
+ const db = inTx(tx);
107
+ for (const [name, list] of Map.groupBy(jobs, queueOf)) {
108
+ const keyed = await Promise.all(list.map(async (job) => ({ job, key: await storedReplaceKey(job) })));
109
+ const keys = keyed.map(({ key }) => key).filter((key) => key !== undefined);
110
+ await inQueue(name, async () => {
111
+ if (keys.length)
112
+ await replaceWaiting(db, keys);
113
+ await boss.insert(name, keyed.map(({ job, key }) => rowOf(job, key)), { db });
114
+ });
115
+ }
116
+ },
117
+ /** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
118
+ async deliver() { },
119
+ /**
120
+ * A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
121
+ * it has run, so it's no longer a call a newer one replaces.
122
+ */
123
+ async retry(id) {
124
+ const queues = await queuesOf(id);
125
+ if (!database || !queues.length)
126
+ return false;
127
+ const uuid = pgBossId(id);
128
+ return database.transaction(async (tx) => {
129
+ const db = inTx(tx);
130
+ for (const { name } of queues) {
131
+ // failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
132
+ const { affected } = await boss.retry(name, uuid, { db });
133
+ if (!affected)
134
+ continue;
135
+ const [failed] = await boss.findJobs(name, { id: uuid, db });
136
+ if (!failed)
137
+ continue;
138
+ // as new: retry count 0, and its retries again
139
+ await boss.deleteJob(name, uuid, { db });
140
+ await boss.insert(name, [rowOf(failed.data)], { db });
141
+ return true;
142
+ }
143
+ return false;
144
+ });
145
+ },
146
+ /** pg-boss keeps failed jobs in its own tables, one queue at a time, with no state filter: list them there. */
147
+ async failed() {
148
+ throw new Error("[logic-sdk] pgBoss(boss) can't list failed jobs across queues: use boss.findJobs(queue) for one, and pgBossId(id) to match ids.");
149
+ },
150
+ /** A failed job, deleted. A waiting, running or retrying one is left alone. */
151
+ async forget(id) {
152
+ const queues = await queuesOf(id);
153
+ if (!database || !queues.length)
154
+ return false;
155
+ const uuid = pgBossId(id);
156
+ return database.transaction(async (tx) => {
157
+ const db = inTx(tx);
158
+ for (const { name } of queues) {
159
+ const [found] = await boss.findJobs(name, { id: uuid, db });
160
+ if (found?.state !== "failed")
161
+ continue;
162
+ await boss.deleteJob(name, uuid, { db });
163
+ return true;
164
+ }
165
+ return false;
166
+ });
167
+ },
168
+ };
169
+ /**
170
+ * A job id's queues: its listener's or cron's (the id's prefix), and the calls queue. Looked up before any
171
+ * transaction: inside one, a lookup on pg-boss's own connection would wait for it on PGlite.
172
+ */
173
+ async function queuesOf(id) {
174
+ const at = id.lastIndexOf("@");
175
+ if (at < 0)
176
+ return []; // not a job id
177
+ const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
178
+ return boss.getQueues(names);
179
+ }
180
+ }