logic-sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -15
- package/bin/logic-sdk.js +1 -1
- 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 +236 -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 +78 -379
- package/dist/index.js +240 -186
- 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 +655 -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 +110 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +404 -564
- 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 +685 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- package/src/drizzle.ts +0 -39
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3
|
+
import { causes } from "../errors.js";
|
|
4
|
+
export { databaseQueue, jobsSchema, outbox } from "../postgres.js";
|
|
5
|
+
/**
|
|
6
|
+
* Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
|
|
7
|
+
* PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
|
|
8
|
+
* The types reject SQLite and libsql databases here.
|
|
9
|
+
*/
|
|
10
|
+
export function drizzleAdapter(db, options = {}) {
|
|
11
|
+
return {
|
|
12
|
+
db,
|
|
13
|
+
transactionAttempts: options.transactionAttempts,
|
|
14
|
+
transaction: (fn) => db.transaction(fn),
|
|
15
|
+
nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
|
|
16
|
+
retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
|
|
17
|
+
query: async (client, text, params) => client.execute(toSql(text, params), "objects"),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
|
|
21
|
+
const toSql = (text, params) => sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
|
|
22
|
+
/** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
|
|
23
|
+
const RETRYABLE = new Set(["40001", "40P01"]);
|
|
24
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
25
|
+
export function sqlState(error) {
|
|
26
|
+
for (const e of causes(error))
|
|
27
|
+
if ("code" in e && typeof e.code === "string")
|
|
28
|
+
return e.code;
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
|
|
33
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
|
|
34
|
+
* done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
35
|
+
*/
|
|
36
|
+
export const jobsTable = pgTable("logic_jobs", {
|
|
37
|
+
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
38
|
+
id: text("id").primaryKey(),
|
|
39
|
+
job: jsonb("job").$type().notNull(),
|
|
40
|
+
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
41
|
+
status: text("status").$type().notNull().default("pending"),
|
|
42
|
+
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
43
|
+
attempts: integer("attempts").notNull().default(0),
|
|
44
|
+
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
45
|
+
availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
|
|
46
|
+
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
47
|
+
receipt: text("receipt"),
|
|
48
|
+
/** The last failure, with its stack. */
|
|
49
|
+
lastError: text("last_error"),
|
|
50
|
+
failedAt: timestamp("failed_at", { withTimezone: true }),
|
|
51
|
+
/** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
|
|
52
|
+
replaceKey: text("replace_key"),
|
|
53
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
54
|
+
}, (t) => [
|
|
55
|
+
index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
|
|
56
|
+
// one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
57
|
+
uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql `status = 'pending' and attempts = 0`),
|
|
58
|
+
]);
|
|
59
|
+
/**
|
|
60
|
+
* The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
|
|
61
|
+
* Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
|
|
62
|
+
*/
|
|
63
|
+
export const cronRunsTable = pgTable("logic_cron_runs", {
|
|
64
|
+
/** The cron job's id, `<cron id>@<minute>`. */
|
|
65
|
+
id: text("id").primaryKey(),
|
|
66
|
+
ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
|
|
67
|
+
});
|
|
@@ -0,0 +1,242 @@
|
|
|
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 "../sqlite.ts";
|
|
4
|
+
/** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
|
|
5
|
+
interface SyncSqlite {
|
|
6
|
+
all<T>(query: SQL): T[];
|
|
7
|
+
run(query: SQL): unknown;
|
|
8
|
+
$client: {
|
|
9
|
+
close(): unknown;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** What mutations get: a connection of their own, inside the transaction the adapter opened. */
|
|
13
|
+
export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
|
|
14
|
+
/** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
|
|
15
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
|
|
16
|
+
/** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
|
|
17
|
+
export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
18
|
+
export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
|
|
19
|
+
/**
|
|
20
|
+
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
21
|
+
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
22
|
+
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare function drizzleAdapter<Db extends SyncSqlite>(open: () => Db, options?: DrizzleAdapterOptions): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
29
|
+
/**
|
|
30
|
+
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
31
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
32
|
+
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
33
|
+
*/
|
|
34
|
+
export declare const jobsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
35
|
+
name: "logic_jobs";
|
|
36
|
+
schema: undefined;
|
|
37
|
+
columns: {
|
|
38
|
+
id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
39
|
+
name: string;
|
|
40
|
+
tableName: "logic_jobs";
|
|
41
|
+
dataType: "string";
|
|
42
|
+
data: string;
|
|
43
|
+
driverParam: string;
|
|
44
|
+
notNull: true;
|
|
45
|
+
hasDefault: false;
|
|
46
|
+
isPrimaryKey: true;
|
|
47
|
+
isAutoincrement: false;
|
|
48
|
+
hasRuntimeDefault: false;
|
|
49
|
+
enumValues: [string, ...string[]];
|
|
50
|
+
baseColumn: never;
|
|
51
|
+
identity: undefined;
|
|
52
|
+
generated: undefined;
|
|
53
|
+
}, {}>;
|
|
54
|
+
job: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
55
|
+
name: string;
|
|
56
|
+
tableName: "logic_jobs";
|
|
57
|
+
dataType: "object json";
|
|
58
|
+
data: Job;
|
|
59
|
+
driverParam: string;
|
|
60
|
+
notNull: true;
|
|
61
|
+
hasDefault: false;
|
|
62
|
+
isPrimaryKey: false;
|
|
63
|
+
isAutoincrement: false;
|
|
64
|
+
hasRuntimeDefault: false;
|
|
65
|
+
enumValues: undefined;
|
|
66
|
+
baseColumn: never;
|
|
67
|
+
identity: undefined;
|
|
68
|
+
generated: undefined;
|
|
69
|
+
}, {}>;
|
|
70
|
+
status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
71
|
+
name: string;
|
|
72
|
+
tableName: "logic_jobs";
|
|
73
|
+
dataType: "string";
|
|
74
|
+
data: "failed" | "pending";
|
|
75
|
+
driverParam: string;
|
|
76
|
+
notNull: true;
|
|
77
|
+
hasDefault: true;
|
|
78
|
+
isPrimaryKey: false;
|
|
79
|
+
isAutoincrement: false;
|
|
80
|
+
hasRuntimeDefault: false;
|
|
81
|
+
enumValues: [string, ...string[]];
|
|
82
|
+
baseColumn: never;
|
|
83
|
+
identity: undefined;
|
|
84
|
+
generated: undefined;
|
|
85
|
+
}, {}>;
|
|
86
|
+
attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
87
|
+
name: string;
|
|
88
|
+
tableName: "logic_jobs";
|
|
89
|
+
dataType: "number int53";
|
|
90
|
+
data: number;
|
|
91
|
+
driverParam: number;
|
|
92
|
+
notNull: true;
|
|
93
|
+
hasDefault: true;
|
|
94
|
+
isPrimaryKey: false;
|
|
95
|
+
isAutoincrement: false;
|
|
96
|
+
hasRuntimeDefault: false;
|
|
97
|
+
enumValues: undefined;
|
|
98
|
+
baseColumn: never;
|
|
99
|
+
identity: undefined;
|
|
100
|
+
generated: undefined;
|
|
101
|
+
}, {}>;
|
|
102
|
+
availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
103
|
+
name: string;
|
|
104
|
+
tableName: "logic_jobs";
|
|
105
|
+
dataType: "object date";
|
|
106
|
+
data: Date;
|
|
107
|
+
driverParam: number;
|
|
108
|
+
notNull: true;
|
|
109
|
+
hasDefault: true;
|
|
110
|
+
isPrimaryKey: false;
|
|
111
|
+
isAutoincrement: false;
|
|
112
|
+
hasRuntimeDefault: false;
|
|
113
|
+
enumValues: undefined;
|
|
114
|
+
baseColumn: never;
|
|
115
|
+
identity: undefined;
|
|
116
|
+
generated: undefined;
|
|
117
|
+
}, {}>;
|
|
118
|
+
receipt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
119
|
+
name: string;
|
|
120
|
+
tableName: "logic_jobs";
|
|
121
|
+
dataType: "string";
|
|
122
|
+
data: string;
|
|
123
|
+
driverParam: string;
|
|
124
|
+
notNull: false;
|
|
125
|
+
hasDefault: false;
|
|
126
|
+
isPrimaryKey: false;
|
|
127
|
+
isAutoincrement: false;
|
|
128
|
+
hasRuntimeDefault: false;
|
|
129
|
+
enumValues: [string, ...string[]];
|
|
130
|
+
baseColumn: never;
|
|
131
|
+
identity: undefined;
|
|
132
|
+
generated: undefined;
|
|
133
|
+
}, {}>;
|
|
134
|
+
lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
135
|
+
name: string;
|
|
136
|
+
tableName: "logic_jobs";
|
|
137
|
+
dataType: "string";
|
|
138
|
+
data: string;
|
|
139
|
+
driverParam: string;
|
|
140
|
+
notNull: false;
|
|
141
|
+
hasDefault: false;
|
|
142
|
+
isPrimaryKey: false;
|
|
143
|
+
isAutoincrement: false;
|
|
144
|
+
hasRuntimeDefault: false;
|
|
145
|
+
enumValues: [string, ...string[]];
|
|
146
|
+
baseColumn: never;
|
|
147
|
+
identity: undefined;
|
|
148
|
+
generated: undefined;
|
|
149
|
+
}, {}>;
|
|
150
|
+
failedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
151
|
+
name: string;
|
|
152
|
+
tableName: "logic_jobs";
|
|
153
|
+
dataType: "object date";
|
|
154
|
+
data: Date;
|
|
155
|
+
driverParam: number;
|
|
156
|
+
notNull: false;
|
|
157
|
+
hasDefault: false;
|
|
158
|
+
isPrimaryKey: false;
|
|
159
|
+
isAutoincrement: false;
|
|
160
|
+
hasRuntimeDefault: false;
|
|
161
|
+
enumValues: undefined;
|
|
162
|
+
baseColumn: never;
|
|
163
|
+
identity: undefined;
|
|
164
|
+
generated: undefined;
|
|
165
|
+
}, {}>;
|
|
166
|
+
replaceKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
167
|
+
name: string;
|
|
168
|
+
tableName: "logic_jobs";
|
|
169
|
+
dataType: "string";
|
|
170
|
+
data: string;
|
|
171
|
+
driverParam: string;
|
|
172
|
+
notNull: false;
|
|
173
|
+
hasDefault: false;
|
|
174
|
+
isPrimaryKey: false;
|
|
175
|
+
isAutoincrement: false;
|
|
176
|
+
hasRuntimeDefault: false;
|
|
177
|
+
enumValues: [string, ...string[]];
|
|
178
|
+
baseColumn: never;
|
|
179
|
+
identity: undefined;
|
|
180
|
+
generated: undefined;
|
|
181
|
+
}, {}>;
|
|
182
|
+
createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
183
|
+
name: string;
|
|
184
|
+
tableName: "logic_jobs";
|
|
185
|
+
dataType: "object date";
|
|
186
|
+
data: Date;
|
|
187
|
+
driverParam: number;
|
|
188
|
+
notNull: true;
|
|
189
|
+
hasDefault: true;
|
|
190
|
+
isPrimaryKey: false;
|
|
191
|
+
isAutoincrement: false;
|
|
192
|
+
hasRuntimeDefault: false;
|
|
193
|
+
enumValues: undefined;
|
|
194
|
+
baseColumn: never;
|
|
195
|
+
identity: undefined;
|
|
196
|
+
generated: undefined;
|
|
197
|
+
}, {}>;
|
|
198
|
+
};
|
|
199
|
+
dialect: 'sqlite';
|
|
200
|
+
isAlias: false;
|
|
201
|
+
}>;
|
|
202
|
+
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
203
|
+
export declare const cronRunsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
204
|
+
name: "logic_cron_runs";
|
|
205
|
+
schema: undefined;
|
|
206
|
+
columns: {
|
|
207
|
+
id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
208
|
+
name: string;
|
|
209
|
+
tableName: "logic_cron_runs";
|
|
210
|
+
dataType: "string";
|
|
211
|
+
data: string;
|
|
212
|
+
driverParam: string;
|
|
213
|
+
notNull: true;
|
|
214
|
+
hasDefault: false;
|
|
215
|
+
isPrimaryKey: true;
|
|
216
|
+
isAutoincrement: false;
|
|
217
|
+
hasRuntimeDefault: false;
|
|
218
|
+
enumValues: [string, ...string[]];
|
|
219
|
+
baseColumn: never;
|
|
220
|
+
identity: undefined;
|
|
221
|
+
generated: undefined;
|
|
222
|
+
}, {}>;
|
|
223
|
+
ranAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
224
|
+
name: string;
|
|
225
|
+
tableName: "logic_cron_runs";
|
|
226
|
+
dataType: "object date";
|
|
227
|
+
data: Date;
|
|
228
|
+
driverParam: number;
|
|
229
|
+
notNull: true;
|
|
230
|
+
hasDefault: true;
|
|
231
|
+
isPrimaryKey: false;
|
|
232
|
+
isAutoincrement: false;
|
|
233
|
+
hasRuntimeDefault: false;
|
|
234
|
+
enumValues: undefined;
|
|
235
|
+
baseColumn: never;
|
|
236
|
+
identity: undefined;
|
|
237
|
+
generated: undefined;
|
|
238
|
+
}, {}>;
|
|
239
|
+
};
|
|
240
|
+
dialect: 'sqlite';
|
|
241
|
+
isAlias: false;
|
|
242
|
+
}>;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import { causes } from "../errors.js";
|
|
4
|
+
export { databaseQueue, jobsSchema, outbox } from "../sqlite.js";
|
|
5
|
+
/** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
|
|
6
|
+
const BUSY_TIMEOUT = 5000;
|
|
7
|
+
/**
|
|
8
|
+
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
9
|
+
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
10
|
+
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export function drizzleAdapter(open, options = {}) {
|
|
17
|
+
const reader = open();
|
|
18
|
+
checkOpen(open, reader);
|
|
19
|
+
exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
|
|
20
|
+
exec(reader, "PRAGMA query_only = ON");
|
|
21
|
+
const takeTurn = turns();
|
|
22
|
+
const transaction = (fn) => takeTurn(async (restartClock) => {
|
|
23
|
+
const tx = await begin(open, restartClock);
|
|
24
|
+
try {
|
|
25
|
+
const out = await fn(tx);
|
|
26
|
+
exec(tx, "COMMIT");
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
undo(tx, "ROLLBACK");
|
|
31
|
+
throw e;
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
tx.$client.close();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
db: reader,
|
|
39
|
+
transactionAttempts: options.transactionAttempts,
|
|
40
|
+
transaction,
|
|
41
|
+
nest: (tx) => savepoints(tx),
|
|
42
|
+
retryable: isBusy,
|
|
43
|
+
// on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
|
|
44
|
+
query: async (client, text, params) => client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Transactions inside a transaction, as savepoints: the test registry's. */
|
|
48
|
+
function savepoints(tx) {
|
|
49
|
+
const takeTurn = turns();
|
|
50
|
+
return {
|
|
51
|
+
db: tx,
|
|
52
|
+
transaction: (fn) => takeTurn(async () => {
|
|
53
|
+
exec(tx, "SAVEPOINT logic_sdk");
|
|
54
|
+
try {
|
|
55
|
+
const out = await fn(tx);
|
|
56
|
+
exec(tx, "RELEASE logic_sdk");
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
|
|
61
|
+
throw e;
|
|
62
|
+
}
|
|
63
|
+
}),
|
|
64
|
+
nest: savepoints,
|
|
65
|
+
query: async (client, text, params) => rowsOf(client, text, params),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const exec = (db, text) => db.run(sql.raw(text));
|
|
69
|
+
/** SQL text with `?` parameters as a Drizzle query. */
|
|
70
|
+
const toSql = (text, params) => sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
|
|
71
|
+
const rowsOf = (db, text, params) => db.all(toSql(text, params));
|
|
72
|
+
/** SQLite rolls some failures back by itself (a full disk, `RAISE(ROLLBACK)`): then there's nothing to undo, and the error that did it is the one to report. */
|
|
73
|
+
function undo(db, ...statements) {
|
|
74
|
+
try {
|
|
75
|
+
for (const statement of statements)
|
|
76
|
+
exec(db, statement);
|
|
77
|
+
}
|
|
78
|
+
catch { }
|
|
79
|
+
}
|
|
80
|
+
/** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
|
|
81
|
+
function checkOpen(open, reader) {
|
|
82
|
+
const another = open();
|
|
83
|
+
if (another.$client === reader.$client)
|
|
84
|
+
throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
|
|
85
|
+
const [main] = another.all(sql `PRAGMA database_list`);
|
|
86
|
+
another.$client.close();
|
|
87
|
+
if (!main?.file)
|
|
88
|
+
throw new Error("[logic-sdk] drizzleAdapter needs SQLite on a disk: an in-memory database is a different one on each connection. Use a temporary file in tests.");
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
|
|
92
|
+
* since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
|
|
93
|
+
*/
|
|
94
|
+
async function begin(open, restartClock) {
|
|
95
|
+
const deadline = Date.now() + BUSY_TIMEOUT;
|
|
96
|
+
for (;;) {
|
|
97
|
+
restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
|
|
98
|
+
let tx;
|
|
99
|
+
try {
|
|
100
|
+
tx = open();
|
|
101
|
+
exec(tx, "PRAGMA busy_timeout = 0");
|
|
102
|
+
exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
|
|
103
|
+
exec(tx, "BEGIN IMMEDIATE");
|
|
104
|
+
return tx;
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
tx?.$client.close();
|
|
108
|
+
if (!isBusy(e) || Date.now() >= deadline)
|
|
109
|
+
throw e;
|
|
110
|
+
}
|
|
111
|
+
await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
|
|
116
|
+
* when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
|
|
117
|
+
*/
|
|
118
|
+
function turns() {
|
|
119
|
+
let last = Promise.resolve();
|
|
120
|
+
let startedAt = 0;
|
|
121
|
+
const restartClock = () => {
|
|
122
|
+
startedAt = Date.now();
|
|
123
|
+
};
|
|
124
|
+
return async (work) => {
|
|
125
|
+
const arrived = Date.now();
|
|
126
|
+
const ahead = last;
|
|
127
|
+
const done = Promise.withResolvers();
|
|
128
|
+
last = ahead.then(() => done.promise);
|
|
129
|
+
try {
|
|
130
|
+
const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
|
|
131
|
+
while (!(await settlesBy(ahead, giveUpAt()))) {
|
|
132
|
+
// the one ahead may have changed while we waited: the line moved
|
|
133
|
+
if (Date.now() >= giveUpAt())
|
|
134
|
+
throw new Error(HELD);
|
|
135
|
+
}
|
|
136
|
+
restartClock();
|
|
137
|
+
return await work(restartClock);
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
done.resolve();
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const HELD = "[logic-sdk] Waited 5 seconds for a transaction in this process, and SQLite writes one at a time. Does a mutation await registry.as(scope).run instead of ctx.run, or do slow work that belongs in an action? In tests, is a t.begin() still open?";
|
|
145
|
+
/** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
|
|
146
|
+
const settlesBy = (promise, time) => new Promise((resolve) => {
|
|
147
|
+
const timer = setTimeout(() => resolve(false), time - Date.now());
|
|
148
|
+
void promise.then(() => {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
resolve(true);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
/** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
|
|
154
|
+
function isBusy(error) {
|
|
155
|
+
for (const e of causes(error))
|
|
156
|
+
if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message)))
|
|
157
|
+
return true;
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
const now = sql `(cast(unixepoch('subsec') * 1000 as integer))`;
|
|
161
|
+
/**
|
|
162
|
+
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
163
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
164
|
+
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
165
|
+
*/
|
|
166
|
+
export const jobsTable = sqliteTable("logic_jobs", {
|
|
167
|
+
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
168
|
+
id: text("id").primaryKey(),
|
|
169
|
+
job: text("job", { mode: "json" }).$type().notNull(),
|
|
170
|
+
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
171
|
+
status: text("status").$type().notNull().default("pending"),
|
|
172
|
+
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
173
|
+
attempts: integer("attempts").notNull().default(0),
|
|
174
|
+
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
175
|
+
availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
176
|
+
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
177
|
+
receipt: text("receipt"),
|
|
178
|
+
/** The last failure, with its stack. */
|
|
179
|
+
lastError: text("last_error"),
|
|
180
|
+
failedAt: integer("failed_at", { mode: "timestamp_ms" }),
|
|
181
|
+
/** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
|
|
182
|
+
replaceKey: text("replace_key"),
|
|
183
|
+
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
184
|
+
}, (t) => [
|
|
185
|
+
index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
|
|
186
|
+
// one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
187
|
+
uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql `status = 'pending' and attempts = 0`),
|
|
188
|
+
]);
|
|
189
|
+
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
190
|
+
export const cronRunsTable = sqliteTable("logic_cron_runs", {
|
|
191
|
+
/** The cron job's id, `<cron id>@<minute>`. */
|
|
192
|
+
id: text("id").primaryKey(),
|
|
193
|
+
ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
194
|
+
});
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
import type { Errors } from "./types.ts";
|
|
3
|
+
export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
|
|
4
|
+
/**
|
|
5
|
+
* An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
|
|
6
|
+
* adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
|
|
7
|
+
* bugs) is unexpected: adapters answer 500 and report it.
|
|
8
|
+
*/
|
|
9
|
+
export declare class DomainError extends Error {
|
|
10
|
+
readonly kind: ErrorKind;
|
|
11
|
+
readonly code: string;
|
|
12
|
+
readonly details: unknown;
|
|
13
|
+
constructor(kind: ErrorKind, code: string, details?: unknown);
|
|
14
|
+
}
|
|
15
|
+
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
16
|
+
export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
|
|
17
|
+
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
18
|
+
export declare const errorsFor: (id: string) => Errors;
|
|
19
|
+
/** What a schema said, as JSON: `[{ message, path }]`. */
|
|
20
|
+
export declare const describeIssues: (issues: readonly StandardSchemaV1.Issue[]) => {
|
|
21
|
+
message: string;
|
|
22
|
+
path: PropertyKey[] | undefined;
|
|
23
|
+
}[];
|
|
24
|
+
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
25
|
+
export declare class StalePayload extends Error {
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
29
|
+
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
30
|
+
*/
|
|
31
|
+
export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
|
|
32
|
+
/** An error and the ones it wraps (`cause`), five deep at most: a driver's error usually arrives wrapped by the ORM. */
|
|
33
|
+
export declare function causes(error: unknown): Generator<object>;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
|
|
3
|
+
* adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
|
|
4
|
+
* bugs) is unexpected: adapters answer 500 and report it.
|
|
5
|
+
*/
|
|
6
|
+
export class DomainError extends Error {
|
|
7
|
+
kind;
|
|
8
|
+
code;
|
|
9
|
+
details;
|
|
10
|
+
constructor(kind, code, details) {
|
|
11
|
+
// the details are in the message too: logs and AI tool errors (which show only the message) stay useful
|
|
12
|
+
super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
|
|
13
|
+
this.name = "DomainError";
|
|
14
|
+
this.kind = kind;
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.details = details;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
20
|
+
export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
|
|
21
|
+
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
22
|
+
export const errorsFor = (id) => {
|
|
23
|
+
const module = id.slice(0, id.indexOf("."));
|
|
24
|
+
return {
|
|
25
|
+
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
26
|
+
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
27
|
+
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
28
|
+
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/** What a schema said, as JSON: `[{ message, path }]`. */
|
|
32
|
+
export const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
33
|
+
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
34
|
+
export class StalePayload extends Error {
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
38
|
+
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
39
|
+
*/
|
|
40
|
+
export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
|
|
41
|
+
/** An error and the ones it wraps (`cause`), five deep at most: a driver's error usually arrives wrapped by the ORM. */
|
|
42
|
+
export function* causes(error) {
|
|
43
|
+
for (let e = error, i = 0; typeof e === "object" && e !== null && i < 5; e = "cause" in e ? e.cause : undefined, i++)
|
|
44
|
+
yield e;
|
|
45
|
+
}
|
package/dist/fetch.d.ts
CHANGED
|
@@ -1,22 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
/**
|
|
3
|
-
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
4
|
-
* For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
|
|
5
|
-
*/
|
|
6
|
-
export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
|
|
1
|
+
import { type ErrorKind } from "./index.ts";
|
|
7
2
|
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
8
3
|
export declare const statusOf: Record<ErrorKind, number>;
|
|
9
|
-
export interface FetchOptions<S extends object> {
|
|
10
|
-
/** Build the scope for this request (session → actor, account, locale...). */
|
|
11
|
-
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
12
|
-
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
13
|
-
basePath?: string;
|
|
14
|
-
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
15
|
-
onError?: (error: unknown) => void;
|
|
16
|
-
}
|
|
17
4
|
/**
|
|
18
|
-
* A
|
|
19
|
-
*
|
|
20
|
-
*
|
|
5
|
+
* A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
|
|
6
|
+
* (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
|
|
7
|
+
* and logs it, and its message never reaches the client.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* app.post("/orders", async (c) => {
|
|
11
|
+
* try {
|
|
12
|
+
* return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
|
|
13
|
+
* } catch (e) {
|
|
14
|
+
* return toResponse(e);
|
|
15
|
+
* }
|
|
16
|
+
* });
|
|
17
|
+
* ```
|
|
21
18
|
*/
|
|
22
|
-
export declare function
|
|
19
|
+
export declare function toResponse(error: unknown): Response;
|