logic-sdk 0.7.1 → 0.7.3
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 +9 -10
- package/dist/adapters/cloudflare-queue.d.ts +15 -0
- package/dist/adapters/cloudflare-queue.js +58 -0
- package/dist/adapters/drizzle-pg.d.ts +280 -0
- package/dist/adapters/drizzle-pg.js +78 -0
- package/dist/adapters/drizzle-sqlite.d.ts +273 -0
- package/dist/adapters/drizzle-sqlite.js +203 -0
- package/dist/adapters/postgres.d.ts +33 -0
- package/dist/adapters/postgres.js +129 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +108 -0
- package/dist/adapters/stored-jobs.d.ts +89 -0
- package/dist/adapters/stored-jobs.js +370 -0
- 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 +37 -0
- package/dist/core/jobs.d.ts +63 -0
- package/dist/core/jobs.js +514 -0
- package/dist/core/registry.d.ts +156 -0
- package/dist/core/registry.js +515 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +232 -0
- package/dist/{types.d.ts → core/types.d.ts} +289 -64
- 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 +43 -0
- package/dist/hosts/cloudflare.js +40 -0
- package/dist/hosts/node.d.ts +36 -0
- package/dist/hosts/node.js +103 -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/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 -12
- package/skills/logic-sdk/SKILL.md +6 -5
- package/src/adapters/cloudflare-queue.ts +65 -0
- package/src/adapters/drizzle-pg.ts +117 -0
- package/src/adapters/drizzle-sqlite.ts +241 -0
- package/src/adapters/postgres.ts +136 -0
- package/src/adapters/sqlite.ts +116 -0
- package/src/adapters/stored-jobs.ts +463 -0
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +38 -0
- package/src/core/jobs.ts +548 -0
- package/src/core/registry.ts +719 -0
- package/src/core/testing.ts +309 -0
- package/src/{types.ts → core/types.ts} +280 -60
- 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 +55 -0
- package/src/hosts/node.ts +126 -0
- package/src/index.ts +17 -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/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- package/dist/jobs.d.ts +0 -44
- package/dist/jobs.js +0 -260
- package/dist/pg-boss.d.ts +0 -53
- package/dist/pg-boss.js +0 -213
- package/dist/stored-jobs.d.ts +0 -64
- package/dist/stored-jobs.js +0 -188
- package/src/jobs.ts +0 -307
- package/src/pg-boss.ts +0 -241
- package/src/stored-jobs.ts +0 -260
- /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
package/src/drizzle/pg.ts
CHANGED
|
@@ -1,110 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { causes } from "../errors.ts";
|
|
5
|
-
|
|
6
|
-
export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../postgres.ts";
|
|
7
|
-
|
|
8
|
-
/** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
|
|
9
|
-
interface Transactional {
|
|
10
|
-
transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
|
|
11
|
-
execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
|
|
15
|
-
type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
|
|
19
|
-
* events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
|
|
20
|
-
*/
|
|
21
|
-
export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
|
|
22
|
-
|
|
23
|
-
/** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
|
|
24
|
-
export type DrizzleReader<Db> = Omit<
|
|
25
|
-
Db,
|
|
26
|
-
"insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView"
|
|
27
|
-
>;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
|
|
31
|
-
* the transaction.
|
|
32
|
-
*/
|
|
33
|
-
export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
|
|
34
|
-
|
|
35
|
-
export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
|
|
39
|
-
* PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
|
|
40
|
-
* The types reject SQLite and libsql databases here.
|
|
41
|
-
*/
|
|
42
|
-
export function drizzleAdapter<Db extends Transactional>(
|
|
43
|
-
db: Db,
|
|
44
|
-
options: DrizzleAdapterOptions = {},
|
|
45
|
-
): SqlDatabase<Db, Transaction<Db>> { // the whole transaction, for `nest`; mutations see it as a DrizzleTx
|
|
46
|
-
return {
|
|
47
|
-
db,
|
|
48
|
-
transactionAttempts: options.transactionAttempts,
|
|
49
|
-
transaction: (fn) => db.transaction(fn),
|
|
50
|
-
nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
|
|
51
|
-
retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
|
|
52
|
-
query: async (client: Transactional, text, params) => client.execute(toSql(text, params), "objects"),
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
|
|
57
|
-
const toSql = (text: string, params: unknown[]) =>
|
|
58
|
-
sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
|
|
59
|
-
|
|
60
|
-
/** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
|
|
61
|
-
const RETRYABLE = new Set(["40001", "40P01"]);
|
|
62
|
-
|
|
63
|
-
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
64
|
-
export function sqlState(error: unknown): string | undefined {
|
|
65
|
-
for (const e of causes(error)) if ("code" in e && typeof e.code === "string") return e.code;
|
|
66
|
-
return undefined;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
|
|
71
|
-
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
|
|
72
|
-
* done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
73
|
-
*/
|
|
74
|
-
export const jobsTable = pgTable(
|
|
75
|
-
"logic_jobs",
|
|
76
|
-
{
|
|
77
|
-
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
78
|
-
id: text("id").primaryKey(),
|
|
79
|
-
job: jsonb("job").$type<Job>().notNull(),
|
|
80
|
-
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
81
|
-
status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
|
|
82
|
-
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
83
|
-
attempts: integer("attempts").notNull().default(0),
|
|
84
|
-
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
85
|
-
availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
|
|
86
|
-
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
87
|
-
receipt: text("receipt"),
|
|
88
|
-
/** The last failure, with its stack. */
|
|
89
|
-
lastError: text("last_error"),
|
|
90
|
-
failedAt: timestamp("failed_at", { withTimezone: true }),
|
|
91
|
-
/** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
|
|
92
|
-
replaceKey: text("replace_key"),
|
|
93
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
94
|
-
},
|
|
95
|
-
(t) => [
|
|
96
|
-
index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
|
|
97
|
-
// one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
98
|
-
uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
|
|
99
|
-
],
|
|
100
|
-
);
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
|
|
104
|
-
* Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
|
|
105
|
-
*/
|
|
106
|
-
export const cronRunsTable = pgTable("logic_cron_runs", {
|
|
107
|
-
/** The cron job's id, `<cron id>@<minute>`. */
|
|
108
|
-
id: text("id").primaryKey(),
|
|
109
|
-
ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
|
|
110
|
-
});
|
|
1
|
+
export { cronRunsTable, drizzleAdapter, jobsTable, sqlState, type DrizzleDb, type DrizzleReader, type DrizzleTx } from "../adapters/drizzle-pg.ts";
|
|
2
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "../adapters/postgres.ts";
|
|
3
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "../adapters/stored-jobs.ts";
|
package/src/drizzle/sqlite.ts
CHANGED
|
@@ -1,236 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { causes } from "../errors.ts";
|
|
5
|
-
|
|
6
|
-
export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../sqlite.ts";
|
|
7
|
-
|
|
8
|
-
/** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
|
|
9
|
-
interface SyncSqlite {
|
|
10
|
-
all<T>(query: SQL): T[];
|
|
11
|
-
run(query: SQL): unknown;
|
|
12
|
-
$client: { close(): unknown };
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/** What mutations get: a connection of their own, inside the transaction the adapter opened. */
|
|
16
|
-
export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
|
|
17
|
-
|
|
18
|
-
/** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
|
|
19
|
-
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
|
|
20
|
-
|
|
21
|
-
/** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
|
|
22
|
-
export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
23
|
-
|
|
24
|
-
export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
|
|
25
|
-
|
|
26
|
-
/** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
|
|
27
|
-
const BUSY_TIMEOUT = 5000;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
31
|
-
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
32
|
-
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
33
|
-
*
|
|
34
|
-
* ```ts
|
|
35
|
-
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
36
|
-
* ```
|
|
37
|
-
*/
|
|
38
|
-
export function drizzleAdapter<Db extends SyncSqlite>(
|
|
39
|
-
open: () => Db,
|
|
40
|
-
options: DrizzleAdapterOptions = {},
|
|
41
|
-
): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>> {
|
|
42
|
-
const reader = open();
|
|
43
|
-
checkOpen(open, reader);
|
|
44
|
-
exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
|
|
45
|
-
exec(reader, "PRAGMA query_only = ON");
|
|
46
|
-
|
|
47
|
-
const takeTurn = turns();
|
|
48
|
-
const transaction = <T>(fn: (tx: DrizzleTx<Db>) => Promise<T>) =>
|
|
49
|
-
takeTurn(async (restartClock) => {
|
|
50
|
-
const tx = await begin(open, restartClock);
|
|
51
|
-
try {
|
|
52
|
-
const out = await fn(tx);
|
|
53
|
-
exec(tx, "COMMIT");
|
|
54
|
-
return out;
|
|
55
|
-
} catch (e) {
|
|
56
|
-
undo(tx, "ROLLBACK");
|
|
57
|
-
throw e;
|
|
58
|
-
} finally {
|
|
59
|
-
tx.$client.close();
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
return {
|
|
64
|
-
db: reader,
|
|
65
|
-
transactionAttempts: options.transactionAttempts,
|
|
66
|
-
transaction,
|
|
67
|
-
nest: (tx) => savepoints(tx),
|
|
68
|
-
retryable: isBusy,
|
|
69
|
-
// on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
|
|
70
|
-
query: async (client: Pick<SyncSqlite, "all">, text, params) =>
|
|
71
|
-
client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Transactions inside a transaction, as savepoints: the test registry's. */
|
|
76
|
-
function savepoints<Tx extends Pick<SyncSqlite, "all" | "run">>(tx: Tx): SqlDatabase<Tx, Tx> {
|
|
77
|
-
const takeTurn = turns();
|
|
78
|
-
return {
|
|
79
|
-
db: tx,
|
|
80
|
-
transaction: (fn) =>
|
|
81
|
-
takeTurn(async () => {
|
|
82
|
-
exec(tx, "SAVEPOINT logic_sdk");
|
|
83
|
-
try {
|
|
84
|
-
const out = await fn(tx);
|
|
85
|
-
exec(tx, "RELEASE logic_sdk");
|
|
86
|
-
return out;
|
|
87
|
-
} catch (e) {
|
|
88
|
-
undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
|
|
89
|
-
throw e;
|
|
90
|
-
}
|
|
91
|
-
}),
|
|
92
|
-
nest: savepoints,
|
|
93
|
-
query: async (client, text, params) => rowsOf(client, text, params),
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const exec = (db: Pick<SyncSqlite, "run">, text: string) => db.run(sql.raw(text));
|
|
98
|
-
|
|
99
|
-
/** SQL text with `?` parameters as a Drizzle query. */
|
|
100
|
-
const toSql = (text: string, params: unknown[]) =>
|
|
101
|
-
sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
|
|
102
|
-
|
|
103
|
-
const rowsOf = (db: Pick<SyncSqlite, "all">, text: string, params: unknown[]) =>
|
|
104
|
-
db.all<Record<string, unknown>>(toSql(text, params));
|
|
105
|
-
|
|
106
|
-
/** 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. */
|
|
107
|
-
function undo(db: Pick<SyncSqlite, "run">, ...statements: string[]) {
|
|
108
|
-
try {
|
|
109
|
-
for (const statement of statements) exec(db, statement);
|
|
110
|
-
} catch {}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
|
|
114
|
-
function checkOpen<Db extends SyncSqlite>(open: () => Db, reader: Db) {
|
|
115
|
-
const another = open();
|
|
116
|
-
if (another.$client === reader.$client)
|
|
117
|
-
throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
|
|
118
|
-
const [main] = another.all<{ file: string }>(sql`PRAGMA database_list`);
|
|
119
|
-
another.$client.close();
|
|
120
|
-
if (!main?.file)
|
|
121
|
-
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.");
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
|
|
126
|
-
* since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
|
|
127
|
-
*/
|
|
128
|
-
async function begin<Db extends SyncSqlite>(open: () => Db, restartClock: () => void): Promise<Db> {
|
|
129
|
-
const deadline = Date.now() + BUSY_TIMEOUT;
|
|
130
|
-
for (;;) {
|
|
131
|
-
restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
|
|
132
|
-
let tx: Db | undefined;
|
|
133
|
-
try {
|
|
134
|
-
tx = open();
|
|
135
|
-
exec(tx, "PRAGMA busy_timeout = 0");
|
|
136
|
-
exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
|
|
137
|
-
exec(tx, "BEGIN IMMEDIATE");
|
|
138
|
-
return tx;
|
|
139
|
-
} catch (e) {
|
|
140
|
-
tx?.$client.close();
|
|
141
|
-
if (!isBusy(e) || Date.now() >= deadline) throw e;
|
|
142
|
-
}
|
|
143
|
-
await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
|
|
149
|
-
* when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
|
|
150
|
-
*/
|
|
151
|
-
function turns() {
|
|
152
|
-
let last = Promise.resolve();
|
|
153
|
-
let startedAt = 0;
|
|
154
|
-
const restartClock = () => {
|
|
155
|
-
startedAt = Date.now();
|
|
156
|
-
};
|
|
157
|
-
return async <T>(work: (restartClock: () => void) => Promise<T>): Promise<T> => {
|
|
158
|
-
const arrived = Date.now();
|
|
159
|
-
const ahead = last;
|
|
160
|
-
const done = Promise.withResolvers<void>();
|
|
161
|
-
last = ahead.then(() => done.promise);
|
|
162
|
-
try {
|
|
163
|
-
const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
|
|
164
|
-
while (!(await settlesBy(ahead, giveUpAt()))) {
|
|
165
|
-
// the one ahead may have changed while we waited: the line moved
|
|
166
|
-
if (Date.now() >= giveUpAt()) throw new Error(HELD);
|
|
167
|
-
}
|
|
168
|
-
restartClock();
|
|
169
|
-
return await work(restartClock);
|
|
170
|
-
} finally {
|
|
171
|
-
done.resolve();
|
|
172
|
-
}
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
const HELD =
|
|
177
|
-
"[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?";
|
|
178
|
-
|
|
179
|
-
/** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
|
|
180
|
-
const settlesBy = (promise: Promise<void>, time: number) =>
|
|
181
|
-
new Promise<boolean>((resolve) => {
|
|
182
|
-
const timer = setTimeout(() => resolve(false), time - Date.now());
|
|
183
|
-
void promise.then(() => {
|
|
184
|
-
clearTimeout(timer);
|
|
185
|
-
resolve(true);
|
|
186
|
-
});
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
/** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
|
|
190
|
-
function isBusy(error: unknown): boolean {
|
|
191
|
-
for (const e of causes(error))
|
|
192
|
-
if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message))) return true;
|
|
193
|
-
return false;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
const now = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
200
|
-
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
201
|
-
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
202
|
-
*/
|
|
203
|
-
export const jobsTable = sqliteTable(
|
|
204
|
-
"logic_jobs",
|
|
205
|
-
{
|
|
206
|
-
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
207
|
-
id: text("id").primaryKey(),
|
|
208
|
-
job: text("job", { mode: "json" }).$type<Job>().notNull(),
|
|
209
|
-
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
210
|
-
status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
|
|
211
|
-
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
212
|
-
attempts: integer("attempts").notNull().default(0),
|
|
213
|
-
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
214
|
-
availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
215
|
-
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
216
|
-
receipt: text("receipt"),
|
|
217
|
-
/** The last failure, with its stack. */
|
|
218
|
-
lastError: text("last_error"),
|
|
219
|
-
failedAt: integer("failed_at", { mode: "timestamp_ms" }),
|
|
220
|
-
/** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
|
|
221
|
-
replaceKey: text("replace_key"),
|
|
222
|
-
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
223
|
-
},
|
|
224
|
-
(t) => [
|
|
225
|
-
index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
|
|
226
|
-
// one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
227
|
-
uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
|
|
228
|
-
],
|
|
229
|
-
);
|
|
230
|
-
|
|
231
|
-
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
232
|
-
export const cronRunsTable = sqliteTable("logic_cron_runs", {
|
|
233
|
-
/** The cron job's id, `<cron id>@<minute>`. */
|
|
234
|
-
id: text("id").primaryKey(),
|
|
235
|
-
ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
236
|
-
});
|
|
1
|
+
export { cronRunsTable, drizzleAdapter, jobsTable, type DrizzleDb, type DrizzleReader, type DrizzleTx } from "../adapters/drizzle-sqlite.ts";
|
|
2
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "../adapters/sqlite.ts";
|
|
3
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "../adapters/stored-jobs.ts";
|
package/src/fetch.ts
CHANGED
|
@@ -1,31 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
4
|
-
export const statusOf: Record<ErrorKind, number> = {
|
|
5
|
-
invalid: 400,
|
|
6
|
-
unauthenticated: 401,
|
|
7
|
-
forbidden: 403,
|
|
8
|
-
not_found: 404,
|
|
9
|
-
conflict: 409,
|
|
10
|
-
rejected: 422,
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
|
|
15
|
-
* (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
|
|
16
|
-
* and logs it, and its message never reaches the client.
|
|
17
|
-
*
|
|
18
|
-
* ```ts
|
|
19
|
-
* app.post("/orders", async (c) => {
|
|
20
|
-
* try {
|
|
21
|
-
* return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
|
|
22
|
-
* } catch (e) {
|
|
23
|
-
* return toResponse(e);
|
|
24
|
-
* }
|
|
25
|
-
* });
|
|
26
|
-
* ```
|
|
27
|
-
*/
|
|
28
|
-
export function toResponse(error: unknown): Response {
|
|
29
|
-
if (!isDomainError(error)) throw error;
|
|
30
|
-
return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
|
|
31
|
-
}
|
|
1
|
+
export { statusOf, toResponse } from "./integrations/fetch.ts";
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { defaultBackoff } from "../core/jobs.ts";
|
|
2
|
+
import type { Job, Jobs } from "../core/types.ts";
|
|
3
|
+
|
|
4
|
+
/** What the handler uses of a consumer's `MessageBatch<Job>`. Type your Worker with `ExportedHandler<Env, Job>`. */
|
|
5
|
+
export interface QueueBatch {
|
|
6
|
+
readonly messages: readonly {
|
|
7
|
+
readonly body: Job;
|
|
8
|
+
readonly attempts: number;
|
|
9
|
+
ack(): void;
|
|
10
|
+
retry(options?: { delaySeconds?: number }): void;
|
|
11
|
+
}[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
|
|
16
|
+
* retries it with a backoff (it threw). One message at a time, each acknowledged on its own, so one failure doesn't
|
|
17
|
+
* redeliver the batch. Alone, a throw means the listener has tries left. Behind an outbox, a message is a signal: the
|
|
18
|
+
* job runs from its row (with a `key`, the key's next jobs, in order), and a throw means the table couldn't be reached.
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* async queue(batch, env, ctx) {
|
|
22
|
+
* await handleQueue(makeRegistry(env, ctx), batch);
|
|
23
|
+
* },
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export async function handleQueue(registry: { jobs: Pick<Jobs, "run"> }, batch: QueueBatch): Promise<void> {
|
|
27
|
+
for (const message of batch.messages) {
|
|
28
|
+
try {
|
|
29
|
+
await registry.jobs.run(message.body, { attempt: message.attempts });
|
|
30
|
+
message.ack();
|
|
31
|
+
} catch {
|
|
32
|
+
// already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
|
|
33
|
+
message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (the jobs table's retries,
|
|
40
|
+
* delayed jobs, and what a lost signal or a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
|
|
41
|
+
* 1 = Sunday, so write them as names (`MON`) in both places.
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* async scheduled(controller, env, ctx) {
|
|
45
|
+
* await handleScheduled(makeRegistry(env, ctx), controller);
|
|
46
|
+
* },
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export async function handleScheduled(
|
|
50
|
+
registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
|
|
51
|
+
controller: { readonly scheduledTime: number },
|
|
52
|
+
): Promise<void> {
|
|
53
|
+
await registry.jobs.tick(new Date(controller.scheduledTime));
|
|
54
|
+
await registry.jobs.sweep();
|
|
55
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { Jobs } from "../core/types.ts";
|
|
2
|
+
|
|
3
|
+
export interface WorkOptions {
|
|
4
|
+
/** Jobs this process runs at once. Default 1, like pg-boss, graphile-worker and a Laravel worker: run more processes, or raise it. */
|
|
5
|
+
concurrency?: number;
|
|
6
|
+
/** Seconds a free slot waits before it looks for a job again, when there was none. Default 2, like pg-boss and graphile-worker. */
|
|
7
|
+
pollEvery?: number;
|
|
8
|
+
/**
|
|
9
|
+
* The queues it runs, in order: each claim takes the first one with a job due, so `["mail", "default"]` sends mail
|
|
10
|
+
* first. Each one of `jobs.queues`, or `"default"`. Default: every queue, oldest due first.
|
|
11
|
+
*/
|
|
12
|
+
queues?: readonly string[];
|
|
13
|
+
/** Where a failed tick or claim goes, and a skipped minute. Default `console.error`. */
|
|
14
|
+
onError?: (error: unknown) => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface StopOptions {
|
|
18
|
+
/** Seconds to wait for the running jobs and ticks before giving up on them. Default 30, like pg-boss's `stop()`. */
|
|
19
|
+
timeout?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const MINUTE = 60_000;
|
|
23
|
+
/**
|
|
24
|
+
* Ticks still running before the next is skipped (reported). Overlap is normal, like Laravel and Oban: a slow cron
|
|
25
|
+
* doesn't hold back the next minute. Ten still running means they're stuck (the database is unreachable), and letting
|
|
26
|
+
* them pile up would run a backlog of stale minutes when it comes back.
|
|
27
|
+
*/
|
|
28
|
+
const MAX_RUNNING = 10;
|
|
29
|
+
/** The longest a slot waits between claims while they throw (the database is down), so an outage is reported less and less often. */
|
|
30
|
+
const MAX_WAIT = 30;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A worker, like Laravel's `queue:work` and `schedule:work` in one process: `concurrency` slots, each claiming the next
|
|
34
|
+
* due job (`registry.jobs.sweep({ limit: 1 })`) and waiting `pollEvery` seconds when there's none, and your crons
|
|
35
|
+
* ticked on every minute. Run as many as you like: a job is claimed once, and a cron's minute runs once. A minute the
|
|
36
|
+
* process wasn't running for is skipped, not caught up. In the web process, it takes the jobs requests commit, so they
|
|
37
|
+
* answer at once and it starts them right away; in a process of its own, it claims what's due, `pollEvery` seconds
|
|
38
|
+
* apart when there's nothing (with `databaseQueue({ runIn: "worker" })` that's every job). Returns `stop()`, which
|
|
39
|
+
* waits for the running jobs and ticks, `timeout` seconds at most.
|
|
40
|
+
*
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { work } from "logic-sdk/node";
|
|
43
|
+
* const stop = work(registry, { concurrency: 5 });
|
|
44
|
+
* process.on("SIGTERM", async () => { await stop(); process.exit(0); });
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export function work(registry: { jobs: Pick<Jobs, "tick" | "sweep" | "attach"> }, options: WorkOptions = {}): (options?: StopOptions) => Promise<void> {
|
|
48
|
+
const { concurrency = 1, pollEvery = 2, queues } = options;
|
|
49
|
+
const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
50
|
+
const onError = (error: unknown) => {
|
|
51
|
+
try {
|
|
52
|
+
reportTo(error);
|
|
53
|
+
} catch (inner) {
|
|
54
|
+
console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
let stopping = false;
|
|
58
|
+
/** The sleeping slots: a commit wakes as many as it has jobs, `stop()` all of them. */
|
|
59
|
+
const wakes = new Set<() => void>();
|
|
60
|
+
const wakeUp = (count = Infinity) => {
|
|
61
|
+
for (const wake of [...wakes].slice(0, count)) wake();
|
|
62
|
+
};
|
|
63
|
+
/** Resolves after `seconds`, or at once on `stop()`. */
|
|
64
|
+
const sleep = (seconds: number) =>
|
|
65
|
+
new Promise<void>((resolve) => {
|
|
66
|
+
const wake = () => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
wakes.delete(wake);
|
|
69
|
+
resolve();
|
|
70
|
+
};
|
|
71
|
+
const timer = setTimeout(wake, seconds * 1000);
|
|
72
|
+
wakes.add(wake);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/** One job at a time: the next due one, back to back while there are some. */
|
|
76
|
+
async function slot() {
|
|
77
|
+
let wait = pollEvery;
|
|
78
|
+
while (!stopping) {
|
|
79
|
+
try {
|
|
80
|
+
const { done, failed, discarded, retrying } = await registry.jobs.sweep({ limit: 1, queues });
|
|
81
|
+
wait = pollEvery;
|
|
82
|
+
if (done + failed + discarded + retrying) continue;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
onError(error);
|
|
85
|
+
wait = Math.min(wait * 2, MAX_WAIT);
|
|
86
|
+
}
|
|
87
|
+
await sleep(wait);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const ticks = new Set<Promise<void>>();
|
|
92
|
+
let tickTimer: ReturnType<typeof setTimeout> | undefined;
|
|
93
|
+
const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
|
|
94
|
+
const tick = (at: Date) => {
|
|
95
|
+
if (ticks.size >= MAX_RUNNING) {
|
|
96
|
+
onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const run = registry.jobs.tick(at).then(() => {}, onError);
|
|
100
|
+
ticks.add(run);
|
|
101
|
+
void run.finally(() => ticks.delete(run));
|
|
102
|
+
};
|
|
103
|
+
const armTick = (minute: number) => {
|
|
104
|
+
tickTimer = setTimeout(() => {
|
|
105
|
+
// early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
|
|
106
|
+
const due = Math.max(minute, startOfMinute(Date.now()));
|
|
107
|
+
armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
|
|
108
|
+
tick(new Date(due));
|
|
109
|
+
}, minute - Date.now());
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const detach = registry.jobs.attach({ wake: wakeUp, queues }); // first: it throws on a queue jobs.queues doesn't declare
|
|
113
|
+
armTick(startOfMinute(Date.now()) + MINUTE);
|
|
114
|
+
const slots = Array.from({ length: concurrency }, slot);
|
|
115
|
+
|
|
116
|
+
return async ({ timeout = 30 } = {}) => {
|
|
117
|
+
stopping = true;
|
|
118
|
+
detach(); // requests run their own jobs again
|
|
119
|
+
clearTimeout(tickTimer);
|
|
120
|
+
wakeUp();
|
|
121
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
122
|
+
const gaveUp = new Promise<void>((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
|
|
123
|
+
await Promise.race([Promise.all([...slots, ...ticks]), gaveUp]);
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
};
|
|
126
|
+
}
|