logic-sdk 0.7.1 → 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 (99) hide show
  1. package/README.md +7 -7
  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/{jobs.d.ts → core/jobs.d.ts} +23 -10
  23. package/dist/{jobs.js → core/jobs.js} +152 -39
  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} +203 -40
  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 -122
  42. package/dist/index.js +4 -492
  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 -53
  54. package/dist/pg-boss.js +2 -213
  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 -75
  60. package/dist/testing.js +1 -227
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +4 -3
  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} +152 -38
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +197 -40
  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 +15 -652
  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 -241
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -305
  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
@@ -1,236 +1,3 @@
1
- import { sql, type SQL } from "drizzle-orm";
2
- import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
3
- import type { DatabaseAdapter, Job, ReadWrite, SqlDatabase } from "../index.ts";
4
- import { causes } from "../errors.ts";
5
-
6
- export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../sqlite.ts";
7
-
8
- /** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
9
- interface SyncSqlite {
10
- all<T>(query: SQL): T[];
11
- run(query: SQL): unknown;
12
- $client: { close(): unknown };
13
- }
14
-
15
- /** What mutations get: a connection of their own, inside the transaction the adapter opened. */
16
- export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
17
-
18
- /** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
19
- export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
20
-
21
- /** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
22
- export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
23
-
24
- export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
25
-
26
- /** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
27
- const BUSY_TIMEOUT = 5000;
28
-
29
- /**
30
- * Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
31
- * `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
32
- * ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
33
- *
34
- * ```ts
35
- * const database = drizzleAdapter(() => drizzle("app.db"));
36
- * ```
37
- */
38
- export function drizzleAdapter<Db extends SyncSqlite>(
39
- open: () => Db,
40
- options: DrizzleAdapterOptions = {},
41
- ): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>> {
42
- const reader = open();
43
- checkOpen(open, reader);
44
- exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
45
- exec(reader, "PRAGMA query_only = ON");
46
-
47
- const takeTurn = turns();
48
- const transaction = <T>(fn: (tx: DrizzleTx<Db>) => Promise<T>) =>
49
- takeTurn(async (restartClock) => {
50
- const tx = await begin(open, restartClock);
51
- try {
52
- const out = await fn(tx);
53
- exec(tx, "COMMIT");
54
- return out;
55
- } catch (e) {
56
- undo(tx, "ROLLBACK");
57
- throw e;
58
- } finally {
59
- tx.$client.close();
60
- }
61
- });
62
-
63
- return {
64
- db: reader,
65
- transactionAttempts: options.transactionAttempts,
66
- transaction,
67
- nest: (tx) => savepoints(tx),
68
- retryable: isBusy,
69
- // on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
70
- query: async (client: Pick<SyncSqlite, "all">, text, params) =>
71
- client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
72
- };
73
- }
74
-
75
- /** Transactions inside a transaction, as savepoints: the test registry's. */
76
- function savepoints<Tx extends Pick<SyncSqlite, "all" | "run">>(tx: Tx): SqlDatabase<Tx, Tx> {
77
- const takeTurn = turns();
78
- return {
79
- db: tx,
80
- transaction: (fn) =>
81
- takeTurn(async () => {
82
- exec(tx, "SAVEPOINT logic_sdk");
83
- try {
84
- const out = await fn(tx);
85
- exec(tx, "RELEASE logic_sdk");
86
- return out;
87
- } catch (e) {
88
- undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
89
- throw e;
90
- }
91
- }),
92
- nest: savepoints,
93
- query: async (client, text, params) => rowsOf(client, text, params),
94
- };
95
- }
96
-
97
- const exec = (db: Pick<SyncSqlite, "run">, text: string) => db.run(sql.raw(text));
98
-
99
- /** SQL text with `?` parameters as a Drizzle query. */
100
- const toSql = (text: string, params: unknown[]) =>
101
- sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
102
-
103
- const rowsOf = (db: Pick<SyncSqlite, "all">, text: string, params: unknown[]) =>
104
- db.all<Record<string, unknown>>(toSql(text, params));
105
-
106
- /** 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. */
107
- function undo(db: Pick<SyncSqlite, "run">, ...statements: string[]) {
108
- try {
109
- for (const statement of statements) exec(db, statement);
110
- } catch {}
111
- }
112
-
113
- /** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
114
- function checkOpen<Db extends SyncSqlite>(open: () => Db, reader: Db) {
115
- const another = open();
116
- if (another.$client === reader.$client)
117
- throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
118
- const [main] = another.all<{ file: string }>(sql`PRAGMA database_list`);
119
- another.$client.close();
120
- if (!main?.file)
121
- 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.");
122
- }
123
-
124
- /**
125
- * A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
126
- * since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
127
- */
128
- async function begin<Db extends SyncSqlite>(open: () => Db, restartClock: () => void): Promise<Db> {
129
- const deadline = Date.now() + BUSY_TIMEOUT;
130
- for (;;) {
131
- restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
132
- let tx: Db | undefined;
133
- try {
134
- tx = open();
135
- exec(tx, "PRAGMA busy_timeout = 0");
136
- exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
137
- exec(tx, "BEGIN IMMEDIATE");
138
- return tx;
139
- } catch (e) {
140
- tx?.$client.close();
141
- if (!isBusy(e) || Date.now() >= deadline) throw e;
142
- }
143
- await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
144
- }
145
- }
146
-
147
- /**
148
- * One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
149
- * when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
150
- */
151
- function turns() {
152
- let last = Promise.resolve();
153
- let startedAt = 0;
154
- const restartClock = () => {
155
- startedAt = Date.now();
156
- };
157
- return async <T>(work: (restartClock: () => void) => Promise<T>): Promise<T> => {
158
- const arrived = Date.now();
159
- const ahead = last;
160
- const done = Promise.withResolvers<void>();
161
- last = ahead.then(() => done.promise);
162
- try {
163
- const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
164
- while (!(await settlesBy(ahead, giveUpAt()))) {
165
- // the one ahead may have changed while we waited: the line moved
166
- if (Date.now() >= giveUpAt()) throw new Error(HELD);
167
- }
168
- restartClock();
169
- return await work(restartClock);
170
- } finally {
171
- done.resolve();
172
- }
173
- };
174
- }
175
-
176
- const HELD =
177
- "[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?";
178
-
179
- /** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
180
- const settlesBy = (promise: Promise<void>, time: number) =>
181
- new Promise<boolean>((resolve) => {
182
- const timer = setTimeout(() => resolve(false), time - Date.now());
183
- void promise.then(() => {
184
- clearTimeout(timer);
185
- resolve(true);
186
- });
187
- });
188
-
189
- /** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
190
- function isBusy(error: unknown): boolean {
191
- for (const e of causes(error))
192
- if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message))) return true;
193
- return false;
194
- }
195
-
196
- const now = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
197
-
198
- /**
199
- * The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
200
- * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
201
- * job; done rows are deleted, failed ones stay so you can query them and `retry` them.
202
- */
203
- export const jobsTable = sqliteTable(
204
- "logic_jobs",
205
- {
206
- /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
207
- id: text("id").primaryKey(),
208
- job: text("job", { mode: "json" }).$type<Job>().notNull(),
209
- /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
210
- status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
211
- /** Incremented when a runner claims it, so a crash still uses an attempt. */
212
- attempts: integer("attempts").notNull().default(0),
213
- /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
214
- availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
215
- /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
216
- receipt: text("receipt"),
217
- /** The last failure, with its stack. */
218
- lastError: text("last_error"),
219
- failedAt: integer("failed_at", { mode: "timestamp_ms" }),
220
- /** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
221
- replaceKey: text("replace_key"),
222
- createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
223
- },
224
- (t) => [
225
- index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
226
- // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
227
- uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
228
- ],
229
- );
230
-
231
- /** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
232
- export const cronRunsTable = sqliteTable("logic_cron_runs", {
233
- /** The cron job's id, `<cron id>@<minute>`. */
234
- id: text("id").primaryKey(),
235
- ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
236
- });
1
+ export { cronRunsTable, drizzleAdapter, jobsTable, type DrizzleDb, type DrizzleReader, type DrizzleTx } from "../adapters/drizzle-sqlite.ts";
2
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "../adapters/sqlite.ts";
3
+ export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "../adapters/stored-jobs.ts";
package/src/fetch.ts CHANGED
@@ -1,31 +1 @@
1
- import { isDomainError, type ErrorKind } from "./index.ts";
2
-
3
- /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
4
- export const statusOf: Record<ErrorKind, number> = {
5
- invalid: 400,
6
- unauthenticated: 401,
7
- forbidden: 403,
8
- not_found: 404,
9
- conflict: 409,
10
- rejected: 422,
11
- };
12
-
13
- /**
14
- * A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
15
- * (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
16
- * and logs it, and its message never reaches the client.
17
- *
18
- * ```ts
19
- * app.post("/orders", async (c) => {
20
- * try {
21
- * return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
22
- * } catch (e) {
23
- * return toResponse(e);
24
- * }
25
- * });
26
- * ```
27
- */
28
- export function toResponse(error: unknown): Response {
29
- if (!isDomainError(error)) throw error;
30
- return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
31
- }
1
+ export { statusOf, toResponse } from "./integrations/fetch.ts";
@@ -0,0 +1,54 @@
1
+ import { defaultBackoff } from "../core/jobs.ts";
2
+ import type { Job, Jobs } from "../core/types.ts";
3
+
4
+ /** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
5
+ export interface QueueBatch {
6
+ readonly messages: readonly {
7
+ readonly body: Job;
8
+ readonly attempts: number;
9
+ ack(): void;
10
+ retry(options?: { delaySeconds?: number }): void;
11
+ }[];
12
+ }
13
+
14
+ /**
15
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
16
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
17
+ * its own, so one failure doesn't redeliver the batch.
18
+ *
19
+ * ```ts
20
+ * async queue(batch, env, ctx) {
21
+ * await handleQueue(makeRegistry(env, ctx), batch);
22
+ * },
23
+ * ```
24
+ */
25
+ export async function handleQueue(registry: { jobs: Pick<Jobs, "run"> }, batch: QueueBatch): Promise<void> {
26
+ for (const message of batch.messages) {
27
+ try {
28
+ await registry.jobs.run(message.body, { attempt: message.attempts });
29
+ message.ack();
30
+ } catch {
31
+ // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
32
+ message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
33
+ }
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
39
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
40
+ * 1 = Sunday, so write them as names (`MON`) in both places.
41
+ *
42
+ * ```ts
43
+ * async scheduled(controller, env, ctx) {
44
+ * await handleScheduled(makeRegistry(env, ctx), controller);
45
+ * },
46
+ * ```
47
+ */
48
+ export async function handleScheduled(
49
+ registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
50
+ controller: { readonly scheduledTime: number },
51
+ ): Promise<void> {
52
+ await registry.jobs.tick(new Date(controller.scheduledTime));
53
+ await registry.jobs.sweep();
54
+ }
@@ -0,0 +1,99 @@
1
+ import type { Jobs } from "../core/types.ts";
2
+
3
+ export interface TickingOptions {
4
+ /** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
5
+ sweepEvery?: number;
6
+ /** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
7
+ onError?: (error: unknown) => void;
8
+ }
9
+
10
+ export interface StopOptions {
11
+ /** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
12
+ timeout?: number;
13
+ }
14
+
15
+ const MINUTE = 60_000;
16
+ /**
17
+ * Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
18
+ * Oban: a slow cron doesn't hold back the next minute, and a hung job doesn't stop the sweeps, as it wouldn't stop the
19
+ * other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
20
+ * up would run a backlog of stale minutes when it comes back.
21
+ */
22
+ const MAX_RUNNING = 10;
23
+
24
+ /**
25
+ * A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
26
+ * every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
27
+ * minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
28
+ * which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
29
+ *
30
+ * ```ts
31
+ * import { startTicking } from "logic-sdk/node";
32
+ * const stop = startTicking(registry);
33
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
34
+ * ```
35
+ */
36
+ export function startTicking(
37
+ registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
38
+ options: TickingOptions = {},
39
+ ): (options?: StopOptions) => Promise<void> {
40
+ const sweepEvery = options.sweepEvery ?? 60;
41
+ const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
42
+ const onError = (error: unknown) => {
43
+ try {
44
+ reportTo(error);
45
+ } catch (inner) {
46
+ console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
47
+ }
48
+ };
49
+ let tickTimer: ReturnType<typeof setTimeout> | undefined;
50
+ let sweepTimer: ReturnType<typeof setTimeout> | undefined;
51
+ const ticks = new Set<Promise<void>>();
52
+ const sweeps = new Set<Promise<void>>();
53
+
54
+ const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
55
+
56
+ const track = (running: Set<Promise<void>>, work: Promise<unknown>) => {
57
+ const run = work.then(() => {}, onError);
58
+ running.add(run);
59
+ void run.finally(() => running.delete(run));
60
+ };
61
+
62
+ const tick = (at: Date) => {
63
+ if (ticks.size >= MAX_RUNNING) {
64
+ onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
65
+ return;
66
+ }
67
+ track(ticks, registry.jobs.tick(at));
68
+ };
69
+
70
+ const armTick = (minute: number) => {
71
+ tickTimer = setTimeout(() => {
72
+ // early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
73
+ const due = Math.max(minute, startOfMinute(Date.now()));
74
+ armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
75
+ tick(new Date(due));
76
+ }, minute - Date.now());
77
+ };
78
+
79
+ const sweep = () => {
80
+ sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
81
+ if (sweeps.size >= MAX_RUNNING) {
82
+ onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
83
+ return;
84
+ }
85
+ track(sweeps, registry.jobs.sweep());
86
+ };
87
+
88
+ armTick(startOfMinute(Date.now()) + MINUTE);
89
+ if (sweepEvery > 0) sweepTimer = setTimeout(sweep, sweepEvery * 1000);
90
+
91
+ return async ({ timeout = 30 } = {}) => {
92
+ clearTimeout(tickTimer);
93
+ clearTimeout(sweepTimer);
94
+ let timer: ReturnType<typeof setTimeout> | undefined;
95
+ const gaveUp = new Promise<void>((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
96
+ await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
97
+ clearTimeout(timer);
98
+ };
99
+ }
@@ -0,0 +1,71 @@
1
+ // `work()`, the pg-boss worker: its queues and names are the adapter's (adapters/pg-boss.ts).
2
+ import type { JobResult, PgBoss } from "pg-boss";
3
+ import { CALLS_QUEUE, PREFIX, queueConfig, queueName, tuningOf, type PgBossTuning } from "../adapters/pg-boss.ts";
4
+ import type { Job, Jobs, Registry } from "../core/types.ts";
5
+ import { startTicking } from "./node.ts";
6
+
7
+ export interface PgBossWorkOptions {
8
+ /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
9
+ calls?: PgBossTuning;
10
+ /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
11
+ onError?: (error: unknown) => void;
12
+ }
13
+
14
+ /**
15
+ * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
16
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
17
+ *
18
+ * ```ts
19
+ * await boss.start();
20
+ * await work(registry, boss);
21
+ * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
22
+ * ```
23
+ */
24
+ export async function work(
25
+ registry: Pick<Registry, "definitions"> & { jobs: Pick<Jobs, "run" | "tick" | "sweep"> },
26
+ boss: PgBoss,
27
+ options: PgBossWorkOptions = {},
28
+ ): Promise<void> {
29
+ const { listeners, crons } = registry.definitions;
30
+ const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
31
+ const queues: { name: string; tuning: PgBossTuning | undefined }[] = [
32
+ ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
33
+ ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
34
+ { name: CALLS_QUEUE, tuning: options.calls },
35
+ ];
36
+
37
+ /** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
38
+ const settle = async (job: { id: string; data: Job; retryCount: number }): Promise<JobResult> => {
39
+ let reason: unknown;
40
+ const fail = async (error: unknown) => {
41
+ reason = error; // kept by pg-boss as the failed job's output
42
+ };
43
+ try {
44
+ const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
45
+ if (outcome === "failed") return { id: job.id, status: "deadletter", output: reason };
46
+ return { id: job.id, status: "completed" };
47
+ } catch (error) {
48
+ return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
49
+ }
50
+ };
51
+
52
+ for (const { name, tuning } of queues) {
53
+ const config = queueConfig(tuning?.queue);
54
+ const { partition: _createOnly, ...updatable } = config;
55
+ await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
56
+ await boss.updateQueue(name, updatable);
57
+ await boss.work<Job>(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
58
+ }
59
+
60
+ // a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
61
+ // They never get a try that could report, so say so here
62
+ const ours = new Set(queues.map((q) => q.name));
63
+ for (const q of await boss.getQueues())
64
+ if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
65
+ onError(new Error(`[logic-sdk] pg-boss queue ${q.name} has ${q.queuedCount} job(s) and no listener or cron here (renamed or removed?). Give it its old id back, or delete the queue.`));
66
+
67
+ if (!crons.length) return;
68
+ // ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
69
+ const stop = startTicking(registry, { sweepEvery: 0, onError });
70
+ boss.once("stopped", () => void stop());
71
+ }