logic-sdk 0.4.0 → 0.6.0

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 (58) hide show
  1. package/README.md +40 -15
  2. package/bin/logic-sdk.js +1 -1
  3. package/dist/ai.d.ts +16 -26
  4. package/dist/ai.js +8 -21
  5. package/dist/cloudflare.d.ts +55 -0
  6. package/dist/cloudflare.js +85 -0
  7. package/dist/drizzle/pg.d.ts +236 -0
  8. package/dist/drizzle/pg.js +67 -0
  9. package/dist/drizzle/sqlite.d.ts +242 -0
  10. package/dist/drizzle/sqlite.js +194 -0
  11. package/dist/errors.d.ts +33 -0
  12. package/dist/errors.js +45 -0
  13. package/dist/fetch.d.ts +15 -18
  14. package/dist/fetch.js +18 -55
  15. package/dist/index.d.ts +78 -379
  16. package/dist/index.js +240 -186
  17. package/dist/jobs.d.ts +44 -0
  18. package/dist/jobs.js +252 -0
  19. package/dist/node.d.ts +26 -0
  20. package/dist/node.js +76 -0
  21. package/dist/orpc.d.ts +10 -17
  22. package/dist/orpc.js +19 -28
  23. package/dist/pg-boss.d.ts +55 -0
  24. package/dist/pg-boss.js +211 -0
  25. package/dist/postgres.d.ts +28 -0
  26. package/dist/postgres.js +82 -0
  27. package/dist/schedule.d.ts +23 -0
  28. package/dist/schedule.js +109 -0
  29. package/dist/sqlite.d.ts +9 -0
  30. package/dist/sqlite.js +65 -0
  31. package/dist/stored-jobs.d.ts +64 -0
  32. package/dist/stored-jobs.js +188 -0
  33. package/dist/testing.d.ts +50 -14
  34. package/dist/testing.js +198 -46
  35. package/dist/types.d.ts +655 -0
  36. package/dist/types.js +6 -0
  37. package/package.json +45 -7
  38. package/skills/logic-sdk/SKILL.md +114 -0
  39. package/src/ai.ts +23 -46
  40. package/src/cloudflare.ts +107 -0
  41. package/src/drizzle/pg.ts +110 -0
  42. package/src/drizzle/sqlite.ts +236 -0
  43. package/src/errors.ts +59 -0
  44. package/src/fetch.ts +17 -65
  45. package/src/index.ts +404 -564
  46. package/src/jobs.ts +296 -0
  47. package/src/node.ts +99 -0
  48. package/src/orpc.ts +24 -42
  49. package/src/pg-boss.ts +242 -0
  50. package/src/postgres.ts +90 -0
  51. package/src/schedule.ts +129 -0
  52. package/src/sqlite.ts +74 -0
  53. package/src/stored-jobs.ts +260 -0
  54. package/src/testing.ts +252 -55
  55. package/src/types.ts +685 -0
  56. package/dist/drizzle.d.ts +0 -18
  57. package/dist/drizzle.js +0 -23
  58. package/src/drizzle.ts +0 -39
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Logic SDK
2
2
 
3
- **Business logic for TypeScript apps, as queries, mutations, actions and events.**
3
+ **Business logic for TypeScript apps, as queries, mutations, actions, events, jobs and crons.**
4
4
 
5
5
  Write the layer between your routes and your database once, as plain declarations. Call it from an HTTP route, a Server Action, a queue worker, a script, a test or an AI agent: same rules, same transaction, same events.
6
6
 
@@ -10,7 +10,7 @@ Write the layer between your routes and your database once, as plain declaration
10
10
  npm i logic-sdk zod
11
11
  ```
12
12
 
13
- Node 24+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
13
+ Node 24+, Bun or Cloudflare Workers. Postgres or SQLite on a disk for mutations, through Drizzle or any ORM that can run SQL in a transaction.
14
14
 
15
15
  ## Quick start
16
16
 
@@ -18,7 +18,7 @@ Declare your types once, and who may do what:
18
18
 
19
19
  ```ts
20
20
  // src/logic.ts
21
- export const { query, mutation, action, event, on, createRegistry } = init<Config>();
21
+ export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
22
22
 
23
23
  // src/policies.ts: sync type guards over the scope
24
24
  export const anyone = () => true;
@@ -30,14 +30,12 @@ Write a module:
30
30
 
31
31
  ```ts
32
32
  // src/bookings/mutations.ts
33
+ /** Confirm a pending booking */
33
34
  export const confirm = mutation({
34
- description: "Confirm a pending booking",
35
35
  input: z.object({ bookingId: z.uuid() }),
36
36
  output: Booking,
37
37
  // Who may call it, on every call
38
38
  authorize: staff,
39
- // HTTP, oRPC and AI tools may publish it
40
- expose: true,
41
39
 
42
40
  async handler(ctx, input) {
43
41
  const booking = await findBooking(ctx, input.bookingId);
@@ -71,15 +69,37 @@ const caller = registry.as({ actor, accountId });
71
69
  await caller.run(bookings.confirm, { bookingId });
72
70
  ```
73
71
 
72
+ Work that must not be lost goes through a jobs adapter. Listeners, scheduled calls and crons all use it:
73
+
74
+ ```ts
75
+ const database = drizzleAdapter(db);
76
+
77
+ export const registry = createRegistry({
78
+ modules: { bookings, availability },
79
+ database,
80
+ jobs: { adapter: databaseQueue(database), scope: { store, load } },
81
+ });
82
+
83
+ // a listener, with tries
84
+ export const sendConfirmation = listener({ event: () => confirmed, attempts: 3, handler });
85
+
86
+ // a cron
87
+ export const morningDigest = cron({ schedule: "0 8 * * MON-FRI", run: () => sendDigest, scope: asSystem("digest") });
88
+
89
+ // later, from a mutation, committed with it
90
+ ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
91
+ ```
92
+
74
93
  ## What you get
75
94
 
76
95
  - **One transaction across modules.** A failure anywhere rolls back everything, even if someone catches it.
77
96
  - **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
78
- - **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction.
97
+ - **Jobs, four ways.** Your Postgres as the queue (`databaseQueue`), Cloudflare Queues alone, an outbox in front of a queue, or pg-boss. All but in-process can run a job twice, so make them idempotent.
98
+ - **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction: three tries, or `drizzleAdapter(db, { transactionAttempts })`.
79
99
  - **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
80
100
  - **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
81
- - **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
82
- - **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API. Opt-in, one function at a time or by `filter`.
101
+ - **Internal by default.** A function reaches clients only when you publish it: in your oRPC router or an agent's tools, which refuse one without `authorize`, or from your own route, which should only call functions that have one.
102
+ - **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API, one function at a time.
83
103
  - **Settings in one place.** Declare `config` once, fill it from env at the entry, read `ctx.config` anywhere. The CLI fails the build if a module reads env.
84
104
  - **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
85
105
  - **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
@@ -89,9 +109,15 @@ await caller.run(bookings.confirm, { bookingId });
89
109
 
90
110
  | Import | |
91
111
  |---|---|
92
- | `logic-sdk/drizzle` | The database adapter |
93
- | `logic-sdk/fetch` | A web-standard HTTP handler for exposed functions |
94
- | `logic-sdk/orpc` | A typed oRPC v2 router and client |
112
+ | `logic-sdk/drizzle/pg` | The database adapter, `databaseQueue` and `outbox` |
113
+ | `logic-sdk/postgres` | `databaseQueue` and `outbox` on Postgres with any ORM |
114
+ | `logic-sdk/drizzle/sqlite` | The same on SQLite: `drizzleAdapter(() => drizzle("app.db"))` |
115
+ | `logic-sdk/sqlite` | `databaseQueue` and `outbox` on SQLite with any ORM |
116
+ | `logic-sdk/cloudflare` | Cloudflare Queues and Cron Triggers |
117
+ | `logic-sdk/pg-boss` | Jobs in pg-boss |
118
+ | `logic-sdk/node` | `startTicking`: crons and sweeps in a long-running process |
119
+ | `logic-sdk/fetch` | `toResponse`: a domain error as an HTTP response, for your own routes |
120
+ | `logic-sdk/orpc` | `toORPCProcedure`: a function as an oRPC v2 procedure, for your router |
95
121
  | `logic-sdk/ai` | AI SDK tools: agents run your functions with the same rules |
96
122
  | `logic-sdk/testing` | Rolled-back test transactions, stubs, frozen time |
97
123
 
@@ -102,10 +128,9 @@ npm i -D @logic-sdk/cli
102
128
  npx logic-sdk list # every function, its kind and policy
103
129
  logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
104
130
  logic-sdk graph --format mermaid # who runs whom, who reacts to which event
105
- logic-sdk check # module boundaries, run cycles, no network in transactions, can* checks
106
131
  ```
107
132
 
108
- Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
133
+ Read-only, `--json` everywhere, exit codes for scripts. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
109
134
 
110
135
  ## Examples
111
136
 
@@ -114,7 +139,7 @@ Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships
114
139
 
115
140
  ## Docs
116
141
 
117
- The docs site lives in [`apps/web`](apps/web) (`bun run --filter web dev`). Start with the [introduction](apps/web/docs/index.mdx) and the [quickstart](apps/web/docs/02-quickstart.mdx). [`AGENTS.md`](AGENTS.md) is the short version for coding agents.
142
+ The docs site lives in [`apps/web`](apps/web) (`bun run --filter web dev`). Start with the [introduction](apps/web/docs/index.mdx) and the [quickstart](apps/web/docs/02-quickstart.mdx). The agent skill, [`skills/logic-sdk/SKILL.md`](packages/logic-sdk/skills/logic-sdk/SKILL.md), ships in the package: the short version for coding agents.
118
143
 
119
144
  ## Repository
120
145
 
package/bin/logic-sdk.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // `npx logic-sdk check`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
2
+ // `npx logic-sdk list`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
3
3
  // (a Worker, a Next.js app) don't download its parser and loader.
4
4
  const CLI = "@logic-sdk/cli";
5
5
 
package/dist/ai.d.ts CHANGED
@@ -1,26 +1,25 @@
1
1
  import { type Tool } from "ai";
2
- import { type Caller, type ExposedFn, type ExposedOf, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
3
- type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
4
- /** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
5
- export type AIToolsOf<Mods> = UnionToIntersection<{
6
- [M in keyof Mods & string]: {
7
- [N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<FnIn<Mods[M][N & keyof Mods[M]]>, FnOut<Mods[M][N & keyof Mods[M]]>>;
2
+ import { type Caller, type FnIn, type FnOut, type ForFunctions, type PublishableFn, type ScopeOfFn } from "./index.ts";
3
+ /**
4
+ * What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
5
+ * `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
6
+ */
7
+ export type AIMeta = ForFunctions<{
8
+ ai?: {
9
+ /** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
10
+ description?: string;
8
11
  };
9
- }[keyof Mods & string]>;
12
+ }>;
10
13
  export interface AIToolOptions {
14
+ /** Overrides `meta.ai.description` for this tool. */
15
+ description?: string;
11
16
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
12
17
  onError?: (error: unknown) => void;
13
18
  }
14
- export interface AIToolsOptions extends AIToolOptions {
15
- /**
16
- * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
17
- * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
18
- */
19
- filter: (fn: RegisteredFn) => boolean;
20
- }
21
19
  /**
22
- * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
23
- * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
20
+ * One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
21
+ * and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
22
+ * `authorize`: the model acts for someone else.
24
23
  *
25
24
  * ```ts
26
25
  * const caller = registry.as(await scopeFrom(request));
@@ -30,13 +29,4 @@ export interface AIToolsOptions extends AIToolOptions {
30
29
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
31
30
  * to `onError` and the model gets "internal_error", so internals never land in its context.
32
31
  */
33
- export declare function toAITool<F extends ExposedFn>(caller: Caller<object>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
34
- /**
35
- * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
36
- *
37
- * ```ts
38
- * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
39
- * ```
40
- */
41
- export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options: AIToolsOptions): Partial<AIToolsOf<Mods>>;
42
- export {};
32
+ export declare function toAITool<F extends PublishableFn>(caller: Caller<ScopeOfFn<F>>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
package/dist/ai.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { jsonSchema, tool } from "ai";
2
2
  import { isDomainError } from "./index.js";
3
+ /** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
4
+ const aiMeta = (fn) => fn.meta?.ai;
3
5
  /** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
4
6
  const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
5
7
  /**
6
- * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
7
- * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
8
+ * One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
9
+ * and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
10
+ * `authorize`: the model acts for someone else.
8
11
  *
9
12
  * ```ts
10
13
  * const caller = registry.as(await scopeFrom(request));
@@ -15,11 +18,11 @@ const noInput = jsonSchema({ type: "object", properties: {}, additionalPropertie
15
18
  * to `onError` and the model gets "internal_error", so internals never land in its context.
16
19
  */
17
20
  export function toAITool(caller, fn, options = {}) {
21
+ if (!fn.authorize)
22
+ throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
18
23
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
19
- if (fn.expose !== true)
20
- throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
21
24
  return tool({
22
- description: fn.description,
25
+ description: options.description ?? aiMeta(fn)?.description,
23
26
  inputSchema: fn.input ?? noInput,
24
27
  outputSchema: fn.output,
25
28
  async execute(input, { abortSignal }) {
@@ -35,19 +38,3 @@ export function toAITool(caller, fn, options = {}) {
35
38
  },
36
39
  });
37
40
  }
38
- /**
39
- * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
40
- *
41
- * ```ts
42
- * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
43
- * ```
44
- */
45
- export function toAITools(registry, caller, options) {
46
- if (typeof options?.filter !== "function")
47
- throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
48
- const tools = {};
49
- for (const f of registry.functions)
50
- if (f.exposed && options.filter(f))
51
- tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn, options);
52
- return tools;
53
- }
@@ -0,0 +1,55 @@
1
+ import type { Job, Jobs, JobsAdapter } from "./index.ts";
2
+ /** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
3
+ export interface QueueBinding {
4
+ sendBatch(messages: Iterable<{
5
+ body: Job;
6
+ delaySeconds?: number;
7
+ }>): Promise<unknown>;
8
+ }
9
+ /** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
10
+ export interface QueueBatch {
11
+ readonly messages: readonly {
12
+ readonly body: Job;
13
+ readonly attempts: number;
14
+ ack(): void;
15
+ retry(options?: {
16
+ delaySeconds?: number;
17
+ }): void;
18
+ }[];
19
+ }
20
+ /**
21
+ * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
22
+ * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
23
+ * Run them with `handleQueue(registry, batch)` in your consumer.
24
+ */
25
+ export declare function cloudflareQueue(queue: QueueBinding): JobsAdapter;
26
+ /**
27
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
28
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
29
+ * its own, so one failure doesn't redeliver the batch.
30
+ *
31
+ * ```ts
32
+ * async queue(batch, env, ctx) {
33
+ * await handleQueue(makeRegistry(env, ctx), batch);
34
+ * },
35
+ * ```
36
+ */
37
+ export declare function handleQueue(registry: {
38
+ jobs: Pick<Jobs, "run">;
39
+ }, batch: QueueBatch): Promise<void>;
40
+ /**
41
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
42
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
43
+ * 1 = Sunday, so write them as names (`MON`) in both places.
44
+ *
45
+ * ```ts
46
+ * async scheduled(controller, env, ctx) {
47
+ * await handleScheduled(makeRegistry(env, ctx), controller);
48
+ * },
49
+ * ```
50
+ */
51
+ export declare function handleScheduled(registry: {
52
+ jobs: Pick<Jobs, "tick" | "sweep">;
53
+ }, controller: {
54
+ readonly scheduledTime: number;
55
+ }): Promise<void>;
@@ -0,0 +1,85 @@
1
+ import { defaultBackoff } from "./stored-jobs.js";
2
+ // Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
3
+ const MAX_MESSAGES = 100;
4
+ const MAX_BATCH_BYTES = 256_000;
5
+ const MAX_MESSAGE_BYTES = 128_000;
6
+ /** Cloudflare counts about this much metadata per message toward the limits. */
7
+ const OVERHEAD_BYTES = 100;
8
+ /** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
9
+ const MAX_DELAY = 86_400;
10
+ const encoder = new TextEncoder();
11
+ /**
12
+ * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
13
+ * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
14
+ * Run them with `handleQueue(registry, batch)` in your consumer.
15
+ */
16
+ export function cloudflareQueue(queue) {
17
+ return {
18
+ holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
19
+ async deliver(jobs) {
20
+ for (const batch of batches(jobs))
21
+ await queue.sendBatch(batch);
22
+ },
23
+ };
24
+ }
25
+ /** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
26
+ function* batches(jobs) {
27
+ const sized = jobs.map((body) => {
28
+ const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
29
+ if (size > MAX_MESSAGE_BYTES)
30
+ throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
31
+ return { body, size };
32
+ });
33
+ let batch = [];
34
+ let bytes = 0;
35
+ for (const { body, size } of sized) {
36
+ if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
37
+ yield batch;
38
+ batch = [];
39
+ bytes = 0;
40
+ }
41
+ batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
42
+ bytes += size;
43
+ }
44
+ if (batch.length)
45
+ yield batch;
46
+ }
47
+ const secondsUntil = (iso) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
48
+ /**
49
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
50
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
51
+ * its own, so one failure doesn't redeliver the batch.
52
+ *
53
+ * ```ts
54
+ * async queue(batch, env, ctx) {
55
+ * await handleQueue(makeRegistry(env, ctx), batch);
56
+ * },
57
+ * ```
58
+ */
59
+ export async function handleQueue(registry, batch) {
60
+ for (const message of batch.messages) {
61
+ try {
62
+ await registry.jobs.run(message.body, { attempt: message.attempts });
63
+ message.ack();
64
+ }
65
+ catch {
66
+ // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
67
+ message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
68
+ }
69
+ }
70
+ }
71
+ /**
72
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
73
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
74
+ * 1 = Sunday, so write them as names (`MON`) in both places.
75
+ *
76
+ * ```ts
77
+ * async scheduled(controller, env, ctx) {
78
+ * await handleScheduled(makeRegistry(env, ctx), controller);
79
+ * },
80
+ * ```
81
+ */
82
+ export async function handleScheduled(registry, controller) {
83
+ await registry.jobs.tick(new Date(controller.scheduledTime));
84
+ await registry.jobs.sweep();
85
+ }
@@ -0,0 +1,236 @@
1
+ import { type SQL } from "drizzle-orm";
2
+ import type { DatabaseAdapter, Job, ReadWrite, SqlDatabase } from "../index.ts";
3
+ export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../postgres.ts";
4
+ /** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
5
+ interface Transactional {
6
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
7
+ execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
8
+ }
9
+ /** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
10
+ type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
11
+ /**
12
+ * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
13
+ * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
14
+ */
15
+ export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
16
+ /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
17
+ export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView">;
18
+ /**
19
+ * Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
20
+ * the transaction.
21
+ */
22
+ export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
23
+ export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
24
+ /**
25
+ * Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
26
+ * PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
27
+ * The types reject SQLite and libsql databases here.
28
+ */
29
+ export declare function drizzleAdapter<Db extends Transactional>(db: Db, options?: DrizzleAdapterOptions): SqlDatabase<Db, Transaction<Db>>;
30
+ /** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
31
+ export declare function sqlState(error: unknown): string | undefined;
32
+ /**
33
+ * The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
34
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
35
+ * done rows are deleted, failed ones stay so you can query them and `retry` them.
36
+ */
37
+ export declare const jobsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
38
+ name: "logic_jobs";
39
+ schema: undefined;
40
+ columns: {
41
+ id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
42
+ name: string;
43
+ tableName: "logic_jobs";
44
+ dataType: "string";
45
+ data: string;
46
+ driverParam: string;
47
+ notNull: true;
48
+ hasDefault: false;
49
+ isPrimaryKey: false;
50
+ isAutoincrement: false;
51
+ hasRuntimeDefault: false;
52
+ enumValues: undefined;
53
+ identity: undefined;
54
+ generated: undefined;
55
+ }>;
56
+ job: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgJsonbBuilder, Job>>, {
57
+ name: string;
58
+ tableName: "logic_jobs";
59
+ dataType: "object json";
60
+ data: Job;
61
+ driverParam: unknown;
62
+ notNull: true;
63
+ hasDefault: false;
64
+ isPrimaryKey: false;
65
+ isAutoincrement: false;
66
+ hasRuntimeDefault: false;
67
+ enumValues: undefined;
68
+ identity: undefined;
69
+ generated: undefined;
70
+ }>;
71
+ status: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, "failed" | "pending">>>, {
72
+ name: string;
73
+ tableName: "logic_jobs";
74
+ dataType: "string";
75
+ data: "failed" | "pending";
76
+ driverParam: string;
77
+ notNull: true;
78
+ hasDefault: true;
79
+ isPrimaryKey: false;
80
+ isAutoincrement: false;
81
+ hasRuntimeDefault: false;
82
+ enumValues: undefined;
83
+ identity: undefined;
84
+ generated: undefined;
85
+ }>;
86
+ attempts: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgIntegerBuilder>>, {
87
+ name: string;
88
+ tableName: "logic_jobs";
89
+ dataType: "number int32";
90
+ data: number;
91
+ driverParam: string | number;
92
+ notNull: true;
93
+ hasDefault: true;
94
+ isPrimaryKey: false;
95
+ isAutoincrement: false;
96
+ hasRuntimeDefault: false;
97
+ enumValues: undefined;
98
+ identity: undefined;
99
+ generated: undefined;
100
+ }>;
101
+ availableAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
102
+ name: string;
103
+ tableName: "logic_jobs";
104
+ dataType: "object date";
105
+ data: Date;
106
+ driverParam: string;
107
+ notNull: true;
108
+ hasDefault: true;
109
+ isPrimaryKey: false;
110
+ isAutoincrement: false;
111
+ hasRuntimeDefault: false;
112
+ enumValues: undefined;
113
+ identity: undefined;
114
+ generated: undefined;
115
+ }>;
116
+ receipt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
117
+ name: string;
118
+ tableName: "logic_jobs";
119
+ dataType: "string";
120
+ data: string;
121
+ driverParam: string;
122
+ notNull: false;
123
+ hasDefault: false;
124
+ isPrimaryKey: false;
125
+ isAutoincrement: false;
126
+ hasRuntimeDefault: false;
127
+ enumValues: undefined;
128
+ identity: undefined;
129
+ generated: undefined;
130
+ }>;
131
+ lastError: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
132
+ name: string;
133
+ tableName: "logic_jobs";
134
+ dataType: "string";
135
+ data: string;
136
+ driverParam: string;
137
+ notNull: false;
138
+ hasDefault: false;
139
+ isPrimaryKey: false;
140
+ isAutoincrement: false;
141
+ hasRuntimeDefault: false;
142
+ enumValues: undefined;
143
+ identity: undefined;
144
+ generated: undefined;
145
+ }>;
146
+ failedAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTimestampBuilder, {
147
+ name: string;
148
+ tableName: "logic_jobs";
149
+ dataType: "object date";
150
+ data: Date;
151
+ driverParam: string;
152
+ notNull: false;
153
+ hasDefault: false;
154
+ isPrimaryKey: false;
155
+ isAutoincrement: false;
156
+ hasRuntimeDefault: false;
157
+ enumValues: undefined;
158
+ identity: undefined;
159
+ generated: undefined;
160
+ }>;
161
+ replaceKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
162
+ name: string;
163
+ tableName: "logic_jobs";
164
+ dataType: "string";
165
+ data: string;
166
+ driverParam: string;
167
+ notNull: false;
168
+ hasDefault: false;
169
+ isPrimaryKey: false;
170
+ isAutoincrement: false;
171
+ hasRuntimeDefault: false;
172
+ enumValues: undefined;
173
+ identity: undefined;
174
+ generated: undefined;
175
+ }>;
176
+ createdAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
177
+ name: string;
178
+ tableName: "logic_jobs";
179
+ dataType: "object date";
180
+ data: Date;
181
+ driverParam: string;
182
+ notNull: true;
183
+ hasDefault: true;
184
+ isPrimaryKey: false;
185
+ isAutoincrement: false;
186
+ hasRuntimeDefault: false;
187
+ enumValues: undefined;
188
+ identity: undefined;
189
+ generated: undefined;
190
+ }>;
191
+ };
192
+ dialect: 'pg';
193
+ isAlias: false;
194
+ }>;
195
+ /**
196
+ * The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
197
+ * Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
198
+ */
199
+ export declare const cronRunsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
200
+ name: "logic_cron_runs";
201
+ schema: undefined;
202
+ columns: {
203
+ id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_cron_runs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
204
+ name: string;
205
+ tableName: "logic_cron_runs";
206
+ dataType: "string";
207
+ data: string;
208
+ driverParam: string;
209
+ notNull: true;
210
+ hasDefault: false;
211
+ isPrimaryKey: false;
212
+ isAutoincrement: false;
213
+ hasRuntimeDefault: false;
214
+ enumValues: undefined;
215
+ identity: undefined;
216
+ generated: undefined;
217
+ }>;
218
+ ranAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_cron_runs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
219
+ name: string;
220
+ tableName: "logic_cron_runs";
221
+ dataType: "object date";
222
+ data: Date;
223
+ driverParam: string;
224
+ notNull: true;
225
+ hasDefault: true;
226
+ isPrimaryKey: false;
227
+ isAutoincrement: false;
228
+ hasRuntimeDefault: false;
229
+ enumValues: undefined;
230
+ identity: undefined;
231
+ generated: undefined;
232
+ }>;
233
+ };
234
+ dialect: 'pg';
235
+ isAlias: false;
236
+ }>;