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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -12,6 +12,7 @@
12
12
  "drizzle",
13
13
  "events",
14
14
  "mutations",
15
+ "pg-boss",
15
16
  "queries",
16
17
  "tools",
17
18
  "transactions",
@@ -46,9 +47,33 @@
46
47
  "types": "./dist/index.d.ts",
47
48
  "default": "./dist/index.js"
48
49
  },
49
- "./drizzle": {
50
- "types": "./dist/drizzle.d.ts",
51
- "default": "./dist/drizzle.js"
50
+ "./postgres": {
51
+ "types": "./dist/postgres.d.ts",
52
+ "default": "./dist/postgres.js"
53
+ },
54
+ "./sqlite": {
55
+ "types": "./dist/sqlite.d.ts",
56
+ "default": "./dist/sqlite.js"
57
+ },
58
+ "./drizzle/sqlite": {
59
+ "types": "./dist/drizzle/sqlite.d.ts",
60
+ "default": "./dist/drizzle/sqlite.js"
61
+ },
62
+ "./drizzle/pg": {
63
+ "types": "./dist/drizzle/pg.d.ts",
64
+ "default": "./dist/drizzle/pg.js"
65
+ },
66
+ "./cloudflare": {
67
+ "types": "./dist/cloudflare.d.ts",
68
+ "default": "./dist/cloudflare.js"
69
+ },
70
+ "./pg-boss": {
71
+ "types": "./dist/pg-boss.d.ts",
72
+ "default": "./dist/pg-boss.js"
73
+ },
74
+ "./node": {
75
+ "types": "./dist/node.d.ts",
76
+ "default": "./dist/node.js"
52
77
  },
53
78
  "./testing": {
54
79
  "types": "./dist/testing.d.ts",
@@ -71,7 +96,8 @@
71
96
  "files": [
72
97
  "dist",
73
98
  "src",
74
- "bin"
99
+ "bin",
100
+ "skills"
75
101
  ],
76
102
  "publishConfig": {
77
103
  "access": "public"
@@ -84,13 +110,21 @@
84
110
  },
85
111
  "peerDependencies": {
86
112
  "@orpc/server": ">=2.0.0-beta.51 <3",
113
+ "drizzle-orm": ">=1.0.0-rc.6 <2",
114
+ "pg-boss": ">=12.39.0 <13",
87
115
  "ai": ">=7 <8",
88
- "@logic-sdk/cli": ">=0.4.0 <0.5.0"
116
+ "@logic-sdk/cli": ">=0.6.0 <0.7.0"
89
117
  },
90
118
  "peerDependenciesMeta": {
91
119
  "@orpc/server": {
92
120
  "optional": true
93
121
  },
122
+ "drizzle-orm": {
123
+ "optional": true
124
+ },
125
+ "pg-boss": {
126
+ "optional": true
127
+ },
94
128
  "ai": {
95
129
  "optional": true
96
130
  },
@@ -99,10 +133,14 @@
99
133
  }
100
134
  },
101
135
  "devDependencies": {
136
+ "@electric-sql/pglite": "^0.5.16",
102
137
  "@orpc/server": "2.0.0-beta.51",
103
138
  "@types/bun": "^1.4.4",
104
139
  "ai": "^7.0.177",
105
- "drizzle-orm": "1.0.0-rc.5",
140
+ "croner": "11.0.1",
141
+ "drizzle-orm": "1.0.0-rc.6",
142
+ "pg-boss": "12.39.0",
143
+ "postgres": "^4.1.1",
106
144
  "zod": "^4.6.7"
107
145
  }
108
146
  }
@@ -0,0 +1,114 @@
1
+ ---
2
+ name: logic-sdk
3
+ description: Write and change business logic with logic-sdk (queries, mutations, actions, events, listeners, policies, modules, tests). Use when adding a module or function, wiring createRegistry, writing authorize policies or can* checks, emitting events, or testing with createTestRegistry.
4
+ ---
5
+
6
+ # Business logic with logic-sdk
7
+
8
+ Follow this exactly. Every module looks the same.
9
+
10
+ ## Where things go
11
+
12
+ ```
13
+ src/
14
+ logic.ts export const { query, mutation, action, event, listener, createRegistry } = init<Config>(); // Config's db: DrizzleDb<Db>, so queries can't write
15
+ policies.ts Scope type and policies: sync type guards over scope (anyone, member, admin)
16
+ registry.ts createRegistry({ modules: { bookings, ... } }) // only what this init() defined: another's is a type error
17
+ rpc.ts export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } } // the API: only what's listed is reachable
18
+ <module>/
19
+ index.ts export * from each public file below. Other modules import ONLY this.
20
+ queries.ts query({...}) reads
21
+ mutations.ts mutation({...}) writes, one transaction (no nested ctx.db.transaction: its events would escape a rollback)
22
+ actions.ts action({...}) network calls: payments, email, AI, webhooks out
23
+ events.ts event({...}) things that happened
24
+ listeners.ts listener({...}) reacting to OTHER modules' events
25
+ data.ts private helpers taking ctx (findBooking(ctx, id)) and can* record checks. Never imported by other modules.
26
+ schema.ts tables this module owns. Other modules never read them.
27
+ <module>.test.ts
28
+ ```
29
+
30
+ New module: create the folder, then add one line to `createRegistry({ modules })` in `src/registry.ts`.
31
+
32
+ ## Writing a function
33
+
34
+ ```ts
35
+ // policies.ts
36
+ export type Scope = SignedOutScope | MemberScope; // a union, so guards narrow it
37
+ export const anyone = () => true;
38
+ export const member = (s: Scope): s is MemberScope => s.actor !== null;
39
+ export const admin = (s: Scope): s is AdminScope => s.actor?.role === "admin";
40
+
41
+ // bookings/data.ts
42
+ export const canCancel = (actor: Actor, b: BookingRow) => actor.role === "admin" || b.createdBy === actor.id;
43
+
44
+ // bookings/mutations.ts
45
+ /** Cancel a booking and free its dates */
46
+ export const cancel = mutation({
47
+ input: z.object({ bookingId: z.uuid() }),
48
+ output: Booking, // what callers may see: unknown fields stripped
49
+ authorize: member, // who may call it, on every call; narrows ctx.scope
50
+ async handler(ctx, input) {
51
+ const b = await findBooking(ctx, input.bookingId); // account-scoped: other accounts' ids are 404
52
+ if (!canCancel(ctx.scope.actor, b)) throw ctx.errors.deny(); // 403
53
+ if (b.status === "cancelled") throw ctx.errors.reject("already_cancelled"); // code "bookings.already_cancelled"
54
+ await ctx.run(availability.release, { sourceId: b.id }); // other module: through its index, with run()
55
+ const updated = await setStatus(ctx, b.id, "cancelled"); // same module: a plain helper
56
+ ctx.emit(cancelled, { bookingId: b.id });
57
+ return updated;
58
+ },
59
+ });
60
+ ```
61
+
62
+ ## Rules
63
+
64
+ 1. **Pick the kind by what it touches.** Only reads: `query`. Writes to our database: `mutation`. Talks to the network: `action`. Reacts to another module: `listener`.
65
+ 2. **Never put side effects in a mutation or query.** No email, HTTP or payments. They don't have `services` on purpose. Emit an event and react in a listener, or write an action that runs the mutation.
66
+ 3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages.
67
+ 4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing.
68
+ 5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
69
+ 6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
70
+ 7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
71
+ 8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error.
72
+ 9. **Need the result? `run` it. Just a consequence? `emit`** and let the owning module react in its `listeners.ts`.
73
+ 10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners.
74
+ 11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, change the scope for that call: `ctx.run(fn, input, { scope: { actor: system } })`.
75
+ 12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
76
+ 13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
77
+ 14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`.
78
+ 15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
79
+ 16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database, jobs: { adapter: databaseQueue(database), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(database, cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe, and `delay: 60` (seconds) to run it later.
80
+ 17. **Scheduled work is a `cron`,** exported from the module like a listener: `cron({ schedule: "0 9 * * MON", run: () => fn, scope: asSystem("reports.weekly") })`, where `asSystem` builds a `System` variant of the app's `Scope` (`actor: null`, `system: name`, never built from a request) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. `run` is an existing function (it keeps its policy); never put the work in the cron itself. On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)`.
81
+ 18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). The function re-checks its reason when it runs ("still confirmed?"): there's no cancel. Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: bookingId`: the newer call replaces the waiting one, so it doesn't run twice. It needs `jobs: { adapter: databaseQueue(database), scope: { store, load } }`, an `outbox` or `pgBoss(boss)` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
82
+
83
+ ## Tests
84
+
85
+ ```ts
86
+ const mailer = memoryMailer();
87
+ const t = createTestRegistry(registry, {
88
+ services: { mailer },
89
+ now: "2026-07-01T10:00:00Z",
90
+ config: { orders: { maxItems: 1 } }, // any part of config; merged over the registry's
91
+ });
92
+ beforeEach(async () => {
93
+ mailer.sent.length = 0; // fresh memory services per test
94
+ await t.begin(); // each test in a transaction that's rolled back
95
+ });
96
+ afterEach(() => t.rollback());
97
+
98
+ test("cancel frees the dates", async () => {
99
+ const agent = t.as(scopeAs("agent"));
100
+ // arrange with real functions, not inserts
101
+ // act: await agent.run(bookings.cancel, { bookingId })
102
+ // assert on rows (t.db), t.events, and memory services
103
+ });
104
+ ```
105
+
106
+ - Use the real database. Don't mock modules. If you must simulate a failure elsewhere: `t.stub(availability.hold, async () => { throw … })`.
107
+ - A failing listener makes `run` throw in tests. `createTestRegistry(registry, { jobs: "manual" })` keeps jobs in `t.jobs.queued` to test one module alone; `t.jobs.drain()` runs them, `t.jobs.perform(listener, payload, { scope })` runs one.
108
+ - Test the deny path: another account's id is `not_found`, a caller who fails `authorize` or `can*` is `forbidden`.
109
+
110
+ ## Done means
111
+
112
+ `tsc` passes and the tests pass. Every new mutation has a test for its main rule.
113
+
114
+ Before changing a function, look it up: `logic-sdk show bookings.confirm --json` gives its schemas, policy, record checks, what it runs and emits, and who calls it. `logic-sdk graph --module bookings` shows a module's connections.
package/src/ai.ts CHANGED
@@ -1,37 +1,34 @@
1
1
  import { jsonSchema, tool, type Tool } from "ai";
2
- import { isDomainError, 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;
2
+ import { isDomainError, type Caller, type FnIn, type FnOut, type ForFunctions, type PublishableFn, type ScopeOfFn } from "./index.ts";
4
3
 
5
- /** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
6
- export type AIToolsOf<Mods> = UnionToIntersection<
7
- {
8
- [M in keyof Mods & string]: {
9
- [N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<
10
- FnIn<Mods[M][N & keyof Mods[M]]>,
11
- FnOut<Mods[M][N & keyof Mods[M]]>
12
- >;
13
- };
14
- }[keyof Mods & string]
15
- >;
4
+ /**
5
+ * What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
6
+ * `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
7
+ */
8
+ export type AIMeta = ForFunctions<{
9
+ ai?: {
10
+ /** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
11
+ description?: string;
12
+ };
13
+ }>;
16
14
 
17
15
  export interface AIToolOptions {
16
+ /** Overrides `meta.ai.description` for this tool. */
17
+ description?: string;
18
18
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
19
19
  onError?: (error: unknown) => void;
20
20
  }
21
- export interface AIToolsOptions extends AIToolOptions {
22
- /**
23
- * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
24
- * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
25
- */
26
- filter: (fn: RegisteredFn) => boolean;
27
- }
21
+
22
+ /** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
23
+ const aiMeta = (fn: { meta?: Readonly<Record<string, unknown>> }) => fn.meta?.ai as { description?: string } | undefined;
28
24
 
29
25
  /** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
30
26
  const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
31
27
 
32
28
  /**
33
- * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
34
- * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
29
+ * One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
30
+ * and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
31
+ * `authorize`: the model acts for someone else.
35
32
  *
36
33
  * ```ts
37
34
  * const caller = registry.as(await scopeFrom(request));
@@ -41,15 +38,15 @@ const noInput = jsonSchema({ type: "object", properties: {}, additionalPropertie
41
38
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
42
39
  * to `onError` and the model gets "internal_error", so internals never land in its context.
43
40
  */
44
- export function toAITool<F extends ExposedFn>(
45
- caller: Caller<object>,
41
+ export function toAITool<F extends PublishableFn>(
42
+ caller: Caller<ScopeOfFn<F>>,
46
43
  fn: F,
47
44
  options: AIToolOptions = {},
48
45
  ): Tool<FnIn<F>, FnOut<F>> {
46
+ if (!fn.authorize) throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
49
47
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
50
- if (fn.expose !== true) throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
51
48
  return tool({
52
- description: fn.description,
49
+ description: options.description ?? aiMeta(fn)?.description,
53
50
  inputSchema: fn.input ?? noInput,
54
51
  outputSchema: fn.output,
55
52
  async execute(input, { abortSignal }) {
@@ -63,23 +60,3 @@ export function toAITool<F extends ExposedFn>(
63
60
  },
64
61
  }) as Tool<FnIn<F>, FnOut<F>>;
65
62
  }
66
-
67
- /**
68
- * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
69
- *
70
- * ```ts
71
- * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
72
- * ```
73
- */
74
- export function toAITools<S extends object, Mods extends Record<string, object>>(
75
- registry: Registry<S, Mods>,
76
- caller: Caller<S>,
77
- options: AIToolsOptions,
78
- ): Partial<AIToolsOf<Mods>> {
79
- if (typeof options?.filter !== "function")
80
- throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
81
- const tools: Record<string, Tool> = {};
82
- for (const f of registry.functions)
83
- if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as ExposedFn, options);
84
- return tools as Partial<AIToolsOf<Mods>>;
85
- }
@@ -0,0 +1,107 @@
1
+ import type { Job, Jobs, JobsAdapter } from "./index.ts";
2
+ import { defaultBackoff } from "./stored-jobs.ts";
3
+
4
+ /** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
5
+ export interface QueueBinding {
6
+ sendBatch(messages: Iterable<{ body: Job; delaySeconds?: number }>): Promise<unknown>;
7
+ }
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?: { delaySeconds?: number }): void;
16
+ }[];
17
+ }
18
+
19
+ // Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
20
+ const MAX_MESSAGES = 100;
21
+ const MAX_BATCH_BYTES = 256_000;
22
+ const MAX_MESSAGE_BYTES = 128_000;
23
+ /** Cloudflare counts about this much metadata per message toward the limits. */
24
+ const OVERHEAD_BYTES = 100;
25
+ /** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
26
+ const MAX_DELAY = 86_400;
27
+ const encoder = new TextEncoder();
28
+
29
+ /**
30
+ * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
31
+ * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
32
+ * Run them with `handleQueue(registry, batch)` in your consumer.
33
+ */
34
+ export function cloudflareQueue(queue: QueueBinding): JobsAdapter {
35
+ return {
36
+ holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
37
+ async deliver(jobs) {
38
+ for (const batch of batches(jobs)) await queue.sendBatch(batch);
39
+ },
40
+ };
41
+ }
42
+
43
+ /** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
44
+ function* batches(jobs: Job[]) {
45
+ const sized = jobs.map((body) => {
46
+ const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
47
+ if (size > MAX_MESSAGE_BYTES)
48
+ throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
49
+ return { body, size };
50
+ });
51
+ let batch: { body: Job; delaySeconds?: number }[] = [];
52
+ let bytes = 0;
53
+ for (const { body, size } of sized) {
54
+ if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
55
+ yield batch;
56
+ batch = [];
57
+ bytes = 0;
58
+ }
59
+ batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
60
+ bytes += size;
61
+ }
62
+ if (batch.length) yield batch;
63
+ }
64
+
65
+ const secondsUntil = (iso: string) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
66
+
67
+ /**
68
+ * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
69
+ * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
70
+ * its own, so one failure doesn't redeliver the batch.
71
+ *
72
+ * ```ts
73
+ * async queue(batch, env, ctx) {
74
+ * await handleQueue(makeRegistry(env, ctx), batch);
75
+ * },
76
+ * ```
77
+ */
78
+ export async function handleQueue(registry: { jobs: Pick<Jobs, "run"> }, batch: QueueBatch): Promise<void> {
79
+ for (const message of batch.messages) {
80
+ try {
81
+ await registry.jobs.run(message.body, { attempt: message.attempts });
82
+ message.ack();
83
+ } catch {
84
+ // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
85
+ message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
86
+ }
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
92
+ * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
93
+ * 1 = Sunday, so write them as names (`MON`) in both places.
94
+ *
95
+ * ```ts
96
+ * async scheduled(controller, env, ctx) {
97
+ * await handleScheduled(makeRegistry(env, ctx), controller);
98
+ * },
99
+ * ```
100
+ */
101
+ export async function handleScheduled(
102
+ registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
103
+ controller: { readonly scheduledTime: number },
104
+ ): Promise<void> {
105
+ await registry.jobs.tick(new Date(controller.scheduledTime));
106
+ await registry.jobs.sweep();
107
+ }
@@ -0,0 +1,110 @@
1
+ import { sql, type SQL } from "drizzle-orm";
2
+ import { index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
3
+ import type { DatabaseAdapter, Job, ReadWrite, SqlDatabase } from "../index.ts";
4
+ import { causes } from "../errors.ts";
5
+
6
+ export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../postgres.ts";
7
+
8
+ /** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
9
+ interface Transactional {
10
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
11
+ execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
12
+ }
13
+
14
+ /** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
15
+ type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
16
+
17
+ /**
18
+ * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
19
+ * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
20
+ */
21
+ export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
22
+
23
+ /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
24
+ export type DrizzleReader<Db> = Omit<
25
+ Db,
26
+ "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView"
27
+ >;
28
+
29
+ /**
30
+ * Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
31
+ * the transaction.
32
+ */
33
+ export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
34
+
35
+ export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
36
+
37
+ /**
38
+ * Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
39
+ * PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
40
+ * The types reject SQLite and libsql databases here.
41
+ */
42
+ export function drizzleAdapter<Db extends Transactional>(
43
+ db: Db,
44
+ options: DrizzleAdapterOptions = {},
45
+ ): SqlDatabase<Db, Transaction<Db>> { // the whole transaction, for `nest`; mutations see it as a DrizzleTx
46
+ return {
47
+ db,
48
+ transactionAttempts: options.transactionAttempts,
49
+ transaction: (fn) => db.transaction(fn),
50
+ nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
51
+ retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
52
+ query: async (client: Transactional, text, params) => client.execute(toSql(text, params), "objects"),
53
+ };
54
+ }
55
+
56
+ /** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
57
+ const toSql = (text: string, params: unknown[]) =>
58
+ sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
59
+
60
+ /** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
61
+ const RETRYABLE = new Set(["40001", "40P01"]);
62
+
63
+ /** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
64
+ export function sqlState(error: unknown): string | undefined {
65
+ for (const e of causes(error)) if ("code" in e && typeof e.code === "string") return e.code;
66
+ return undefined;
67
+ }
68
+
69
+ /**
70
+ * The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
71
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
72
+ * done rows are deleted, failed ones stay so you can query them and `retry` them.
73
+ */
74
+ export const jobsTable = pgTable(
75
+ "logic_jobs",
76
+ {
77
+ /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
78
+ id: text("id").primaryKey(),
79
+ job: jsonb("job").$type<Job>().notNull(),
80
+ /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
81
+ status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
82
+ /** Incremented when a runner claims it, so a crash still uses an attempt. */
83
+ attempts: integer("attempts").notNull().default(0),
84
+ /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
85
+ availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
86
+ /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
87
+ receipt: text("receipt"),
88
+ /** The last failure, with its stack. */
89
+ lastError: text("last_error"),
90
+ failedAt: timestamp("failed_at", { withTimezone: true }),
91
+ /** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
92
+ replaceKey: text("replace_key"),
93
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
94
+ },
95
+ (t) => [
96
+ index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
97
+ // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
98
+ uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
99
+ ],
100
+ );
101
+
102
+ /**
103
+ * The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
104
+ * Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
105
+ */
106
+ export const cronRunsTable = pgTable("logic_cron_runs", {
107
+ /** The cron job's id, `<cron id>@<minute>`. */
108
+ id: text("id").primaryKey(),
109
+ ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
110
+ });