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
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
3
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
4
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n claimed_at timestamptz,\n last_error text,\n failed_at timestamptz,\n replace_key text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
|
|
5
|
+
/**
|
|
6
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
7
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
8
|
+
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
9
|
+
* its row being deleted runs it again.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
13
|
+
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
|
|
17
|
+
/**
|
|
18
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
19
|
+
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
20
|
+
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
21
|
+
* so a job can run twice, even at once.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare const outbox: (queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
28
|
+
/**
|
|
29
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
30
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
31
|
+
*/
|
|
32
|
+
export declare const failedJobs: () => FailedJobs;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// The jobs table on Postgres, in SQL. With Drizzle, import from `logic-sdk/drizzle/pg` instead: the same two
|
|
2
|
+
// functions, plus the table for your schema.
|
|
3
|
+
import { failedStore, storedJobs } from "./stored-jobs.js";
|
|
4
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
+
export const jobsSchema = `
|
|
6
|
+
CREATE TABLE logic_jobs (
|
|
7
|
+
id text PRIMARY KEY,
|
|
8
|
+
job jsonb NOT NULL,
|
|
9
|
+
status text NOT NULL DEFAULT 'pending',
|
|
10
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
11
|
+
available_at timestamptz NOT NULL DEFAULT now(),
|
|
12
|
+
receipt text,
|
|
13
|
+
claimed_at timestamptz,
|
|
14
|
+
last_error text,
|
|
15
|
+
failed_at timestamptz,
|
|
16
|
+
replace_key text,
|
|
17
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
18
|
+
);
|
|
19
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
20
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
21
|
+
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
22
|
+
CREATE TABLE logic_cron_runs (
|
|
23
|
+
id text PRIMARY KEY,
|
|
24
|
+
ran_at timestamptz NOT NULL DEFAULT now()
|
|
25
|
+
);
|
|
26
|
+
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
27
|
+
`;
|
|
28
|
+
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
29
|
+
const ids = (n) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
|
|
30
|
+
const mine = (n) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
31
|
+
const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
|
|
32
|
+
const statements = {
|
|
33
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
|
|
34
|
+
insert: `
|
|
35
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
36
|
+
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
|
|
37
|
+
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
38
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
39
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
|
|
40
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
41
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
42
|
+
claimNew: `
|
|
43
|
+
UPDATE logic_jobs SET attempts = 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
44
|
+
WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
45
|
+
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
46
|
+
claimDue: `
|
|
47
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
48
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
49
|
+
RETURNING job::text AS job, attempts`,
|
|
50
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
51
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2, claimed_at = NULL WHERE ${mine(3)}`,
|
|
52
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now(), claimed_at = NULL WHERE ${mine(2)}`,
|
|
53
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
54
|
+
// its receipt goes, so the runner that lost it can't finish the new run. Its key goes: it has run, so it's no longer
|
|
55
|
+
// a call a newer one replaces (and one may be waiting with it)
|
|
56
|
+
retry: `
|
|
57
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
58
|
+
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
59
|
+
fail: `
|
|
60
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
61
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
62
|
+
// field by field, as SQLite matches, so both databases agree; `failed_at` back as text to the microsecond, for the cursor
|
|
63
|
+
failed: `
|
|
64
|
+
WITH p AS (SELECT NULLIF($1, '') AS source, NULLIF($2, '') AS want, NULLIF($3, '')::timestamptz AS at, NULLIF($4, '') AS after_id)
|
|
65
|
+
SELECT j.id, j.job::text AS job, j.last_error, to_char(j.failed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS failed_at
|
|
66
|
+
FROM logic_jobs j, p
|
|
67
|
+
WHERE j.status = 'failed'
|
|
68
|
+
AND (p.source IS NULL OR coalesce(j.job ->> 'listener', j.job ->> 'cron', j.job ->> 'fn') = p.source)
|
|
69
|
+
AND (p.want IS NULL OR NOT EXISTS (
|
|
70
|
+
SELECT 1 FROM jsonb_array_elements(p.want::jsonb) AS w(m)
|
|
71
|
+
WHERE (coalesce(j.job -> 'scope', j.job #> '{envelope,scope}') #> ARRAY(SELECT jsonb_array_elements_text(w.m -> 'path'))) IS DISTINCT FROM (w.m -> 'value')))
|
|
72
|
+
AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
|
|
73
|
+
ORDER BY j.failed_at DESC, j.id DESC
|
|
74
|
+
LIMIT $5::int`,
|
|
75
|
+
forget: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
76
|
+
take: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING job::text AS job`,
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
80
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
81
|
+
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
82
|
+
* its row being deleted runs it again.
|
|
83
|
+
*
|
|
84
|
+
* ```ts
|
|
85
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
86
|
+
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export const databaseQueue = (options = {}) => storedJobs(statements, options);
|
|
90
|
+
/**
|
|
91
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
92
|
+
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
93
|
+
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
94
|
+
* so a job can run twice, even at once.
|
|
95
|
+
*
|
|
96
|
+
* ```ts
|
|
97
|
+
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
export const outbox = (queue, options = {}) => storedJobs(statements, options, queue);
|
|
101
|
+
/**
|
|
102
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
103
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
104
|
+
*/
|
|
105
|
+
export const failedJobs = () => failedStore(statements);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
3
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
4
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n claimed_at integer,\n last_error text,\n failed_at integer,\n replace_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
|
|
5
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
6
|
+
export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
|
|
7
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
8
|
+
export declare const outbox: (queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
9
|
+
/**
|
|
10
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
11
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
12
|
+
*/
|
|
13
|
+
export declare const failedJobs: () => FailedJobs;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// The jobs table on SQLite (3.42 or later, for `unixepoch('subsec')`), in SQL. With Drizzle, import from
|
|
2
|
+
// `logic-sdk/drizzle/sqlite` instead: the same two functions, plus the table for your schema. Times are whole milliseconds since 1970, on SQLite's clock.
|
|
3
|
+
// Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
|
|
4
|
+
import { failedStore, storedJobs } from "./stored-jobs.js";
|
|
5
|
+
const now = `cast(unixepoch('subsec') * 1000 as integer)`;
|
|
6
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
7
|
+
export const jobsSchema = `
|
|
8
|
+
CREATE TABLE logic_jobs (
|
|
9
|
+
id text PRIMARY KEY NOT NULL,
|
|
10
|
+
job text NOT NULL,
|
|
11
|
+
status text NOT NULL DEFAULT 'pending',
|
|
12
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
13
|
+
available_at integer NOT NULL DEFAULT (${now}),
|
|
14
|
+
receipt text,
|
|
15
|
+
claimed_at integer,
|
|
16
|
+
last_error text,
|
|
17
|
+
failed_at integer,
|
|
18
|
+
replace_key text,
|
|
19
|
+
created_at integer NOT NULL DEFAULT (${now})
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
22
|
+
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
23
|
+
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
24
|
+
CREATE TABLE logic_cron_runs (
|
|
25
|
+
id text PRIMARY KEY NOT NULL,
|
|
26
|
+
ran_at integer NOT NULL DEFAULT (${now})
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
29
|
+
`;
|
|
30
|
+
const ids = "(SELECT value FROM json_each(?))";
|
|
31
|
+
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
32
|
+
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
33
|
+
const statements = {
|
|
34
|
+
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
|
|
35
|
+
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
|
|
36
|
+
insert: `
|
|
37
|
+
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
38
|
+
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
|
|
39
|
+
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
40
|
+
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
41
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
42
|
+
RETURNING id`,
|
|
43
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
44
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
45
|
+
claimNew: `
|
|
46
|
+
UPDATE logic_jobs SET attempts = 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
47
|
+
WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
48
|
+
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
49
|
+
claimDue: `
|
|
50
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, claimed_at = ${now}, available_at = ${inSeconds}
|
|
51
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
|
|
52
|
+
RETURNING job, attempts`,
|
|
53
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
54
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ?, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
55
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now}, claimed_at = NULL WHERE ${mine} RETURNING id`,
|
|
56
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
57
|
+
retry: `
|
|
58
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
59
|
+
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
60
|
+
fail: `
|
|
61
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|
|
62
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
|
|
63
|
+
RETURNING id`,
|
|
64
|
+
// each field by its type and value: a missing one isn't null, and true isn't 1
|
|
65
|
+
failed: `
|
|
66
|
+
WITH p(source, want, at, after_id) AS (SELECT NULLIF(?, ''), NULLIF(?, ''), CAST(NULLIF(?, '') AS INTEGER), NULLIF(?, ''))
|
|
67
|
+
SELECT j.id, j.job, j.last_error, j.failed_at FROM logic_jobs j, p
|
|
68
|
+
WHERE j.status = 'failed'
|
|
69
|
+
AND (p.source IS NULL OR coalesce(j.job ->> '$.listener', j.job ->> '$.cron', j.job ->> '$.fn') = p.source)
|
|
70
|
+
AND (p.want IS NULL OR NOT EXISTS (
|
|
71
|
+
SELECT 1 FROM json_each(p.want) AS w
|
|
72
|
+
WHERE json_type(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_type(w.value, '$.value')
|
|
73
|
+
OR json_extract(coalesce(j.job -> '$.scope', j.job -> '$.envelope.scope'), w.value ->> '$.jsonPath') IS NOT json_extract(w.value, '$.value')))
|
|
74
|
+
AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
|
|
75
|
+
ORDER BY j.failed_at DESC, j.id DESC
|
|
76
|
+
LIMIT ?`,
|
|
77
|
+
forget: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
78
|
+
take: `DELETE FROM logic_jobs WHERE id = ? AND status = 'failed' RETURNING job`,
|
|
79
|
+
};
|
|
80
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
81
|
+
export const databaseQueue = (options = {}) => storedJobs(statements, options);
|
|
82
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
83
|
+
export const outbox = (queue, options = {}) => storedJobs(statements, options, queue);
|
|
84
|
+
/**
|
|
85
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
86
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
87
|
+
*/
|
|
88
|
+
export const failedJobs = () => failedStore(statements);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { FailedJobs, FailedQuery, FailedRow, JobsAdapter, Runner, SweepResult } from "../core/types.ts";
|
|
2
2
|
/**
|
|
3
3
|
* The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
|
|
4
4
|
* lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
|
|
@@ -27,6 +27,16 @@ export interface JobsSql {
|
|
|
27
27
|
retry: string;
|
|
28
28
|
/** `(id, job, error)`: a failed row, new or over the one there. */
|
|
29
29
|
fail: string;
|
|
30
|
+
/**
|
|
31
|
+
* `(source, matches, at, id, limit)`, `''` for "any": failed rows newest first, after the cursor row (`at`, `id`), each
|
|
32
|
+
* matching the source and every field in `matches` (JSON `[{ path, jsonPath, value }]`). Returns `id`, `job` (JSON
|
|
33
|
+
* text), `last_error` and `failed_at` (as `at` takes it back).
|
|
34
|
+
*/
|
|
35
|
+
failed: string;
|
|
36
|
+
/** `(id)`: deletes a failed row. Returns `id`. */
|
|
37
|
+
forget: string;
|
|
38
|
+
/** `(id)`: deletes a failed row. Returns `job` (JSON text). */
|
|
39
|
+
take: string;
|
|
30
40
|
}
|
|
31
41
|
export interface DatabaseQueueOptions {
|
|
32
42
|
/**
|
|
@@ -35,14 +45,11 @@ export interface DatabaseQueueOptions {
|
|
|
35
45
|
* longer than that.
|
|
36
46
|
*/
|
|
37
47
|
lease?: number;
|
|
38
|
-
/** Seconds to wait after a failed try. Default `
|
|
48
|
+
/** Seconds to wait after a failed try. Default `defaultBackoff`, the curve Graphile Worker uses. */
|
|
39
49
|
backoff?: (attempt: number) => number;
|
|
40
50
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
lease?: number;
|
|
44
|
-
/** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
|
|
45
|
-
backoff?: (attempt: number) => number;
|
|
51
|
+
/** `lease` is how long a send owns its jobs, and `backoff` the wait after a failed send. */
|
|
52
|
+
export interface OutboxOptions extends DatabaseQueueOptions {
|
|
46
53
|
/**
|
|
47
54
|
* Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
|
|
48
55
|
* are its `attempts`.
|
|
@@ -57,8 +64,18 @@ export interface StoredJobs extends JobsAdapter {
|
|
|
57
64
|
}): Promise<SweepResult>;
|
|
58
65
|
/** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
|
|
59
66
|
retry(id: string): Promise<boolean>;
|
|
67
|
+
/** A page of failed rows, newest first. */
|
|
68
|
+
failed(query: FailedQuery): Promise<{
|
|
69
|
+
rows: FailedRow[];
|
|
70
|
+
cursor: string | null;
|
|
71
|
+
}>;
|
|
72
|
+
/** Delete a failed row. `false` when no failed row has that id. */
|
|
73
|
+
forget(id: string): Promise<boolean>;
|
|
60
74
|
}
|
|
61
75
|
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
76
|
+
export declare function storedJobs(sql: JobsSql, options: OutboxOptions, via?: JobsAdapter): StoredJobs;
|
|
77
|
+
/**
|
|
78
|
+
* Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
|
|
79
|
+
* `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
|
|
80
|
+
*/
|
|
81
|
+
export declare function failedStore(sql: JobsSql): FailedJobs;
|
|
@@ -1,7 +1,7 @@
|
|
|
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.js";
|
|
5
5
|
/** 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. */
|
|
6
6
|
const PICKUP = 30;
|
|
7
7
|
/**
|
|
@@ -9,19 +9,40 @@ const PICKUP = 30;
|
|
|
9
9
|
* expiry. Past it, a job that hangs is taken over like a crashed one. A longer job needs a `lease` that long.
|
|
10
10
|
*/
|
|
11
11
|
const MAX_EXTEND = 15 * 60;
|
|
12
|
+
/**
|
|
13
|
+
* The registry's database, taken at `createRegistry` (`sql: true`, so the core refuses one that doesn't run SQL): jobs
|
|
14
|
+
* are rows written in the mutation's transaction, so there's no other database they could go to. Laravel's `database`
|
|
15
|
+
* driver uses the app's connection too.
|
|
16
|
+
*/
|
|
17
|
+
function registryDatabase(name) {
|
|
18
|
+
let database;
|
|
19
|
+
return {
|
|
20
|
+
connect({ sql }) {
|
|
21
|
+
if (database && sql && database.db !== sql.db)
|
|
22
|
+
throw new Error(`[logic-sdk] ${name} is already connected to another registry's database: call it once per registry.`);
|
|
23
|
+
database = sql;
|
|
24
|
+
},
|
|
25
|
+
get() {
|
|
26
|
+
if (!database)
|
|
27
|
+
throw new Error(`[logic-sdk] ${name} isn't connected: pass it to createRegistry.`);
|
|
28
|
+
return database;
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
12
32
|
/** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
33
|
+
export function storedJobs(sql, options, via) {
|
|
34
|
+
const name = via ? "outbox(queue)" : "databaseQueue()";
|
|
35
|
+
const database = registryDatabase(name);
|
|
16
36
|
const lease = options.lease ?? 300;
|
|
17
37
|
const maxAttempts = options.maxAttempts ?? 10;
|
|
18
38
|
const backoff = options.backoff ?? defaultBackoff;
|
|
19
39
|
/** Outside a mutation: on the database itself. */
|
|
20
|
-
const query = (text, params) => database.query(database.db, text, params);
|
|
40
|
+
const query = (text, params) => database.get().query(database.get().db, text, params);
|
|
21
41
|
const list = (ids) => JSON.stringify(ids);
|
|
22
42
|
// These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
|
|
23
43
|
// newer runner's work, and a handoff that finishes late can't delete the failure a consumer already recorded. By
|
|
24
44
|
// receipt, not attempt number: `retry(id)` starts those again at 1.
|
|
45
|
+
const failedRows = rowsOfFailed(sql, query);
|
|
25
46
|
const markFailed = (ids, claim, error) => query(sql.markFailed, [describe(error), list(ids), claim.receipt]);
|
|
26
47
|
const backOff = (ids, claim, error) => query(sql.backOff, [backoff(claim.attempt), describe(error), list(ids), claim.receipt]);
|
|
27
48
|
const remove = (ids, claim) => query(sql.remove, [list(ids), claim.receipt]);
|
|
@@ -93,8 +114,8 @@ export function storedJobs(sql, database, options, via) {
|
|
|
93
114
|
async function recordTicks(tx, ticks) {
|
|
94
115
|
if (!ticks.length)
|
|
95
116
|
return new Set();
|
|
96
|
-
const first = await database.query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
|
|
97
|
-
await database.query(tx, sql.pruneTicks, []);
|
|
117
|
+
const first = await database.get().query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
|
|
118
|
+
await database.get().query(tx, sql.pruneTicks, []);
|
|
98
119
|
return new Set(first.map((row) => row.id));
|
|
99
120
|
}
|
|
100
121
|
const settle = (job, claim, runner) => (via ? handOff(via, [job], claim, runner) : run(job, claim, runner));
|
|
@@ -106,27 +127,25 @@ export function storedJobs(sql, database, options, via) {
|
|
|
106
127
|
return { claim, won: jobs.filter((j) => ids.has(j.id)) }; // in emit order: RETURNING has none
|
|
107
128
|
}
|
|
108
129
|
return {
|
|
130
|
+
name,
|
|
131
|
+
retries: true, // a failed try backs off as a row
|
|
109
132
|
holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
|
|
110
133
|
replaces: true, // a waiting row is replaced in place; under `via` too, since rows wait here until they're due
|
|
111
|
-
/**
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
throw new Error(`[logic-sdk] ${via ? "outbox(database, queue)" : "databaseQueue(database)"} must use the same database as \`database\`: jobs are written in your mutation's transaction. ` +
|
|
115
|
-
"A queue in another database goes behind an outbox: outbox(database, queue).");
|
|
116
|
-
},
|
|
134
|
+
/** Takes the registry's database: it writes in the mutation's transaction. */
|
|
135
|
+
sql: true,
|
|
136
|
+
connect: (setup) => database.connect(setup),
|
|
117
137
|
/**
|
|
118
138
|
* Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
|
|
119
139
|
* request. Delayed: available from `runAt`, for a sweep. A cron's minute runs once: only ticks nobody recorded yet.
|
|
120
140
|
*/
|
|
121
141
|
async enqueue(tx, jobs) {
|
|
122
142
|
const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
.map((j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: replaceKeyOf(j) ?? null }))
|
|
143
|
+
const kept = jobs.filter((j) => j.kind !== "cron" || firstTicks.has(j.id));
|
|
144
|
+
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 }))))
|
|
126
145
|
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
127
146
|
.sort((a, b) => byText(a.key ?? "", b.key ?? ""));
|
|
128
147
|
if (rows.length)
|
|
129
|
-
await database.query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
|
|
148
|
+
await database.get().query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
|
|
130
149
|
},
|
|
131
150
|
/**
|
|
132
151
|
* After commit, in this request: each job is claimed just before it runs, so a slow or dead one doesn't spend the
|
|
@@ -177,12 +196,79 @@ export function storedJobs(sql, database, options, via) {
|
|
|
177
196
|
async retry(id) {
|
|
178
197
|
return (await query(sql.retry, [id])).length > 0;
|
|
179
198
|
},
|
|
180
|
-
/** A job that failed for good in a queue consumer:
|
|
199
|
+
/** A job that failed for good in a queue consumer: kept as a failed row, so you can list it and `retry` it. */
|
|
200
|
+
fail: failedRows.fail,
|
|
201
|
+
failed: failedRows.failed,
|
|
202
|
+
forget: failedRows.forget,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
async function listFailed(sql, query, { source, scope, limit, cursor }) {
|
|
206
|
+
const [at, after] = cursor === undefined ? ["", ""] : cursorOf(cursor);
|
|
207
|
+
const matches = scope?.map(({ path, value }) => {
|
|
208
|
+
if (path.some((key) => !key || key.includes('"')))
|
|
209
|
+
throw new Error(`[logic-sdk] jobs.failed({ scope }) can't match the field ${JSON.stringify(path.join("."))}.`);
|
|
210
|
+
return { path, jsonPath: `$${path.map((key) => `."${key}"`).join("")}`, value };
|
|
211
|
+
});
|
|
212
|
+
const found = await query(sql.failed, [source ?? "", matches ? JSON.stringify(matches) : "", at, after, limit + 1]);
|
|
213
|
+
const page = found.slice(0, limit);
|
|
214
|
+
const last = page.at(-1);
|
|
215
|
+
return {
|
|
216
|
+
rows: page.map((row) => ({
|
|
217
|
+
id: String(row.id),
|
|
218
|
+
job: JSON.parse(String(row.job)), // JSON text, on every driver
|
|
219
|
+
error: String(row.last_error ?? ""),
|
|
220
|
+
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
|
|
221
|
+
})),
|
|
222
|
+
cursor: found.length > limit && last ? JSON.stringify([String(last.failed_at), String(last.id)]) : null,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Failed jobs in the jobs table, for a queue that can't keep them itself (`cloudflareQueue` alone), like Laravel's
|
|
227
|
+
* `failed` driver next to SQS. `retry` takes the row and hands the job back to the queue.
|
|
228
|
+
*/
|
|
229
|
+
export function failedStore(sql) {
|
|
230
|
+
const database = registryDatabase("failedJobs()");
|
|
231
|
+
const query = (text, params) => database.get().query(database.get().db, text, params);
|
|
232
|
+
return {
|
|
233
|
+
name: "failedJobs()",
|
|
234
|
+
sql: true,
|
|
235
|
+
connect: (setup) => database.connect(setup),
|
|
236
|
+
...rowsOfFailed(sql, query),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/** Failed rows in the jobs table: kept, listed, taken back for a retry, forgotten. A waiting or running row is never touched. */
|
|
240
|
+
function rowsOfFailed(sql, query) {
|
|
241
|
+
return {
|
|
181
242
|
async fail(job, error) {
|
|
182
243
|
await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
|
|
183
244
|
},
|
|
245
|
+
/**
|
|
246
|
+
* Newest first, by a cursor on (failed_at, id) rather than an offset, so a script retrying page by page skips none.
|
|
247
|
+
* One row past the limit says there's another page.
|
|
248
|
+
*/
|
|
249
|
+
failed: (q) => listFailed(sql, query, q),
|
|
250
|
+
async take(id) {
|
|
251
|
+
const [row] = await query(sql.take, [id]);
|
|
252
|
+
return row ? JSON.parse(String(row.job)) : undefined;
|
|
253
|
+
},
|
|
254
|
+
async forget(id) {
|
|
255
|
+
return (await query(sql.forget, [id])).length > 0;
|
|
256
|
+
},
|
|
184
257
|
};
|
|
185
258
|
}
|
|
259
|
+
/** A `failed` page's cursor: the last row's `failed_at` (as the database gave it) and id. */
|
|
260
|
+
function cursorOf(cursor) {
|
|
261
|
+
let parsed;
|
|
262
|
+
try {
|
|
263
|
+
parsed = JSON.parse(cursor);
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
parsed = undefined;
|
|
267
|
+
}
|
|
268
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || !parsed.every((part) => typeof part === "string" && part))
|
|
269
|
+
throw new Error(`[logic-sdk] jobs.failed({ cursor }) takes the cursor of the page before (got ${JSON.stringify(cursor)}).`);
|
|
270
|
+
return parsed;
|
|
271
|
+
}
|
|
186
272
|
/** Not `localeCompare`: processes with another locale would lock in another order. */
|
|
187
273
|
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
188
274
|
const describe = (e) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,32 +1 @@
|
|
|
1
|
-
|
|
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;
|
|
11
|
-
};
|
|
12
|
-
}>;
|
|
13
|
-
export interface AIToolOptions {
|
|
14
|
-
/** Overrides `meta.ai.description` for this tool. */
|
|
15
|
-
description?: string;
|
|
16
|
-
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
17
|
-
onError?: (error: unknown) => void;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
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.
|
|
23
|
-
*
|
|
24
|
-
* ```ts
|
|
25
|
-
* const caller = registry.as(await scopeFrom(request));
|
|
26
|
-
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
27
|
-
* ```
|
|
28
|
-
*
|
|
29
|
-
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
30
|
-
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
31
|
-
*/
|
|
32
|
-
export declare function toAITool<F extends PublishableFn>(caller: Caller<ScopeOfFn<F>>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
|
|
1
|
+
export { toAITool, type AIMeta, type AIToolOptions } from "./integrations/ai.ts";
|
package/dist/ai.js
CHANGED
|
@@ -1,40 +1 @@
|
|
|
1
|
-
|
|
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;
|
|
5
|
-
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
6
|
-
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
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.
|
|
11
|
-
*
|
|
12
|
-
* ```ts
|
|
13
|
-
* const caller = registry.as(await scopeFrom(request));
|
|
14
|
-
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
15
|
-
* ```
|
|
16
|
-
*
|
|
17
|
-
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
18
|
-
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
19
|
-
*/
|
|
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`).");
|
|
23
|
-
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
24
|
-
return tool({
|
|
25
|
-
description: options.description ?? aiMeta(fn)?.description,
|
|
26
|
-
inputSchema: fn.input ?? noInput,
|
|
27
|
-
outputSchema: fn.output,
|
|
28
|
-
async execute(input, { abortSignal }) {
|
|
29
|
-
try {
|
|
30
|
-
return await caller.run(fn, input, { signal: abortSignal });
|
|
31
|
-
}
|
|
32
|
-
catch (e) {
|
|
33
|
-
if (isDomainError(e))
|
|
34
|
-
throw e;
|
|
35
|
-
onError(e);
|
|
36
|
-
throw new Error("internal_error");
|
|
37
|
-
}
|
|
38
|
-
},
|
|
39
|
-
});
|
|
40
|
-
}
|
|
1
|
+
export { toAITool } from "./integrations/ai.js";
|
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,55 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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>;
|
|
1
|
+
export { cloudflareQueue, type QueueBinding } from "./adapters/cloudflare-queue.ts";
|
|
2
|
+
export { handleQueue, handleScheduled, type QueueBatch } from "./hosts/cloudflare.ts";
|