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,194 +1,2 @@
1
- import { sql } from "drizzle-orm";
2
- import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
3
- import { causes } from "../errors.js";
4
- export { databaseQueue, jobsSchema, outbox } from "../sqlite.js";
5
- /** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
6
- const BUSY_TIMEOUT = 5000;
7
- /**
8
- * Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
9
- * `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
10
- * ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
11
- *
12
- * ```ts
13
- * const database = drizzleAdapter(() => drizzle("app.db"));
14
- * ```
15
- */
16
- export function drizzleAdapter(open, options = {}) {
17
- const reader = open();
18
- checkOpen(open, reader);
19
- exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
20
- exec(reader, "PRAGMA query_only = ON");
21
- const takeTurn = turns();
22
- const transaction = (fn) => takeTurn(async (restartClock) => {
23
- const tx = await begin(open, restartClock);
24
- try {
25
- const out = await fn(tx);
26
- exec(tx, "COMMIT");
27
- return out;
28
- }
29
- catch (e) {
30
- undo(tx, "ROLLBACK");
31
- throw e;
32
- }
33
- finally {
34
- tx.$client.close();
35
- }
36
- });
37
- return {
38
- db: reader,
39
- transactionAttempts: options.transactionAttempts,
40
- transaction,
41
- nest: (tx) => savepoints(tx),
42
- retryable: isBusy,
43
- // on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
44
- query: async (client, text, params) => client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
45
- };
46
- }
47
- /** Transactions inside a transaction, as savepoints: the test registry's. */
48
- function savepoints(tx) {
49
- const takeTurn = turns();
50
- return {
51
- db: tx,
52
- transaction: (fn) => takeTurn(async () => {
53
- exec(tx, "SAVEPOINT logic_sdk");
54
- try {
55
- const out = await fn(tx);
56
- exec(tx, "RELEASE logic_sdk");
57
- return out;
58
- }
59
- catch (e) {
60
- undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
61
- throw e;
62
- }
63
- }),
64
- nest: savepoints,
65
- query: async (client, text, params) => rowsOf(client, text, params),
66
- };
67
- }
68
- const exec = (db, text) => db.run(sql.raw(text));
69
- /** SQL text with `?` parameters as a Drizzle query. */
70
- const toSql = (text, params) => sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
71
- const rowsOf = (db, text, params) => db.all(toSql(text, params));
72
- /** 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. */
73
- function undo(db, ...statements) {
74
- try {
75
- for (const statement of statements)
76
- exec(db, statement);
77
- }
78
- catch { }
79
- }
80
- /** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
81
- function checkOpen(open, reader) {
82
- const another = open();
83
- if (another.$client === reader.$client)
84
- throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
85
- const [main] = another.all(sql `PRAGMA database_list`);
86
- another.$client.close();
87
- if (!main?.file)
88
- 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.");
89
- }
90
- /**
91
- * A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
92
- * since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
93
- */
94
- async function begin(open, restartClock) {
95
- const deadline = Date.now() + BUSY_TIMEOUT;
96
- for (;;) {
97
- restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
98
- let tx;
99
- try {
100
- tx = open();
101
- exec(tx, "PRAGMA busy_timeout = 0");
102
- exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
103
- exec(tx, "BEGIN IMMEDIATE");
104
- return tx;
105
- }
106
- catch (e) {
107
- tx?.$client.close();
108
- if (!isBusy(e) || Date.now() >= deadline)
109
- throw e;
110
- }
111
- await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
112
- }
113
- }
114
- /**
115
- * One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
116
- * when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
117
- */
118
- function turns() {
119
- let last = Promise.resolve();
120
- let startedAt = 0;
121
- const restartClock = () => {
122
- startedAt = Date.now();
123
- };
124
- return async (work) => {
125
- const arrived = Date.now();
126
- const ahead = last;
127
- const done = Promise.withResolvers();
128
- last = ahead.then(() => done.promise);
129
- try {
130
- const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
131
- while (!(await settlesBy(ahead, giveUpAt()))) {
132
- // the one ahead may have changed while we waited: the line moved
133
- if (Date.now() >= giveUpAt())
134
- throw new Error(HELD);
135
- }
136
- restartClock();
137
- return await work(restartClock);
138
- }
139
- finally {
140
- done.resolve();
141
- }
142
- };
143
- }
144
- 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?";
145
- /** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
146
- const settlesBy = (promise, time) => new Promise((resolve) => {
147
- const timer = setTimeout(() => resolve(false), time - Date.now());
148
- void promise.then(() => {
149
- clearTimeout(timer);
150
- resolve(true);
151
- });
152
- });
153
- /** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
154
- function isBusy(error) {
155
- for (const e of causes(error))
156
- if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message)))
157
- return true;
158
- return false;
159
- }
160
- const now = sql `(cast(unixepoch('subsec') * 1000 as integer))`;
161
- /**
162
- * The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
163
- * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
164
- * job; done rows are deleted, failed ones stay so you can query them and `retry` them.
165
- */
166
- export const jobsTable = sqliteTable("logic_jobs", {
167
- /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
168
- id: text("id").primaryKey(),
169
- job: text("job", { mode: "json" }).$type().notNull(),
170
- /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
171
- status: text("status").$type().notNull().default("pending"),
172
- /** Incremented when a runner claims it, so a crash still uses an attempt. */
173
- attempts: integer("attempts").notNull().default(0),
174
- /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
175
- availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
176
- /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
177
- receipt: text("receipt"),
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>@<key>`: 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
- ]);
189
- /** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
190
- export const cronRunsTable = sqliteTable("logic_cron_runs", {
191
- /** The cron job's id, `<cron id>@<minute>`. */
192
- id: text("id").primaryKey(),
193
- ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
194
- });
1
+ export { cronRunsTable, drizzleAdapter, jobsTable } from "../adapters/drizzle-sqlite.js";
2
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "../adapters/sqlite.js";
package/dist/fetch.d.ts CHANGED
@@ -1,19 +1 @@
1
- import { type ErrorKind } from "./index.ts";
2
- /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
- export declare const statusOf: Record<ErrorKind, number>;
4
- /**
5
- * A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
6
- * (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
7
- * and logs it, and its message never reaches the client.
8
- *
9
- * ```ts
10
- * app.post("/orders", async (c) => {
11
- * try {
12
- * return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
13
- * } catch (e) {
14
- * return toResponse(e);
15
- * }
16
- * });
17
- * ```
18
- */
19
- export declare function toResponse(error: unknown): Response;
1
+ export { statusOf, toResponse } from "./integrations/fetch.ts";
package/dist/fetch.js CHANGED
@@ -1,30 +1 @@
1
- import { isDomainError } from "./index.js";
2
- /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
- export const statusOf = {
4
- invalid: 400,
5
- unauthenticated: 401,
6
- forbidden: 403,
7
- not_found: 404,
8
- conflict: 409,
9
- rejected: 422,
10
- };
11
- /**
12
- * A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
13
- * (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
14
- * and logs it, and its message never reaches the client.
15
- *
16
- * ```ts
17
- * app.post("/orders", async (c) => {
18
- * try {
19
- * return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
20
- * } catch (e) {
21
- * return toResponse(e);
22
- * }
23
- * });
24
- * ```
25
- */
26
- export function toResponse(error) {
27
- if (!isDomainError(error))
28
- throw error;
29
- return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
30
- }
1
+ export { statusOf, toResponse } from "./integrations/fetch.js";
@@ -0,0 +1,42 @@
1
+ import type { Job, Jobs } from "../core/types.ts";
2
+ /** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
3
+ export interface QueueBatch {
4
+ readonly messages: readonly {
5
+ readonly body: Job;
6
+ readonly attempts: number;
7
+ ack(): void;
8
+ retry(options?: {
9
+ delaySeconds?: number;
10
+ }): void;
11
+ }[];
12
+ }
13
+ /**
14
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
15
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
16
+ * its own, so one failure doesn't redeliver the batch.
17
+ *
18
+ * ```ts
19
+ * async queue(batch, env, ctx) {
20
+ * await handleQueue(makeRegistry(env, ctx), batch);
21
+ * },
22
+ * ```
23
+ */
24
+ export declare function handleQueue(registry: {
25
+ jobs: Pick<Jobs, "run">;
26
+ }, batch: QueueBatch): Promise<void>;
27
+ /**
28
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
29
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
30
+ * 1 = Sunday, so write them as names (`MON`) in both places.
31
+ *
32
+ * ```ts
33
+ * async scheduled(controller, env, ctx) {
34
+ * await handleScheduled(makeRegistry(env, ctx), controller);
35
+ * },
36
+ * ```
37
+ */
38
+ export declare function handleScheduled(registry: {
39
+ jobs: Pick<Jobs, "tick" | "sweep">;
40
+ }, controller: {
41
+ readonly scheduledTime: number;
42
+ }): Promise<void>;
@@ -0,0 +1,39 @@
1
+ import { defaultBackoff } from "../core/jobs.js";
2
+ /**
3
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
4
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
5
+ * its own, so one failure doesn't redeliver the batch.
6
+ *
7
+ * ```ts
8
+ * async queue(batch, env, ctx) {
9
+ * await handleQueue(makeRegistry(env, ctx), batch);
10
+ * },
11
+ * ```
12
+ */
13
+ export async function handleQueue(registry, batch) {
14
+ for (const message of batch.messages) {
15
+ try {
16
+ await registry.jobs.run(message.body, { attempt: message.attempts });
17
+ message.ack();
18
+ }
19
+ catch {
20
+ // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
21
+ message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
22
+ }
23
+ }
24
+ }
25
+ /**
26
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
27
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
28
+ * 1 = Sunday, so write them as names (`MON`) in both places.
29
+ *
30
+ * ```ts
31
+ * async scheduled(controller, env, ctx) {
32
+ * await handleScheduled(makeRegistry(env, ctx), controller);
33
+ * },
34
+ * ```
35
+ */
36
+ export async function handleScheduled(registry, controller) {
37
+ await registry.jobs.tick(new Date(controller.scheduledTime));
38
+ await registry.jobs.sweep();
39
+ }
@@ -0,0 +1,26 @@
1
+ import type { Jobs } from "../core/types.ts";
2
+ export interface TickingOptions {
3
+ /** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
4
+ sweepEvery?: number;
5
+ /** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
6
+ onError?: (error: unknown) => void;
7
+ }
8
+ export interface StopOptions {
9
+ /** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
10
+ timeout?: number;
11
+ }
12
+ /**
13
+ * A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
14
+ * every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
15
+ * minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
16
+ * which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
17
+ *
18
+ * ```ts
19
+ * import { startTicking } from "logic-sdk/node";
20
+ * const stop = startTicking(registry);
21
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
22
+ * ```
23
+ */
24
+ export declare function startTicking(registry: {
25
+ jobs: Pick<Jobs, "tick" | "sweep">;
26
+ }, options?: TickingOptions): (options?: StopOptions) => Promise<void>;
@@ -0,0 +1,76 @@
1
+ const MINUTE = 60_000;
2
+ /**
3
+ * Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
4
+ * 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
5
+ * other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
6
+ * up would run a backlog of stale minutes when it comes back.
7
+ */
8
+ const MAX_RUNNING = 10;
9
+ /**
10
+ * A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
11
+ * every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
12
+ * minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
13
+ * which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
14
+ *
15
+ * ```ts
16
+ * import { startTicking } from "logic-sdk/node";
17
+ * const stop = startTicking(registry);
18
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
19
+ * ```
20
+ */
21
+ export function startTicking(registry, options = {}) {
22
+ const sweepEvery = options.sweepEvery ?? 60;
23
+ const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
24
+ const onError = (error) => {
25
+ try {
26
+ reportTo(error);
27
+ }
28
+ catch (inner) {
29
+ console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
30
+ }
31
+ };
32
+ let tickTimer;
33
+ let sweepTimer;
34
+ const ticks = new Set();
35
+ const sweeps = new Set();
36
+ const startOfMinute = (ms) => Math.floor(ms / MINUTE) * MINUTE;
37
+ const track = (running, work) => {
38
+ const run = work.then(() => { }, onError);
39
+ running.add(run);
40
+ void run.finally(() => running.delete(run));
41
+ };
42
+ const tick = (at) => {
43
+ if (ticks.size >= MAX_RUNNING) {
44
+ onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
45
+ return;
46
+ }
47
+ track(ticks, registry.jobs.tick(at));
48
+ };
49
+ const armTick = (minute) => {
50
+ tickTimer = setTimeout(() => {
51
+ // early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
52
+ const due = Math.max(minute, startOfMinute(Date.now()));
53
+ armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
54
+ tick(new Date(due));
55
+ }, minute - Date.now());
56
+ };
57
+ const sweep = () => {
58
+ sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
59
+ if (sweeps.size >= MAX_RUNNING) {
60
+ onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
61
+ return;
62
+ }
63
+ track(sweeps, registry.jobs.sweep());
64
+ };
65
+ armTick(startOfMinute(Date.now()) + MINUTE);
66
+ if (sweepEvery > 0)
67
+ sweepTimer = setTimeout(sweep, sweepEvery * 1000);
68
+ return async ({ timeout = 30 } = {}) => {
69
+ clearTimeout(tickTimer);
70
+ clearTimeout(sweepTimer);
71
+ let timer;
72
+ const gaveUp = new Promise((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
73
+ await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
74
+ clearTimeout(timer);
75
+ };
76
+ }
@@ -0,0 +1,22 @@
1
+ import type { PgBoss } from "pg-boss";
2
+ import { type PgBossTuning } from "../adapters/pg-boss.ts";
3
+ import type { Jobs, Registry } from "../core/types.ts";
4
+ export interface PgBossWorkOptions {
5
+ /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
6
+ calls?: PgBossTuning;
7
+ /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
8
+ onError?: (error: unknown) => void;
9
+ }
10
+ /**
11
+ * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
12
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
13
+ *
14
+ * ```ts
15
+ * await boss.start();
16
+ * await work(registry, boss);
17
+ * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
18
+ * ```
19
+ */
20
+ export declare function work(registry: Pick<Registry, "definitions"> & {
21
+ jobs: Pick<Jobs, "run" | "tick" | "sweep">;
22
+ }, boss: PgBoss, options?: PgBossWorkOptions): Promise<void>;
@@ -0,0 +1,55 @@
1
+ import { CALLS_QUEUE, PREFIX, queueConfig, queueName, tuningOf } from "../adapters/pg-boss.js";
2
+ import { startTicking } from "./node.js";
3
+ /**
4
+ * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
5
+ * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
6
+ *
7
+ * ```ts
8
+ * await boss.start();
9
+ * await work(registry, boss);
10
+ * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
11
+ * ```
12
+ */
13
+ export async function work(registry, boss, options = {}) {
14
+ const { listeners, crons } = registry.definitions;
15
+ const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
16
+ const queues = [
17
+ ...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
18
+ ...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
19
+ { name: CALLS_QUEUE, tuning: options.calls },
20
+ ];
21
+ /** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
22
+ const settle = async (job) => {
23
+ let reason;
24
+ const fail = async (error) => {
25
+ reason = error; // kept by pg-boss as the failed job's output
26
+ };
27
+ try {
28
+ const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
29
+ if (outcome === "failed")
30
+ return { id: job.id, status: "deadletter", output: reason };
31
+ return { id: job.id, status: "completed" };
32
+ }
33
+ catch (error) {
34
+ return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
35
+ }
36
+ };
37
+ for (const { name, tuning } of queues) {
38
+ const config = queueConfig(tuning?.queue);
39
+ const { partition: _createOnly, ...updatable } = config;
40
+ await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
41
+ await boss.updateQueue(name, updatable);
42
+ await boss.work(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
43
+ }
44
+ // a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
45
+ // They never get a try that could report, so say so here
46
+ const ours = new Set(queues.map((q) => q.name));
47
+ for (const q of await boss.getQueues())
48
+ if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
49
+ 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.`));
50
+ if (!crons.length)
51
+ return;
52
+ // ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
53
+ const stop = startTicking(registry, { sweepEvery: 0, onError });
54
+ boss.once("stopped", () => void stop());
55
+ }
package/dist/index.d.ts CHANGED
@@ -1,122 +1,5 @@
1
- import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, CronCtx, DatabaseAdapter, DbOf, EventDef, In, JobsOptions, Listener, ListenerCtx, ListenerMetaOf, Out, OwnModules, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, Schema, ScopeOf, ServicesOf } from "./types.ts";
2
- export type { ActionCtx, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DeepPartial, Delivery, Envelope, Errors, EventDef, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, SqlDatabase, SweepResult, } from "./types.ts";
3
- export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
4
- export { inProcess, replaceKeyOf } from "./jobs.ts";
5
- type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
6
- /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
7
- jobs?: JobsOptions<ScopeOf<C>, T>;
8
- /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
9
- wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
10
- } & ({} extends ServicesOf<C> ? {
11
- services?: ServicesOf<C>;
12
- } : {
13
- services: ServicesOf<C>;
14
- }) & ({} extends ConfigOf<C> ? {
15
- config?: ConfigOf<C>;
16
- } : {
17
- config: ConfigOf<C>;
18
- }) & ([DbOf<C>] extends [never] ? {
19
- database?: undefined;
20
- } : {
21
- database: DatabaseAdapter<unknown, DbOf<C>>;
22
- }) & {
23
- modules: OwnModules<C, Mods>;
24
- };
25
- /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
26
- type OnlyKnownKeys<C> = {
27
- [K in Exclude<keyof C, keyof Config>]: never;
28
- };
29
- /**
30
- * Typed constructors for your app:
31
- *
32
- * ```ts
33
- * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
34
- * ```
35
- */
36
- export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
37
- /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
38
- createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
39
- /** Reads data. Can run other queries. No writes, no events, no services. */
40
- query: Constructor<C, "query">;
41
- /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
42
- mutation: Constructor<C, "mutation">;
43
- /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
44
- action: Constructor<C, "action">;
45
- /** Something that happened. Emitted by mutations, delivered after commit. */
46
- event: <S extends Schema>(def: {
47
- /**
48
- * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
49
- * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
50
- */
51
- id?: string;
52
- payload: S;
53
- }) => EventDef<In<S>, Out<S>>;
54
- /**
55
- * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
56
- * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
57
- * idempotent: a retry runs the whole handler again.
58
- * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
59
- */
60
- cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>) => Cron<C>;
61
- /**
62
- * React to an event after commit, like an action. Must be idempotent.
63
- * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
64
- */
65
- listener: <O>(def: {
66
- /**
67
- * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
68
- * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
69
- */
70
- id?: string;
71
- /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
72
- event: () => EventDef<unknown, O>;
73
- /**
74
- * Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
75
- * Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
76
- */
77
- attempts?: number;
78
- /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
79
- delay?: number;
80
- /**
81
- * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
82
- * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
83
- * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
84
- * mutation, as a bad payload does.
85
- */
86
- when?: (payload: O) => boolean;
87
- meta?: ListenerMetaOf<C>;
88
- handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
89
- }) => Listener<O, C>;
90
- };
91
- /** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
92
- type CronDef<C extends Config, Sc> = {
93
- /**
94
- * Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
95
- * so set it before you rename the export.
96
- */
97
- id?: string;
98
- /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
99
- schedule: string;
100
- /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
101
- timezone?: string;
102
- /** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
103
- scope: Sc;
104
- /** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
105
- attempts?: number;
106
- meta?: ListenerMetaOf<C>;
107
- /** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
108
- handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
109
- };
110
- /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
111
- export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
112
- /**
113
- * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
114
- * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
115
- */
116
- export declare function describeModules(modules: Record<string, object>): {
117
- ids: Map<object, string>;
118
- functions: RegisteredFn[];
119
- events: RegisteredEvent[];
120
- listeners: RegisteredListener[];
121
- crons: RegisteredCron[];
122
- };
1
+ export type { ActionCtx, AdapterSetup, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DatabaseOptions, DeepPartial, Delivery, EmittedEvent, Envelope, Errors, EventDef, FailedJob, FailedJobs, FailedOptions, FailedPage, FailedQuery, FailedRow, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, ScopeMatch, SqlDatabase, SweepResult, } from "./core/types.ts";
2
+ export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./core/errors.ts";
3
+ export { inProcess } from "./core/in-process.ts";
4
+ export { defaultBackoff, storedReplaceKey } from "./core/jobs.ts";
5
+ export { createRegistry, describeModules, init } from "./core/registry.ts";