logic-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -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,43 @@
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). One message at a time, each acknowledged on its own, so one failure doesn't
16
+ * redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
17
+ * job runs from its row (with a `key`, the key's next jobs, in order), and a throw means the table couldn't be reached.
18
+ *
19
+ * ```ts
20
+ * async queue(batch, env, ctx) {
21
+ * await handleQueue(makeRegistry(env, ctx), batch);
22
+ * },
23
+ * ```
24
+ */
25
+ export declare function handleQueue(registry: {
26
+ jobs: Pick<Jobs, "run">;
27
+ }, batch: QueueBatch): Promise<void>;
28
+ /**
29
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
30
+ * delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
31
+ * 1 = Sunday, so write them as names (`MON`) in both places.
32
+ *
33
+ * ```ts
34
+ * async scheduled(controller, env, ctx) {
35
+ * await handleScheduled(makeRegistry(env, ctx), controller);
36
+ * },
37
+ * ```
38
+ */
39
+ export declare function handleScheduled(registry: {
40
+ jobs: Pick<Jobs, "tick" | "sweep">;
41
+ }, controller: {
42
+ readonly scheduledTime: number;
43
+ }): Promise<void>;
@@ -0,0 +1,40 @@
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). One message at a time, each acknowledged on its own, so one failure doesn't
5
+ * redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
6
+ * job runs from its row (with a `key`, the key's next jobs, in order), and a throw means the table couldn't be reached.
7
+ *
8
+ * ```ts
9
+ * async queue(batch, env, ctx) {
10
+ * await handleQueue(makeRegistry(env, ctx), batch);
11
+ * },
12
+ * ```
13
+ */
14
+ export async function handleQueue(registry, batch) {
15
+ for (const message of batch.messages) {
16
+ try {
17
+ await registry.jobs.run(message.body, { attempt: message.attempts });
18
+ message.ack();
19
+ }
20
+ catch {
21
+ // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
22
+ message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
23
+ }
24
+ }
25
+ }
26
+ /**
27
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
28
+ * delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
29
+ * 1 = Sunday, so write them as names (`MON`) in both places.
30
+ *
31
+ * ```ts
32
+ * async scheduled(controller, env, ctx) {
33
+ * await handleScheduled(makeRegistry(env, ctx), controller);
34
+ * },
35
+ * ```
36
+ */
37
+ export async function handleScheduled(registry, controller) {
38
+ await registry.jobs.tick(new Date(controller.scheduledTime));
39
+ await registry.jobs.sweep();
40
+ }
@@ -0,0 +1,36 @@
1
+ import type { Jobs } from "../core/types.ts";
2
+ export interface WorkOptions {
3
+ /** Jobs this process runs at once. Default 1, like pg-boss, graphile-worker and a Laravel worker: run more processes, or raise it. */
4
+ concurrency?: number;
5
+ /** Seconds a free slot waits before it looks for a job again, when there was none. Default 2, like pg-boss and graphile-worker. */
6
+ pollEvery?: number;
7
+ /**
8
+ * The queues it runs, in order: each claim takes the first one with a job due, so `["mail", "default"]` sends mail
9
+ * first. Each one of `jobs.queues`, or `"default"`. Default: every queue, oldest due first.
10
+ */
11
+ queues?: readonly string[];
12
+ /** Where a failed tick or claim goes, and a skipped minute. Default `console.error`. */
13
+ onError?: (error: unknown) => void;
14
+ }
15
+ export interface StopOptions {
16
+ /** Seconds to wait for the running jobs and ticks before giving up on them. Default 30, like pg-boss's `stop()`. */
17
+ timeout?: number;
18
+ }
19
+ /**
20
+ * A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
21
+ * due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
22
+ * ticked on every minute. Run as many as you like: a job is claimed once, and a cron's minute runs once. A minute the
23
+ * process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
24
+ * answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
25
+ * apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
26
+ * waits for the running jobs and ticks, `timeout` seconds at most.
27
+ *
28
+ * ```ts
29
+ * import { work } from "logic-sdk/node";
30
+ * const stop = work(registry, { concurrency: 5 });
31
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); });
32
+ * ```
33
+ */
34
+ export declare function work(registry: {
35
+ jobs: Pick<Jobs, "tick" | "sweep" | "attach">;
36
+ }, options?: WorkOptions): (options?: StopOptions) => Promise<void>;
@@ -0,0 +1,103 @@
1
+ const MINUTE = 60_000;
2
+ /**
3
+ * Ticks still running before the next is skipped (reported). Overlap is normal, like Laravel and Oban: a slow cron
4
+ * doesn't hold back the next minute. Ten still running means they're stuck (the database is unreachable), and letting
5
+ * them pile up would run a backlog of stale minutes when it comes back.
6
+ */
7
+ const MAX_RUNNING = 10;
8
+ /** The longest a slot waits between claims while they throw (the database is down), so an outage is reported less and less often. */
9
+ const MAX_WAIT = 30;
10
+ /**
11
+ * A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
12
+ * due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
13
+ * ticked on every minute. Run as many as you like: a job is claimed once, and a cron's minute runs once. A minute the
14
+ * process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
15
+ * answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
16
+ * apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
17
+ * waits for the running jobs and ticks, `timeout` seconds at most.
18
+ *
19
+ * ```ts
20
+ * import { work } from "logic-sdk/node";
21
+ * const stop = work(registry, { concurrency: 5 });
22
+ * process.on("SIGTERM", async () => { await stop(); process.exit(0); });
23
+ * ```
24
+ */
25
+ export function work(registry, options = {}) {
26
+ const { concurrency = 1, pollEvery = 2, queues } = options;
27
+ const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
28
+ const onError = (error) => {
29
+ try {
30
+ reportTo(error);
31
+ }
32
+ catch (inner) {
33
+ console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
34
+ }
35
+ };
36
+ let stopping = false;
37
+ /** The sleeping slots: a commit wakes as many as it has jobs, `stop()` all of them. */
38
+ const wakes = new Set();
39
+ const wakeUp = (count = Infinity) => {
40
+ for (const wake of [...wakes].slice(0, count))
41
+ wake();
42
+ };
43
+ /** Resolves after `seconds`, or at once on `stop()`. */
44
+ const sleep = (seconds) => new Promise((resolve) => {
45
+ const wake = () => {
46
+ clearTimeout(timer);
47
+ wakes.delete(wake);
48
+ resolve();
49
+ };
50
+ const timer = setTimeout(wake, seconds * 1000);
51
+ wakes.add(wake);
52
+ });
53
+ /** One job at a time: the next due one, back to back while there are some. */
54
+ async function slot() {
55
+ let wait = pollEvery;
56
+ while (!stopping) {
57
+ try {
58
+ const { done, failed, discarded, retrying } = await registry.jobs.sweep({ limit: 1, queues });
59
+ wait = pollEvery;
60
+ if (done + failed + discarded + retrying)
61
+ continue;
62
+ }
63
+ catch (error) {
64
+ onError(error);
65
+ wait = Math.min(wait * 2, MAX_WAIT);
66
+ }
67
+ await sleep(wait);
68
+ }
69
+ }
70
+ const ticks = new Set();
71
+ let tickTimer;
72
+ const startOfMinute = (ms) => Math.floor(ms / MINUTE) * MINUTE;
73
+ const tick = (at) => {
74
+ if (ticks.size >= MAX_RUNNING) {
75
+ onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
76
+ return;
77
+ }
78
+ const run = registry.jobs.tick(at).then(() => { }, onError);
79
+ ticks.add(run);
80
+ void run.finally(() => ticks.delete(run));
81
+ };
82
+ const armTick = (minute) => {
83
+ tickTimer = setTimeout(() => {
84
+ // early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
85
+ const due = Math.max(minute, startOfMinute(Date.now()));
86
+ armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
87
+ tick(new Date(due));
88
+ }, minute - Date.now());
89
+ };
90
+ const detach = registry.jobs.attach({ wake: wakeUp, queues }); // first: it throws on a queue jobs.queues doesn't declare
91
+ armTick(startOfMinute(Date.now()) + MINUTE);
92
+ const slots = Array.from({ length: concurrency }, slot);
93
+ return async ({ timeout = 30 } = {}) => {
94
+ stopping = true;
95
+ detach(); // requests run their own jobs again
96
+ clearTimeout(tickTimer);
97
+ wakeUp();
98
+ let timer;
99
+ const gaveUp = new Promise((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
100
+ await Promise.race([Promise.all([...slots, ...ticks]), gaveUp]);
101
+ clearTimeout(timer);
102
+ };
103
+ }
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, LocalWorker, 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, SweepOptions, 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, storedUniqueKey } from "./core/jobs.ts";
5
+ export { createRegistry, describeModules, init } from "./core/registry.ts";