logic-sdk 0.7.1 → 0.7.2
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 +7 -7
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
- package/dist/{jobs.js → core/jobs.js} +152 -39
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +203 -40
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -122
- package/dist/index.js +4 -492
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -53
- package/dist/pg-boss.js +2 -213
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -75
- package/dist/testing.js +1 -227
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +4 -3
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +152 -38
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +197 -40
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +15 -652
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -241
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /package/src/{schedule.ts → core/schedule.ts} +0 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// Jobs in
|
|
2
|
-
// has them (outbox). The table's statements are SQL, one set per database (postgres.ts, sqlite.ts), and run through
|
|
1
|
+
// Jobs in the registry's database, written in the mutation's transaction: run from there (databaseQueue), or kept
|
|
2
|
+
// until a queue has them (outbox). The table's statements are SQL, one set per database (postgres.ts, sqlite.ts), and run through
|
|
3
3
|
// the database adapter's `query`, so this file knows no ORM and no driver.
|
|
4
|
-
import {
|
|
4
|
+
import { defaultBackoff, storedReplaceKey } from "../core/jobs.ts";
|
|
5
|
+
import type { AdapterSetup, FailedJobs, FailedQuery, FailedRow, Job, JobOutcome, JobsAdapter, Runner, SqlDatabase, SweepResult } from "../core/types.ts";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
|
|
@@ -31,6 +32,16 @@ export interface JobsSql {
|
|
|
31
32
|
retry: string;
|
|
32
33
|
/** `(id, job, error)`: a failed row, new or over the one there. */
|
|
33
34
|
fail: string;
|
|
35
|
+
/**
|
|
36
|
+
* `(source, matches, at, id, limit)`, `''` for "any": failed rows newest first, after the cursor row (`at`, `id`), each
|
|
37
|
+
* matching the source and every field in `matches` (JSON `[{ path, jsonPath, value }]`). Returns `id`, `job` (JSON
|
|
38
|
+
* text), `last_error` and `failed_at` (as `at` takes it back).
|
|
39
|
+
*/
|
|
40
|
+
failed: string;
|
|
41
|
+
/** `(id)`: deletes a failed row. Returns `id`. */
|
|
42
|
+
forget: string;
|
|
43
|
+
/** `(id)`: deletes a failed row. Returns `job` (JSON text). */
|
|
44
|
+
take: string;
|
|
34
45
|
}
|
|
35
46
|
|
|
36
47
|
/** Seconds a job due now waits for the request that queued it, before a sweep may take it: how soon a crash after commit is noticed. */
|
|
@@ -55,15 +66,12 @@ export interface DatabaseQueueOptions {
|
|
|
55
66
|
* longer than that.
|
|
56
67
|
*/
|
|
57
68
|
lease?: number;
|
|
58
|
-
/** Seconds to wait after a failed try. Default `
|
|
69
|
+
/** Seconds to wait after a failed try. Default `defaultBackoff`, the curve Graphile Worker uses. */
|
|
59
70
|
backoff?: (attempt: number) => number;
|
|
60
71
|
}
|
|
61
72
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
lease?: number;
|
|
65
|
-
/** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
|
|
66
|
-
backoff?: (attempt: number) => number;
|
|
73
|
+
/** `lease` is how long a send owns its jobs, and `backoff` the wait after a failed send. */
|
|
74
|
+
export interface OutboxOptions extends DatabaseQueueOptions {
|
|
67
75
|
/**
|
|
68
76
|
* Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
|
|
69
77
|
* are its `attempts`.
|
|
@@ -77,23 +85,47 @@ export interface StoredJobs extends JobsAdapter {
|
|
|
77
85
|
sweep(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
|
|
78
86
|
/** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
|
|
79
87
|
retry(id: string): Promise<boolean>;
|
|
88
|
+
/** A page of failed rows, newest first. */
|
|
89
|
+
failed(query: FailedQuery): Promise<{ rows: FailedRow[]; cursor: string | null }>;
|
|
90
|
+
/** Delete a failed row. `false` when no failed row has that id. */
|
|
91
|
+
forget(id: string): Promise<boolean>;
|
|
80
92
|
}
|
|
81
93
|
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
94
|
+
/**
|
|
95
|
+
* The registry's database, taken at `createRegistry` (`sql: true`, so the core refuses one that doesn't run SQL): jobs
|
|
96
|
+
* are rows written in the mutation's transaction, so there's no other database they could go to. Laravel's `database`
|
|
97
|
+
* driver uses the app's connection too.
|
|
98
|
+
*/
|
|
99
|
+
function registryDatabase(name: string) {
|
|
100
|
+
let database: SqlDatabase | undefined;
|
|
101
|
+
return {
|
|
102
|
+
connect({ sql }: AdapterSetup) {
|
|
103
|
+
if (database && sql && database.db !== sql.db)
|
|
104
|
+
throw new Error(`[logic-sdk] ${name} is already connected to another registry's database: call it once per registry.`);
|
|
105
|
+
database = sql;
|
|
106
|
+
},
|
|
107
|
+
get(): SqlDatabase {
|
|
108
|
+
if (!database) throw new Error(`[logic-sdk] ${name} isn't connected: pass it to createRegistry.`);
|
|
109
|
+
return database;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
85
113
|
|
|
86
|
-
|
|
114
|
+
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
|
|
115
|
+
export function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapter): StoredJobs {
|
|
116
|
+
const name = via ? "outbox(queue)" : "databaseQueue()";
|
|
117
|
+
const database = registryDatabase(name);
|
|
87
118
|
const lease = options.lease ?? 300;
|
|
88
119
|
const maxAttempts = options.maxAttempts ?? 10;
|
|
89
120
|
const backoff = options.backoff ?? defaultBackoff;
|
|
90
121
|
/** Outside a mutation: on the database itself. */
|
|
91
|
-
const query = (text: string, params: unknown[]) => database.query(database.db, text, params);
|
|
122
|
+
const query = (text: string, params: unknown[]) => database.get().query(database.get().db, text, params);
|
|
92
123
|
const list = (ids: string[]) => JSON.stringify(ids);
|
|
93
124
|
|
|
94
125
|
// These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
|
|
95
126
|
// newer runner's work, and a handoff that finishes late can't delete the failure a consumer already recorded. By
|
|
96
127
|
// receipt, not attempt number: `retry(id)` starts those again at 1.
|
|
128
|
+
const failedRows = rowsOfFailed(sql, query);
|
|
97
129
|
const markFailed = (ids: string[], claim: Claim, error: unknown) => query(sql.markFailed, [describe(error), list(ids), claim.receipt]);
|
|
98
130
|
const backOff = (ids: string[], claim: Claim, error: unknown) => query(sql.backOff, [backoff(claim.attempt), describe(error), list(ids), claim.receipt]);
|
|
99
131
|
const remove = (ids: string[], claim: Claim) => query(sql.remove, [list(ids), claim.receipt]);
|
|
@@ -166,8 +198,8 @@ export function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxO
|
|
|
166
198
|
/** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
|
|
167
199
|
async function recordTicks(tx: unknown, ticks: Job[]): Promise<Set<unknown>> {
|
|
168
200
|
if (!ticks.length) return new Set();
|
|
169
|
-
const first = await database.query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
|
|
170
|
-
await database.query(tx, sql.pruneTicks, []);
|
|
201
|
+
const first = await database.get().query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
|
|
202
|
+
await database.get().query(tx, sql.pruneTicks, []);
|
|
171
203
|
return new Set(first.map((row) => row.id));
|
|
172
204
|
}
|
|
173
205
|
|
|
@@ -182,28 +214,24 @@ export function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxO
|
|
|
182
214
|
}
|
|
183
215
|
|
|
184
216
|
return {
|
|
217
|
+
name,
|
|
218
|
+
retries: true, // a failed try backs off as a row
|
|
185
219
|
holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
|
|
186
220
|
replaces: true, // a waiting row is replaced in place; under `via` too, since rows wait here until they're due
|
|
187
|
-
/**
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
throw new Error(
|
|
191
|
-
`[logic-sdk] ${via ? "outbox(database, queue)" : "databaseQueue(database)"} must use the same database as \`database\`: jobs are written in your mutation's transaction. ` +
|
|
192
|
-
"A queue in another database goes behind an outbox: outbox(database, queue).",
|
|
193
|
-
);
|
|
194
|
-
},
|
|
221
|
+
/** Takes the registry's database: it writes in the mutation's transaction. */
|
|
222
|
+
sql: true,
|
|
223
|
+
connect: (setup) => database.connect(setup),
|
|
195
224
|
/**
|
|
196
225
|
* Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
|
|
197
226
|
* request. Delayed: available from `runAt`, for a sweep. A cron's minute runs once: only ticks nobody recorded yet.
|
|
198
227
|
*/
|
|
199
228
|
async enqueue(tx, jobs) {
|
|
200
229
|
const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
.map((j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: replaceKeyOf(j) ?? null }))
|
|
230
|
+
const kept = jobs.filter((j) => j.kind !== "cron" || firstTicks.has(j.id));
|
|
231
|
+
const rows = (await Promise.all(kept.map(async (j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: (await storedReplaceKey(j)) ?? null }))))
|
|
204
232
|
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
205
233
|
.sort((a, b) => byText(a.key ?? "", b.key ?? ""));
|
|
206
|
-
if (rows.length) await database.query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
|
|
234
|
+
if (rows.length) await database.get().query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
|
|
207
235
|
},
|
|
208
236
|
/**
|
|
209
237
|
* After commit, in this request: each job is claimed just before it runs, so a slow or dead one doesn't spend the
|
|
@@ -248,13 +276,88 @@ export function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxO
|
|
|
248
276
|
async retry(id) {
|
|
249
277
|
return (await query(sql.retry, [id])).length > 0;
|
|
250
278
|
},
|
|
251
|
-
/** A job that failed for good in a queue consumer:
|
|
252
|
-
|
|
279
|
+
/** A job that failed for good in a queue consumer: kept as a failed row, so you can list it and `retry` it. */
|
|
280
|
+
fail: failedRows.fail,
|
|
281
|
+
failed: failedRows.failed,
|
|
282
|
+
forget: failedRows.forget,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Failed rows, newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page
|
|
288
|
+
* skips none. One row past the limit says there's another page.
|
|
289
|
+
*/
|
|
290
|
+
type Query = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
|
|
291
|
+
|
|
292
|
+
async function listFailed(sql: JobsSql, query: Query, { source, scope, limit, cursor }: FailedQuery) {
|
|
293
|
+
const [at, after] = cursor === undefined ? ["", ""] : cursorOf(cursor);
|
|
294
|
+
const matches = scope?.map(({ path, value }) => {
|
|
295
|
+
if (path.some((key) => !key || key.includes('"'))) throw new Error(`[logic-sdk] jobs.failed({ scope }) can't match the field ${JSON.stringify(path.join("."))}.`);
|
|
296
|
+
return { path, jsonPath: `$${path.map((key) => `."${key}"`).join("")}`, value };
|
|
297
|
+
});
|
|
298
|
+
const found = await query(sql.failed, [source ?? "", matches ? JSON.stringify(matches) : "", at, after, limit + 1]);
|
|
299
|
+
const page = found.slice(0, limit);
|
|
300
|
+
const last = page.at(-1);
|
|
301
|
+
return {
|
|
302
|
+
rows: page.map((row): FailedRow => ({
|
|
303
|
+
id: String(row.id),
|
|
304
|
+
job: JSON.parse(String(row.job)), // JSON text, on every driver
|
|
305
|
+
error: String(row.last_error ?? ""),
|
|
306
|
+
failedAt: new Date(/^\d+$/.test(String(row.failed_at)) ? Number(row.failed_at) : Date.parse(String(row.failed_at))).toISOString(), // SQLite: ms; Postgres: ISO text
|
|
307
|
+
})),
|
|
308
|
+
cursor: found.length > limit && last ? JSON.stringify([String(last.failed_at), String(last.id)]) : null,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
|
|
314
|
+
* `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
|
|
315
|
+
*/
|
|
316
|
+
export function failedStore(sql: JobsSql): FailedJobs {
|
|
317
|
+
const database = registryDatabase("failedJobs()");
|
|
318
|
+
const query = (text: string, params: unknown[]) => database.get().query(database.get().db, text, params);
|
|
319
|
+
return {
|
|
320
|
+
name: "failedJobs()",
|
|
321
|
+
sql: true,
|
|
322
|
+
connect: (setup) => database.connect(setup),
|
|
323
|
+
...rowsOfFailed(sql, query),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Failed rows in the jobs table: kept, listed, taken back for a retry, forgotten. A waiting or running row is never touched. */
|
|
328
|
+
function rowsOfFailed(sql: JobsSql, query: Query) {
|
|
329
|
+
return {
|
|
330
|
+
async fail(job: Job, error: unknown) {
|
|
253
331
|
await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
|
|
254
332
|
},
|
|
333
|
+
/**
|
|
334
|
+
* Newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page skips none.
|
|
335
|
+
* One row past the limit says there's another page.
|
|
336
|
+
*/
|
|
337
|
+
failed: (q: FailedQuery) => listFailed(sql, query, q),
|
|
338
|
+
async take(id: string): Promise<Job | undefined> {
|
|
339
|
+
const [row] = await query(sql.take, [id]);
|
|
340
|
+
return row ? JSON.parse(String(row.job)) : undefined;
|
|
341
|
+
},
|
|
342
|
+
async forget(id: string) {
|
|
343
|
+
return (await query(sql.forget, [id])).length > 0;
|
|
344
|
+
},
|
|
255
345
|
};
|
|
256
346
|
}
|
|
257
347
|
|
|
348
|
+
/** A `failed` page's cursor: the last row's `failed_at` (as the database gave it) and id. */
|
|
349
|
+
function cursorOf(cursor: string): [string, string] {
|
|
350
|
+
let parsed: unknown;
|
|
351
|
+
try {
|
|
352
|
+
parsed = JSON.parse(cursor);
|
|
353
|
+
} catch {
|
|
354
|
+
parsed = undefined;
|
|
355
|
+
}
|
|
356
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || !parsed.every((part) => typeof part === "string" && part))
|
|
357
|
+
throw new Error(`[logic-sdk] jobs.failed({ cursor }) takes the cursor of the page before (got ${JSON.stringify(cursor)}).`);
|
|
358
|
+
return parsed as [string, string];
|
|
359
|
+
}
|
|
360
|
+
|
|
258
361
|
/** Not `localeCompare`: processes with another locale would lock in another order. */
|
|
259
362
|
const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
260
363
|
const describe = (e: unknown) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
|
package/src/ai.ts
CHANGED
|
@@ -1,62 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { isDomainError, type Caller, type FnIn, type FnOut, type ForFunctions, type PublishableFn, type ScopeOfFn } from "./index.ts";
|
|
3
|
-
|
|
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
|
-
}>;
|
|
14
|
-
|
|
15
|
-
export interface AIToolOptions {
|
|
16
|
-
/** Overrides `meta.ai.description` for this tool. */
|
|
17
|
-
description?: string;
|
|
18
|
-
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
19
|
-
onError?: (error: unknown) => void;
|
|
20
|
-
}
|
|
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;
|
|
24
|
-
|
|
25
|
-
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
26
|
-
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
27
|
-
|
|
28
|
-
/**
|
|
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.
|
|
32
|
-
*
|
|
33
|
-
* ```ts
|
|
34
|
-
* const caller = registry.as(await scopeFrom(request));
|
|
35
|
-
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
36
|
-
* ```
|
|
37
|
-
*
|
|
38
|
-
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
39
|
-
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
40
|
-
*/
|
|
41
|
-
export function toAITool<F extends PublishableFn>(
|
|
42
|
-
caller: Caller<ScopeOfFn<F>>,
|
|
43
|
-
fn: F,
|
|
44
|
-
options: AIToolOptions = {},
|
|
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`).");
|
|
47
|
-
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
48
|
-
return tool({
|
|
49
|
-
description: options.description ?? aiMeta(fn)?.description,
|
|
50
|
-
inputSchema: fn.input ?? noInput,
|
|
51
|
-
outputSchema: fn.output,
|
|
52
|
-
async execute(input, { abortSignal }) {
|
|
53
|
-
try {
|
|
54
|
-
return await caller.run(fn, input, { signal: abortSignal });
|
|
55
|
-
} catch (e) {
|
|
56
|
-
if (isDomainError(e)) throw e;
|
|
57
|
-
onError(e);
|
|
58
|
-
throw new Error("internal_error");
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
|
-
}) as Tool<FnIn<F>, FnOut<F>>;
|
|
62
|
-
}
|
|
1
|
+
export { toAITool, type AIMeta, type AIToolOptions } from "./integrations/ai.ts";
|
package/src/cloudflare.ts
CHANGED
|
@@ -1,107 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
-
}
|
|
1
|
+
export { cloudflareQueue, type QueueBinding } from "./adapters/cloudflare-queue.ts";
|
|
2
|
+
export { handleQueue, handleScheduled, type QueueBatch } from "./hosts/cloudflare.ts";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { InProcess, JobsAdapter } from "./types.ts";
|
|
2
|
+
import { RUNS_NOW } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
const IN_PROCESS: InProcess = {
|
|
5
|
+
[RUNS_NOW]: true,
|
|
6
|
+
name: "inProcess()",
|
|
7
|
+
async deliver(jobs, { run }) {
|
|
8
|
+
// one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
|
|
9
|
+
for (const job of jobs) await run({ ...job, attempts: 1 });
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
|
|
14
|
+
* hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
|
|
15
|
+
*/
|
|
16
|
+
export const inProcess = (): InProcess => IN_PROCESS;
|
|
17
|
+
/** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
|
|
18
|
+
export const runsNow = (adapter: JobsAdapter) => RUNS_NOW in adapter;
|