logic-sdk 0.4.0 → 0.5.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.
- package/README.md +39 -13
- package/dist/ai.d.ts +16 -26
- package/dist/ai.js +8 -21
- package/dist/cloudflare.d.ts +55 -0
- package/dist/cloudflare.js +85 -0
- package/dist/drizzle/pg.d.ts +237 -0
- package/dist/drizzle/pg.js +67 -0
- package/dist/drizzle/sqlite.d.ts +242 -0
- package/dist/drizzle/sqlite.js +194 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +45 -0
- package/dist/fetch.d.ts +15 -18
- package/dist/fetch.js +18 -55
- package/dist/index.d.ts +75 -379
- package/dist/index.js +228 -181
- package/dist/jobs.d.ts +44 -0
- package/dist/jobs.js +252 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +76 -0
- package/dist/orpc.d.ts +10 -17
- package/dist/orpc.js +19 -28
- package/dist/pg-boss.d.ts +55 -0
- package/dist/pg-boss.js +211 -0
- package/dist/postgres.d.ts +28 -0
- package/dist/postgres.js +82 -0
- package/dist/schedule.d.ts +23 -0
- package/dist/schedule.js +109 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.js +65 -0
- package/dist/stored-jobs.d.ts +64 -0
- package/dist/stored-jobs.js +188 -0
- package/dist/testing.d.ts +50 -14
- package/dist/testing.js +198 -46
- package/dist/types.d.ts +653 -0
- package/dist/types.js +6 -0
- package/package.json +45 -7
- package/skills/logic-sdk/SKILL.md +114 -0
- package/src/ai.ts +23 -46
- package/src/cloudflare.ts +107 -0
- package/src/drizzle/pg.ts +111 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +384 -558
- package/src/jobs.ts +296 -0
- package/src/node.ts +99 -0
- package/src/orpc.ts +24 -42
- package/src/pg-boss.ts +242 -0
- package/src/postgres.ts +90 -0
- package/src/schedule.ts +129 -0
- package/src/sqlite.ts +74 -0
- package/src/stored-jobs.ts +260 -0
- package/src/testing.ts +252 -55
- package/src/types.ts +683 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- 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
|
|
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
|
|
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,
|
|
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
|
-
- **
|
|
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.**
|
|
82
|
-
- **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API
|
|
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/
|
|
94
|
-
| `logic-sdk/
|
|
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
|
|
|
@@ -114,7 +140,7 @@ Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships
|
|
|
114
140
|
|
|
115
141
|
## Docs
|
|
116
142
|
|
|
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). [`
|
|
143
|
+
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
144
|
|
|
119
145
|
## Repository
|
|
120
146
|
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,26 +1,25 @@
|
|
|
1
1
|
import { type Tool } from "ai";
|
|
2
|
-
import { type Caller, type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
}
|
|
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
|
|
23
|
-
*
|
|
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
|
|
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
|
|
7
|
-
*
|
|
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:
|
|
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,237 @@
|
|
|
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
|
+
* `logic-sdk check` catches the rest.
|
|
15
|
+
*/
|
|
16
|
+
export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
|
|
17
|
+
/** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
|
|
18
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView">;
|
|
19
|
+
/**
|
|
20
|
+
* Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
|
|
21
|
+
* the transaction.
|
|
22
|
+
*/
|
|
23
|
+
export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
|
|
24
|
+
export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
|
|
25
|
+
/**
|
|
26
|
+
* Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
|
|
27
|
+
* PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
|
|
28
|
+
* The types reject SQLite and libsql databases here.
|
|
29
|
+
*/
|
|
30
|
+
export declare function drizzleAdapter<Db extends Transactional>(db: Db, options?: DrizzleAdapterOptions): SqlDatabase<Db, Transaction<Db>>;
|
|
31
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
32
|
+
export declare function sqlState(error: unknown): string | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
|
|
35
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
|
|
36
|
+
* done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
37
|
+
*/
|
|
38
|
+
export declare const jobsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
39
|
+
name: "logic_jobs";
|
|
40
|
+
schema: undefined;
|
|
41
|
+
columns: {
|
|
42
|
+
id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
43
|
+
name: string;
|
|
44
|
+
tableName: "logic_jobs";
|
|
45
|
+
dataType: "string";
|
|
46
|
+
data: string;
|
|
47
|
+
driverParam: string;
|
|
48
|
+
notNull: true;
|
|
49
|
+
hasDefault: false;
|
|
50
|
+
isPrimaryKey: false;
|
|
51
|
+
isAutoincrement: false;
|
|
52
|
+
hasRuntimeDefault: false;
|
|
53
|
+
enumValues: undefined;
|
|
54
|
+
identity: undefined;
|
|
55
|
+
generated: undefined;
|
|
56
|
+
}>;
|
|
57
|
+
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>>, {
|
|
58
|
+
name: string;
|
|
59
|
+
tableName: "logic_jobs";
|
|
60
|
+
dataType: "object json";
|
|
61
|
+
data: Job;
|
|
62
|
+
driverParam: unknown;
|
|
63
|
+
notNull: true;
|
|
64
|
+
hasDefault: false;
|
|
65
|
+
isPrimaryKey: false;
|
|
66
|
+
isAutoincrement: false;
|
|
67
|
+
hasRuntimeDefault: false;
|
|
68
|
+
enumValues: undefined;
|
|
69
|
+
identity: undefined;
|
|
70
|
+
generated: undefined;
|
|
71
|
+
}>;
|
|
72
|
+
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">>>, {
|
|
73
|
+
name: string;
|
|
74
|
+
tableName: "logic_jobs";
|
|
75
|
+
dataType: "string";
|
|
76
|
+
data: "failed" | "pending";
|
|
77
|
+
driverParam: string;
|
|
78
|
+
notNull: true;
|
|
79
|
+
hasDefault: true;
|
|
80
|
+
isPrimaryKey: false;
|
|
81
|
+
isAutoincrement: false;
|
|
82
|
+
hasRuntimeDefault: false;
|
|
83
|
+
enumValues: undefined;
|
|
84
|
+
identity: undefined;
|
|
85
|
+
generated: undefined;
|
|
86
|
+
}>;
|
|
87
|
+
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>>, {
|
|
88
|
+
name: string;
|
|
89
|
+
tableName: "logic_jobs";
|
|
90
|
+
dataType: "number int32";
|
|
91
|
+
data: number;
|
|
92
|
+
driverParam: string | number;
|
|
93
|
+
notNull: true;
|
|
94
|
+
hasDefault: true;
|
|
95
|
+
isPrimaryKey: false;
|
|
96
|
+
isAutoincrement: false;
|
|
97
|
+
hasRuntimeDefault: false;
|
|
98
|
+
enumValues: undefined;
|
|
99
|
+
identity: undefined;
|
|
100
|
+
generated: undefined;
|
|
101
|
+
}>;
|
|
102
|
+
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>>, {
|
|
103
|
+
name: string;
|
|
104
|
+
tableName: "logic_jobs";
|
|
105
|
+
dataType: "object date";
|
|
106
|
+
data: Date;
|
|
107
|
+
driverParam: string;
|
|
108
|
+
notNull: true;
|
|
109
|
+
hasDefault: true;
|
|
110
|
+
isPrimaryKey: false;
|
|
111
|
+
isAutoincrement: false;
|
|
112
|
+
hasRuntimeDefault: false;
|
|
113
|
+
enumValues: undefined;
|
|
114
|
+
identity: undefined;
|
|
115
|
+
generated: undefined;
|
|
116
|
+
}>;
|
|
117
|
+
receipt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
118
|
+
name: string;
|
|
119
|
+
tableName: "logic_jobs";
|
|
120
|
+
dataType: "string";
|
|
121
|
+
data: string;
|
|
122
|
+
driverParam: string;
|
|
123
|
+
notNull: false;
|
|
124
|
+
hasDefault: false;
|
|
125
|
+
isPrimaryKey: false;
|
|
126
|
+
isAutoincrement: false;
|
|
127
|
+
hasRuntimeDefault: false;
|
|
128
|
+
enumValues: undefined;
|
|
129
|
+
identity: undefined;
|
|
130
|
+
generated: undefined;
|
|
131
|
+
}>;
|
|
132
|
+
lastError: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
133
|
+
name: string;
|
|
134
|
+
tableName: "logic_jobs";
|
|
135
|
+
dataType: "string";
|
|
136
|
+
data: string;
|
|
137
|
+
driverParam: string;
|
|
138
|
+
notNull: false;
|
|
139
|
+
hasDefault: false;
|
|
140
|
+
isPrimaryKey: false;
|
|
141
|
+
isAutoincrement: false;
|
|
142
|
+
hasRuntimeDefault: false;
|
|
143
|
+
enumValues: undefined;
|
|
144
|
+
identity: undefined;
|
|
145
|
+
generated: undefined;
|
|
146
|
+
}>;
|
|
147
|
+
failedAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTimestampBuilder, {
|
|
148
|
+
name: string;
|
|
149
|
+
tableName: "logic_jobs";
|
|
150
|
+
dataType: "object date";
|
|
151
|
+
data: Date;
|
|
152
|
+
driverParam: string;
|
|
153
|
+
notNull: false;
|
|
154
|
+
hasDefault: false;
|
|
155
|
+
isPrimaryKey: false;
|
|
156
|
+
isAutoincrement: false;
|
|
157
|
+
hasRuntimeDefault: false;
|
|
158
|
+
enumValues: undefined;
|
|
159
|
+
identity: undefined;
|
|
160
|
+
generated: undefined;
|
|
161
|
+
}>;
|
|
162
|
+
replaceKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
163
|
+
name: string;
|
|
164
|
+
tableName: "logic_jobs";
|
|
165
|
+
dataType: "string";
|
|
166
|
+
data: string;
|
|
167
|
+
driverParam: string;
|
|
168
|
+
notNull: false;
|
|
169
|
+
hasDefault: false;
|
|
170
|
+
isPrimaryKey: false;
|
|
171
|
+
isAutoincrement: false;
|
|
172
|
+
hasRuntimeDefault: false;
|
|
173
|
+
enumValues: undefined;
|
|
174
|
+
identity: undefined;
|
|
175
|
+
generated: undefined;
|
|
176
|
+
}>;
|
|
177
|
+
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>>, {
|
|
178
|
+
name: string;
|
|
179
|
+
tableName: "logic_jobs";
|
|
180
|
+
dataType: "object date";
|
|
181
|
+
data: Date;
|
|
182
|
+
driverParam: string;
|
|
183
|
+
notNull: true;
|
|
184
|
+
hasDefault: true;
|
|
185
|
+
isPrimaryKey: false;
|
|
186
|
+
isAutoincrement: false;
|
|
187
|
+
hasRuntimeDefault: false;
|
|
188
|
+
enumValues: undefined;
|
|
189
|
+
identity: undefined;
|
|
190
|
+
generated: undefined;
|
|
191
|
+
}>;
|
|
192
|
+
};
|
|
193
|
+
dialect: 'pg';
|
|
194
|
+
isAlias: false;
|
|
195
|
+
}>;
|
|
196
|
+
/**
|
|
197
|
+
* The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
|
|
198
|
+
* Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
|
|
199
|
+
*/
|
|
200
|
+
export declare const cronRunsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
201
|
+
name: "logic_cron_runs";
|
|
202
|
+
schema: undefined;
|
|
203
|
+
columns: {
|
|
204
|
+
id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_cron_runs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
205
|
+
name: string;
|
|
206
|
+
tableName: "logic_cron_runs";
|
|
207
|
+
dataType: "string";
|
|
208
|
+
data: string;
|
|
209
|
+
driverParam: string;
|
|
210
|
+
notNull: true;
|
|
211
|
+
hasDefault: false;
|
|
212
|
+
isPrimaryKey: false;
|
|
213
|
+
isAutoincrement: false;
|
|
214
|
+
hasRuntimeDefault: false;
|
|
215
|
+
enumValues: undefined;
|
|
216
|
+
identity: undefined;
|
|
217
|
+
generated: undefined;
|
|
218
|
+
}>;
|
|
219
|
+
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>>, {
|
|
220
|
+
name: string;
|
|
221
|
+
tableName: "logic_cron_runs";
|
|
222
|
+
dataType: "object date";
|
|
223
|
+
data: Date;
|
|
224
|
+
driverParam: string;
|
|
225
|
+
notNull: true;
|
|
226
|
+
hasDefault: true;
|
|
227
|
+
isPrimaryKey: false;
|
|
228
|
+
isAutoincrement: false;
|
|
229
|
+
hasRuntimeDefault: false;
|
|
230
|
+
enumValues: undefined;
|
|
231
|
+
identity: undefined;
|
|
232
|
+
generated: undefined;
|
|
233
|
+
}>;
|
|
234
|
+
};
|
|
235
|
+
dialect: 'pg';
|
|
236
|
+
isAlias: false;
|
|
237
|
+
}>;
|