logic-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -0,0 +1,37 @@
1
+ import { ORPCError, os } from "@orpc/server";
2
+ import { isDomainError } from "../core/errors.js";
3
+ /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
4
+ export const orpcCodeOf = {
5
+ invalid: "BAD_REQUEST",
6
+ unauthenticated: "UNAUTHORIZED",
7
+ forbidden: "FORBIDDEN",
8
+ not_found: "NOT_FOUND",
9
+ conflict: "CONFLICT",
10
+ rejected: "UNPROCESSABLE_CONTENT",
11
+ };
12
+ /**
13
+ * One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
14
+ * own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
15
+ *
16
+ * ```ts
17
+ * export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
18
+ * new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
19
+ * ```
20
+ */
21
+ export function toORPCProcedure(fn) {
22
+ if (!fn.authorize)
23
+ throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
24
+ const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
25
+ const withInput = fn.input ? base.input(fn.input) : base;
26
+ const b = fn.output ? withInput.output(fn.output) : withInput;
27
+ return b.handler(async ({ input, context, signal }) => {
28
+ try {
29
+ return await context.caller.run(fn, input, { signal });
30
+ }
31
+ catch (e) {
32
+ if (isDomainError(e))
33
+ throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
34
+ throw e;
35
+ }
36
+ }); // SAFETY: the same procedure, typed from the function: its input, output and init's scope
37
+ }
package/dist/node.d.ts CHANGED
@@ -1,26 +1 @@
1
- import type { Jobs } from "./index.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>;
1
+ export { work, type StopOptions, type WorkOptions } from "./hosts/node.ts";
package/dist/node.js CHANGED
@@ -1,76 +1 @@
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
- }
1
+ export { work } from "./hosts/node.js";
package/dist/orpc.d.ts CHANGED
@@ -1,21 +1 @@
1
- import { type DecoratedProcedure } from "@orpc/server";
2
- import type { StandardSchemaV1 } from "@standard-schema/spec";
3
- import { type Caller, type ErrorKind, type Fn, type Kind, type PublishableFn, type ScopeOfFn } from "./index.ts";
4
- /** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
5
- export type ORPCContext<S extends object> = {
6
- caller: Caller<S>;
7
- };
8
- /** `toORPCProcedure(fn)`: an oRPC procedure, so `.use`, `.meta` and `.errors` work as on your own. */
9
- export type ProcedureOf<F> = F extends Fn<Kind, infer I, infer O> ? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
10
- /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
11
- export declare const orpcCodeOf: Record<ErrorKind, string>;
12
- /**
13
- * One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
14
- * own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
15
- *
16
- * ```ts
17
- * export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
18
- * new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
19
- * ```
20
- */
21
- export declare function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F>;
1
+ export { orpcCodeOf, toORPCProcedure, type ORPCContext, type ProcedureOf } from "./integrations/orpc.ts";
package/dist/orpc.js CHANGED
@@ -1,37 +1 @@
1
- import { ORPCError, os } from "@orpc/server";
2
- import { isDomainError } from "./index.js";
3
- /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
4
- export const orpcCodeOf = {
5
- invalid: "BAD_REQUEST",
6
- unauthenticated: "UNAUTHORIZED",
7
- forbidden: "FORBIDDEN",
8
- not_found: "NOT_FOUND",
9
- conflict: "CONFLICT",
10
- rejected: "UNPROCESSABLE_CONTENT",
11
- };
12
- /**
13
- * One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
14
- * own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
15
- *
16
- * ```ts
17
- * export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
18
- * new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
19
- * ```
20
- */
21
- export function toORPCProcedure(fn) {
22
- if (!fn.authorize)
23
- throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
24
- const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
25
- const withInput = fn.input ? base.input(fn.input) : base;
26
- const b = fn.output ? withInput.output(fn.output) : withInput;
27
- return b.handler(async ({ input, context, signal }) => {
28
- try {
29
- return await context.caller.run(fn, input, { signal });
30
- }
31
- catch (e) {
32
- if (isDomainError(e))
33
- throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
34
- throw e;
35
- }
36
- }); // SAFETY: the same procedure, typed from the function: its input, output and init's scope
37
- }
1
+ export { orpcCodeOf, toORPCProcedure } from "./integrations/orpc.js";
@@ -1,28 +1,2 @@
1
- import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
2
- import type { JobsAdapter, SqlDatabase } from "./index.ts";
3
- export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
4
- /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
5
- export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n last_error text,\n failed_at timestamptz,\n replace_key text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\n";
6
- /**
7
- * Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
8
- * a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
9
- * is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
10
- * its row being deleted runs it again.
11
- *
12
- * ```ts
13
- * const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
14
- * startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
15
- * ```
16
- */
17
- export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
18
- /**
19
- * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
20
- * until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
21
- * one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
22
- * so a job can run twice, even at once.
23
- *
24
- * ```ts
25
- * jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
26
- * ```
27
- */
28
- export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
1
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/postgres.ts";
2
+ export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
package/dist/postgres.js CHANGED
@@ -1,82 +1 @@
1
- // The jobs table on Postgres, in SQL. With Drizzle, import from `logic-sdk/drizzle/pg` instead: the same two
2
- // functions, plus the table for your schema.
3
- import { storedJobs } from "./stored-jobs.js";
4
- /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
5
- export const jobsSchema = `
6
- CREATE TABLE logic_jobs (
7
- id text PRIMARY KEY,
8
- job jsonb NOT NULL,
9
- status text NOT NULL DEFAULT 'pending',
10
- attempts integer NOT NULL DEFAULT 0,
11
- available_at timestamptz NOT NULL DEFAULT now(),
12
- receipt text,
13
- last_error text,
14
- failed_at timestamptz,
15
- replace_key text,
16
- created_at timestamptz NOT NULL DEFAULT now()
17
- );
18
- CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
19
- CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
20
- CREATE TABLE logic_cron_runs (
21
- id text PRIMARY KEY,
22
- ran_at timestamptz NOT NULL DEFAULT now()
23
- );
24
- `;
25
- // `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
26
- const ids = (n) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
27
- const mine = (n) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
28
- const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
29
- const statements = {
30
- // the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
31
- insert: `
32
- INSERT INTO logic_jobs (id, job, available_at, replace_key)
33
- SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
34
- FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
35
- ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
36
- DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
37
- recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
38
- pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
39
- claimNew: `
40
- UPDATE logic_jobs SET attempts = 1, receipt = $1, available_at = ${inSeconds(2)}
41
- WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
42
- // `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
43
- claimDue: `
44
- UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, available_at = ${inSeconds(2)}
45
- WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
46
- RETURNING job::text AS job, attempts`,
47
- extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
48
- backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2 WHERE ${mine(3)}`,
49
- markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now() WHERE ${mine(2)}`,
50
- remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
51
- // its receipt goes, so the runner that lost it can't finish the new run. Its key goes: it has run, so it's no longer
52
- // a call a newer one replaces (and one may be waiting with it)
53
- retry: `
54
- UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
55
- WHERE id = $1 AND status = 'failed' RETURNING id`,
56
- fail: `
57
- INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
58
- ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
59
- };
60
- /**
61
- * Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
62
- * a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
63
- * is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
64
- * its row being deleted runs it again.
65
- *
66
- * ```ts
67
- * const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
68
- * startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
69
- * ```
70
- */
71
- export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
72
- /**
73
- * The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
74
- * until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
75
- * one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
76
- * so a job can run twice, even at once.
77
- *
78
- * ```ts
79
- * jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
80
- * ```
81
- */
82
- export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
1
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/postgres.js";
package/dist/sqlite.d.ts CHANGED
@@ -1,9 +1,2 @@
1
- import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
2
- import type { JobsAdapter, SqlDatabase } from "./index.ts";
3
- export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
4
- /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
5
- export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n last_error text,\n failed_at integer,\n replace_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\n";
6
- /** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
7
- export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
8
- /** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
9
- export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
1
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.ts";
2
+ export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
package/dist/sqlite.js CHANGED
@@ -1,65 +1 @@
1
- // The jobs table on SQLite (3.42 or later, for `unixepoch('subsec')`), in SQL. With Drizzle, import from
2
- // `logic-sdk/drizzle/sqlite` instead: the same two functions, plus the table for your schema. Times are whole milliseconds since 1970, on SQLite's clock.
3
- // Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
4
- import { storedJobs } from "./stored-jobs.js";
5
- const now = `cast(unixepoch('subsec') * 1000 as integer)`;
6
- /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
7
- export const jobsSchema = `
8
- CREATE TABLE logic_jobs (
9
- id text PRIMARY KEY NOT NULL,
10
- job text NOT NULL,
11
- status text NOT NULL DEFAULT 'pending',
12
- attempts integer NOT NULL DEFAULT 0,
13
- available_at integer NOT NULL DEFAULT (${now}),
14
- receipt text,
15
- last_error text,
16
- failed_at integer,
17
- replace_key text,
18
- created_at integer NOT NULL DEFAULT (${now})
19
- );
20
- CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
21
- CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
22
- CREATE TABLE logic_cron_runs (
23
- id text PRIMARY KEY NOT NULL,
24
- ran_at integer NOT NULL DEFAULT (${now})
25
- );
26
- `;
27
- const ids = "(SELECT value FROM json_each(?))";
28
- const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
29
- const inSeconds = `${now} + cast(? * 1000 as integer)`;
30
- const statements = {
31
- // the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
32
- // the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
33
- insert: `
34
- INSERT INTO logic_jobs (id, job, available_at, replace_key)
35
- SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
36
- FROM json_each(?) WHERE true ORDER BY json_each.key
37
- ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
38
- DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
39
- RETURNING id`,
40
- recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
41
- pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
42
- claimNew: `
43
- UPDATE logic_jobs SET attempts = 1, receipt = ?, available_at = ${inSeconds}
44
- WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
45
- // no row locks to skip: SQLite has one writer at a time, and this statement is one write
46
- claimDue: `
47
- UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, available_at = ${inSeconds}
48
- WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
49
- RETURNING job, attempts`,
50
- extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
51
- backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ? WHERE ${mine} RETURNING id`,
52
- markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now} WHERE ${mine} RETURNING id`,
53
- remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
54
- retry: `
55
- UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
56
- WHERE id = ? AND status = 'failed' RETURNING id`,
57
- fail: `
58
- INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
59
- ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
60
- RETURNING id`,
61
- };
62
- /** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
63
- export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
64
- /** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
65
- export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
1
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.js";
package/dist/testing.d.ts CHANGED
@@ -1,75 +1 @@
1
- import { type Caller, type DeepPartial, type CallJob, type Cron, type Delivery, type Envelope, type Fn, type FnIn, type FnOut, type JobOutcome, type Listener, type Registry } from "./index.ts";
2
- export interface TestOptions<Cf = unknown> {
3
- /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
4
- services?: object;
5
- /** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
6
- config?: DeepPartial<Cf>;
7
- /** Freeze time. */
8
- now?: Date | string | (() => Date);
9
- /**
10
- * `"inline"` (default): listeners run right after each mutation, inside the test. `"manual"`: jobs wait in
11
- * `t.jobs.queued` until you `drain()` them, to test one module without the others reacting. Like Oban's
12
- * `testing: :inline | :manual`. Either way, what waits (a listener's `delay`, `ctx.schedule`) waits for `drain()`, and
13
- * your app's adapter (a database queue, an outbox, Cloudflare) is never used.
14
- */
15
- jobs?: "inline" | "manual";
16
- }
17
- /** The jobs of the current test, like `registry.jobs` in production. */
18
- export interface TestJobs<S> {
19
- /** Listener jobs waiting: every one in `jobs: "manual"`, and the delayed ones in either mode. */
20
- readonly queued: readonly Delivery[];
21
- /** What `ctx.schedule` asked for, waiting for `drain()`. */
22
- readonly scheduled: readonly CallJob[];
23
- /**
24
- * Run what's due at the test's now (or `until`), and what that queues, until nothing due is left. Throws a failure.
25
- * Like Rails' `perform_enqueued_jobs(at:)` and Oban's `drain_queue(with_scheduled:)`.
26
- */
27
- drain(options?: {
28
- until?: Date | string;
29
- }): Promise<void>;
30
- /** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
31
- perform<O>(listener: Listener<O>, payload: O, options: {
32
- scope: S;
33
- attempt?: number;
34
- }): Promise<JobOutcome>;
35
- /**
36
- * Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
37
- * its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
38
- */
39
- perform(cron: Cron, options?: {
40
- at?: Date | string;
41
- attempt?: number;
42
- }): Promise<JobOutcome>;
43
- /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
44
- tick(at?: Date | string): Promise<string[]>;
45
- }
46
- export interface TestRegistry<S extends object, Mods extends Record<string, object>, Cf> {
47
- /** Open the test's transaction: `beforeEach(() => t.begin())`. */
48
- begin(): Promise<void>;
49
- /** Roll it back: `afterEach(() => t.rollback())`. */
50
- rollback(): Promise<void>;
51
- /** Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it. */
52
- as(scope: S): Caller<S>;
53
- /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
54
- stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
55
- /** Every event emitted (and committed) in this test, in order. */
56
- readonly events: readonly Envelope[];
57
- /** The test transaction itself: read rows to assert on them. */
58
- readonly db: any;
59
- /** The registry bound to this test's transaction, for adapters: an oRPC context's `caller: t.registry.as(scope)`. */
60
- readonly registry: Registry<S, Mods, Cf>;
61
- readonly jobs: TestJobs<S>;
62
- }
63
- /**
64
- * Run each test inside a transaction that's rolled back, set up once with hooks:
65
- *
66
- * ```ts
67
- * const t = createTestRegistry(registry);
68
- * beforeEach(() => t.begin());
69
- * afterEach(() => t.rollback());
70
- * ```
71
- *
72
- * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
73
- * would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
74
- */
75
- export declare function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>, options?: TestOptions<Cf>): TestRegistry<S, Mods, Cf>;
1
+ export { createTestRegistry, type TestJobs, type TestOptions, type TestRegistry } from "./core/testing.ts";