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/README.md
CHANGED
|
@@ -60,7 +60,7 @@ Register your modules and call them from anywhere:
|
|
|
60
60
|
// src/registry.ts
|
|
61
61
|
export const registry = createRegistry({
|
|
62
62
|
modules: { bookings, availability },
|
|
63
|
-
database: drizzleAdapter(db),
|
|
63
|
+
database: { adapter: drizzleAdapter(db) },
|
|
64
64
|
services: { mailer, payments },
|
|
65
65
|
});
|
|
66
66
|
|
|
@@ -76,8 +76,8 @@ const database = drizzleAdapter(db);
|
|
|
76
76
|
|
|
77
77
|
export const registry = createRegistry({
|
|
78
78
|
modules: { bookings, availability },
|
|
79
|
-
database,
|
|
80
|
-
jobs: { adapter: databaseQueue(
|
|
79
|
+
database: { adapter: database },
|
|
80
|
+
jobs: { adapter: databaseQueue(), scope: { store, load } },
|
|
81
81
|
});
|
|
82
82
|
|
|
83
83
|
// a listener, with tries
|
|
@@ -94,8 +94,8 @@ ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
|
|
|
94
94
|
|
|
95
95
|
- **One transaction across modules.** A failure anywhere rolls back everything, even if someone catches it.
|
|
96
96
|
- **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
|
|
97
|
-
- **Jobs,
|
|
98
|
-
- **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction: three tries, or `
|
|
97
|
+
- **Jobs, three ways.** Your Postgres or SQLite as the queue (`databaseQueue`, with `work()` as the worker on Node), Cloudflare Queues alone, or an outbox in front of a queue. All but in-process can run a job twice, so make them idempotent.
|
|
98
|
+
- **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction: three tries, or `database: { adapter, transactionAttempts }`.
|
|
99
99
|
- **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
|
|
100
100
|
- **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
|
|
101
101
|
- **Internal by default.** A function reaches clients only when you publish it: in your oRPC router or an agent's tools, which refuse one without `authorize`, or from your own route, which should only call functions that have one.
|
|
@@ -109,13 +109,12 @@ ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
|
|
|
109
109
|
|
|
110
110
|
| Import | |
|
|
111
111
|
|---|---|
|
|
112
|
-
| `logic-sdk/drizzle/pg` | The database adapter, `databaseQueue` and `
|
|
113
|
-
| `logic-sdk/postgres` | `databaseQueue` and `
|
|
112
|
+
| `logic-sdk/drizzle/pg` | The database adapter, `databaseQueue`, `outbox` and `failedJobs` |
|
|
113
|
+
| `logic-sdk/postgres` | `databaseQueue`, `outbox` and `failedJobs` on Postgres with any ORM |
|
|
114
114
|
| `logic-sdk/drizzle/sqlite` | The same on SQLite: `drizzleAdapter(() => drizzle("app.db"))` |
|
|
115
|
-
| `logic-sdk/sqlite` | `databaseQueue` and `
|
|
115
|
+
| `logic-sdk/sqlite` | `databaseQueue`, `outbox` and `failedJobs` on SQLite with any ORM |
|
|
116
116
|
| `logic-sdk/cloudflare` | Cloudflare Queues and Cron Triggers |
|
|
117
|
-
| `logic-sdk/
|
|
118
|
-
| `logic-sdk/node` | `startTicking`: crons and sweeps in a long-running process |
|
|
117
|
+
| `logic-sdk/node` | `work(registry)`: a worker for jobs and crons in a long-running process |
|
|
119
118
|
| `logic-sdk/fetch` | `toResponse`: a domain error as an HTTP response, for your own routes |
|
|
120
119
|
| `logic-sdk/orpc` | `toORPCProcedure`: a function as an oRPC v2 procedure, for your router |
|
|
121
120
|
| `logic-sdk/ai` | AI SDK tools: agents run your functions with the same rules |
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Job, JobsAdapter } from "../core/types.ts";
|
|
2
|
+
/** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
|
|
3
|
+
export interface QueueBinding {
|
|
4
|
+
sendBatch(messages: Iterable<{
|
|
5
|
+
body: Job;
|
|
6
|
+
delaySeconds?: number;
|
|
7
|
+
}>): Promise<unknown>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
|
|
11
|
+
* them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
|
|
12
|
+
* Run them with `handleQueue(registry, batch)` in your consumer. With `jobs.queues`, one binding per queue, `"default"`
|
|
13
|
+
* included: `cloudflareQueue({ default: env.JOBS, mail: env.MAIL })`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function cloudflareQueue(queue: QueueBinding | Readonly<Record<string, QueueBinding>>): JobsAdapter;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
|
|
2
|
+
const MAX_MESSAGES = 100;
|
|
3
|
+
const MAX_BATCH_BYTES = 256_000;
|
|
4
|
+
const MAX_MESSAGE_BYTES = 128_000;
|
|
5
|
+
/** Cloudflare counts about this much metadata per message toward the limits. */
|
|
6
|
+
const OVERHEAD_BYTES = 100;
|
|
7
|
+
/** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
|
|
8
|
+
const MAX_DELAY = 86_400;
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
/**
|
|
11
|
+
* Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
|
|
12
|
+
* them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
|
|
13
|
+
* Run them with `handleQueue(registry, batch)` in your consumer. With `jobs.queues`, one binding per queue, `"default"`
|
|
14
|
+
* included: `cloudflareQueue({ default: env.JOBS, mail: env.MAIL })`.
|
|
15
|
+
*/
|
|
16
|
+
export function cloudflareQueue(queue) {
|
|
17
|
+
const one = typeof queue.sendBatch === "function";
|
|
18
|
+
const bindings = (one ? { default: queue } : queue);
|
|
19
|
+
return {
|
|
20
|
+
name: one ? "cloudflareQueue(queue)" : `cloudflareQueue({ ${Object.keys(bindings).join(", ")} })`,
|
|
21
|
+
retries: true, // handleQueue retries a message with a backoff
|
|
22
|
+
holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
|
|
23
|
+
...(one ? {} : { queues: Object.keys(bindings) }),
|
|
24
|
+
async deliver(jobs) {
|
|
25
|
+
const byQueue = Map.groupBy(jobs, (job) => job.queue ?? "default");
|
|
26
|
+
for (const [name, some] of byQueue) {
|
|
27
|
+
const binding = bindings[name];
|
|
28
|
+
if (!binding)
|
|
29
|
+
throw new Error(`[logic-sdk] cloudflareQueue has no binding for queue ${JSON.stringify(name)}.`);
|
|
30
|
+
for (const batch of batches(some))
|
|
31
|
+
await binding.sendBatch(batch);
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
|
|
37
|
+
function* batches(jobs) {
|
|
38
|
+
const sized = jobs.map((body) => {
|
|
39
|
+
const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
|
|
40
|
+
if (size > MAX_MESSAGE_BYTES)
|
|
41
|
+
throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
|
|
42
|
+
return { body, size };
|
|
43
|
+
});
|
|
44
|
+
let batch = [];
|
|
45
|
+
let bytes = 0;
|
|
46
|
+
for (const { body, size } of sized) {
|
|
47
|
+
if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
|
|
48
|
+
yield batch;
|
|
49
|
+
batch = [];
|
|
50
|
+
bytes = 0;
|
|
51
|
+
}
|
|
52
|
+
batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
|
|
53
|
+
bytes += size;
|
|
54
|
+
}
|
|
55
|
+
if (batch.length)
|
|
56
|
+
yield batch;
|
|
57
|
+
}
|
|
58
|
+
const secondsUntil = (iso) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { type SQL } from "drizzle-orm";
|
|
2
|
+
import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
|
|
3
|
+
/** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
|
|
4
|
+
interface Transactional {
|
|
5
|
+
transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
|
|
6
|
+
execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
|
|
7
|
+
}
|
|
8
|
+
/** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
|
|
9
|
+
type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
10
|
+
/**
|
|
11
|
+
* What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
|
|
12
|
+
* events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
|
|
13
|
+
*/
|
|
14
|
+
export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
|
|
15
|
+
/** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
|
|
16
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView">;
|
|
17
|
+
/**
|
|
18
|
+
* Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
|
|
19
|
+
* the transaction.
|
|
20
|
+
*/
|
|
21
|
+
export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
|
|
22
|
+
/**
|
|
23
|
+
* Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
|
|
24
|
+
* PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
|
|
25
|
+
* The types reject SQLite and libsql databases here.
|
|
26
|
+
*/
|
|
27
|
+
export declare function drizzleAdapter<Db extends Transactional>(db: Db): SqlDatabase<Db, Transaction<Db>>;
|
|
28
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
29
|
+
export declare function sqlState(error: unknown): string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
|
|
32
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
|
|
33
|
+
* done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
34
|
+
*/
|
|
35
|
+
export declare const jobsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
36
|
+
name: "logic_jobs";
|
|
37
|
+
schema: undefined;
|
|
38
|
+
columns: {
|
|
39
|
+
id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
40
|
+
name: string;
|
|
41
|
+
tableName: "logic_jobs";
|
|
42
|
+
dataType: "string";
|
|
43
|
+
data: string;
|
|
44
|
+
driverParam: string;
|
|
45
|
+
notNull: true;
|
|
46
|
+
hasDefault: false;
|
|
47
|
+
isPrimaryKey: false;
|
|
48
|
+
isAutoincrement: false;
|
|
49
|
+
hasRuntimeDefault: false;
|
|
50
|
+
enumValues: undefined;
|
|
51
|
+
identity: undefined;
|
|
52
|
+
generated: undefined;
|
|
53
|
+
}>;
|
|
54
|
+
job: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgJsonbBuilder, Job>>, {
|
|
55
|
+
name: string;
|
|
56
|
+
tableName: "logic_jobs";
|
|
57
|
+
dataType: "object json";
|
|
58
|
+
data: Job;
|
|
59
|
+
driverParam: unknown;
|
|
60
|
+
notNull: true;
|
|
61
|
+
hasDefault: false;
|
|
62
|
+
isPrimaryKey: false;
|
|
63
|
+
isAutoincrement: false;
|
|
64
|
+
hasRuntimeDefault: false;
|
|
65
|
+
enumValues: undefined;
|
|
66
|
+
identity: undefined;
|
|
67
|
+
generated: undefined;
|
|
68
|
+
}>;
|
|
69
|
+
status: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, "failed" | "pending">>>, {
|
|
70
|
+
name: string;
|
|
71
|
+
tableName: "logic_jobs";
|
|
72
|
+
dataType: "string";
|
|
73
|
+
data: "failed" | "pending";
|
|
74
|
+
driverParam: string;
|
|
75
|
+
notNull: true;
|
|
76
|
+
hasDefault: true;
|
|
77
|
+
isPrimaryKey: false;
|
|
78
|
+
isAutoincrement: false;
|
|
79
|
+
hasRuntimeDefault: false;
|
|
80
|
+
enumValues: undefined;
|
|
81
|
+
identity: undefined;
|
|
82
|
+
generated: undefined;
|
|
83
|
+
}>;
|
|
84
|
+
attempts: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgIntegerBuilder>>, {
|
|
85
|
+
name: string;
|
|
86
|
+
tableName: "logic_jobs";
|
|
87
|
+
dataType: "number int32";
|
|
88
|
+
data: number;
|
|
89
|
+
driverParam: string | number;
|
|
90
|
+
notNull: true;
|
|
91
|
+
hasDefault: true;
|
|
92
|
+
isPrimaryKey: false;
|
|
93
|
+
isAutoincrement: false;
|
|
94
|
+
hasRuntimeDefault: false;
|
|
95
|
+
enumValues: undefined;
|
|
96
|
+
identity: undefined;
|
|
97
|
+
generated: undefined;
|
|
98
|
+
}>;
|
|
99
|
+
availableAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
|
|
100
|
+
name: string;
|
|
101
|
+
tableName: "logic_jobs";
|
|
102
|
+
dataType: "object date";
|
|
103
|
+
data: Date;
|
|
104
|
+
driverParam: string;
|
|
105
|
+
notNull: true;
|
|
106
|
+
hasDefault: true;
|
|
107
|
+
isPrimaryKey: false;
|
|
108
|
+
isAutoincrement: false;
|
|
109
|
+
hasRuntimeDefault: false;
|
|
110
|
+
enumValues: undefined;
|
|
111
|
+
identity: undefined;
|
|
112
|
+
generated: undefined;
|
|
113
|
+
}>;
|
|
114
|
+
receipt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
115
|
+
name: string;
|
|
116
|
+
tableName: "logic_jobs";
|
|
117
|
+
dataType: "string";
|
|
118
|
+
data: string;
|
|
119
|
+
driverParam: string;
|
|
120
|
+
notNull: false;
|
|
121
|
+
hasDefault: false;
|
|
122
|
+
isPrimaryKey: false;
|
|
123
|
+
isAutoincrement: false;
|
|
124
|
+
hasRuntimeDefault: false;
|
|
125
|
+
enumValues: undefined;
|
|
126
|
+
identity: undefined;
|
|
127
|
+
generated: undefined;
|
|
128
|
+
}>;
|
|
129
|
+
claimedAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTimestampBuilder, {
|
|
130
|
+
name: string;
|
|
131
|
+
tableName: "logic_jobs";
|
|
132
|
+
dataType: "object date";
|
|
133
|
+
data: Date;
|
|
134
|
+
driverParam: string;
|
|
135
|
+
notNull: false;
|
|
136
|
+
hasDefault: false;
|
|
137
|
+
isPrimaryKey: false;
|
|
138
|
+
isAutoincrement: false;
|
|
139
|
+
hasRuntimeDefault: false;
|
|
140
|
+
enumValues: undefined;
|
|
141
|
+
identity: undefined;
|
|
142
|
+
generated: undefined;
|
|
143
|
+
}>;
|
|
144
|
+
lastError: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
145
|
+
name: string;
|
|
146
|
+
tableName: "logic_jobs";
|
|
147
|
+
dataType: "string";
|
|
148
|
+
data: string;
|
|
149
|
+
driverParam: string;
|
|
150
|
+
notNull: false;
|
|
151
|
+
hasDefault: false;
|
|
152
|
+
isPrimaryKey: false;
|
|
153
|
+
isAutoincrement: false;
|
|
154
|
+
hasRuntimeDefault: false;
|
|
155
|
+
enumValues: undefined;
|
|
156
|
+
identity: undefined;
|
|
157
|
+
generated: undefined;
|
|
158
|
+
}>;
|
|
159
|
+
failedAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTimestampBuilder, {
|
|
160
|
+
name: string;
|
|
161
|
+
tableName: "logic_jobs";
|
|
162
|
+
dataType: "object date";
|
|
163
|
+
data: Date;
|
|
164
|
+
driverParam: string;
|
|
165
|
+
notNull: false;
|
|
166
|
+
hasDefault: false;
|
|
167
|
+
isPrimaryKey: false;
|
|
168
|
+
isAutoincrement: false;
|
|
169
|
+
hasRuntimeDefault: false;
|
|
170
|
+
enumValues: undefined;
|
|
171
|
+
identity: undefined;
|
|
172
|
+
generated: undefined;
|
|
173
|
+
}>;
|
|
174
|
+
uniqueKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
175
|
+
name: string;
|
|
176
|
+
tableName: "logic_jobs";
|
|
177
|
+
dataType: "string";
|
|
178
|
+
data: string;
|
|
179
|
+
driverParam: string;
|
|
180
|
+
notNull: false;
|
|
181
|
+
hasDefault: false;
|
|
182
|
+
isPrimaryKey: false;
|
|
183
|
+
isAutoincrement: false;
|
|
184
|
+
hasRuntimeDefault: false;
|
|
185
|
+
enumValues: undefined;
|
|
186
|
+
identity: undefined;
|
|
187
|
+
generated: undefined;
|
|
188
|
+
}>;
|
|
189
|
+
orderKey: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
|
|
190
|
+
name: string;
|
|
191
|
+
tableName: "logic_jobs";
|
|
192
|
+
dataType: "string";
|
|
193
|
+
data: string;
|
|
194
|
+
driverParam: string;
|
|
195
|
+
notNull: false;
|
|
196
|
+
hasDefault: false;
|
|
197
|
+
isPrimaryKey: false;
|
|
198
|
+
isAutoincrement: false;
|
|
199
|
+
hasRuntimeDefault: false;
|
|
200
|
+
enumValues: undefined;
|
|
201
|
+
identity: undefined;
|
|
202
|
+
generated: undefined;
|
|
203
|
+
}>;
|
|
204
|
+
seq: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgBigSerial53Builder>, {
|
|
205
|
+
name: string;
|
|
206
|
+
tableName: "logic_jobs";
|
|
207
|
+
dataType: "number int53";
|
|
208
|
+
data: number;
|
|
209
|
+
driverParam: number;
|
|
210
|
+
notNull: true;
|
|
211
|
+
hasDefault: true;
|
|
212
|
+
isPrimaryKey: false;
|
|
213
|
+
isAutoincrement: false;
|
|
214
|
+
hasRuntimeDefault: false;
|
|
215
|
+
enumValues: undefined;
|
|
216
|
+
identity: undefined;
|
|
217
|
+
generated: undefined;
|
|
218
|
+
}>;
|
|
219
|
+
createdAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_jobs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
|
|
220
|
+
name: string;
|
|
221
|
+
tableName: "logic_jobs";
|
|
222
|
+
dataType: "object date";
|
|
223
|
+
data: Date;
|
|
224
|
+
driverParam: string;
|
|
225
|
+
notNull: true;
|
|
226
|
+
hasDefault: true;
|
|
227
|
+
isPrimaryKey: false;
|
|
228
|
+
isAutoincrement: false;
|
|
229
|
+
hasRuntimeDefault: false;
|
|
230
|
+
enumValues: undefined;
|
|
231
|
+
identity: undefined;
|
|
232
|
+
generated: undefined;
|
|
233
|
+
}>;
|
|
234
|
+
};
|
|
235
|
+
dialect: 'pg';
|
|
236
|
+
isAlias: false;
|
|
237
|
+
}>;
|
|
238
|
+
/**
|
|
239
|
+
* The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
|
|
240
|
+
* Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
|
|
241
|
+
*/
|
|
242
|
+
export declare const cronRunsTable: import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
243
|
+
name: "logic_cron_runs";
|
|
244
|
+
schema: undefined;
|
|
245
|
+
columns: {
|
|
246
|
+
id: import("drizzle-orm/pg-core").PgBuildColumn<"logic_cron_runs", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
247
|
+
name: string;
|
|
248
|
+
tableName: "logic_cron_runs";
|
|
249
|
+
dataType: "string";
|
|
250
|
+
data: string;
|
|
251
|
+
driverParam: string;
|
|
252
|
+
notNull: true;
|
|
253
|
+
hasDefault: false;
|
|
254
|
+
isPrimaryKey: false;
|
|
255
|
+
isAutoincrement: false;
|
|
256
|
+
hasRuntimeDefault: false;
|
|
257
|
+
enumValues: undefined;
|
|
258
|
+
identity: undefined;
|
|
259
|
+
generated: undefined;
|
|
260
|
+
}>;
|
|
261
|
+
ranAt: import("drizzle-orm/pg-core").PgBuildColumn<"logic_cron_runs", import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>, {
|
|
262
|
+
name: string;
|
|
263
|
+
tableName: "logic_cron_runs";
|
|
264
|
+
dataType: "object date";
|
|
265
|
+
data: Date;
|
|
266
|
+
driverParam: string;
|
|
267
|
+
notNull: true;
|
|
268
|
+
hasDefault: true;
|
|
269
|
+
isPrimaryKey: false;
|
|
270
|
+
isAutoincrement: false;
|
|
271
|
+
hasRuntimeDefault: false;
|
|
272
|
+
enumValues: undefined;
|
|
273
|
+
identity: undefined;
|
|
274
|
+
generated: undefined;
|
|
275
|
+
}>;
|
|
276
|
+
};
|
|
277
|
+
dialect: 'pg';
|
|
278
|
+
isAlias: false;
|
|
279
|
+
}>;
|
|
280
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { bigserial, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3
|
+
import { causes } from "../core/errors.js";
|
|
4
|
+
/**
|
|
5
|
+
* Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
|
|
6
|
+
* PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
|
|
7
|
+
* The types reject SQLite and libsql databases here.
|
|
8
|
+
*/
|
|
9
|
+
export function drizzleAdapter(db) {
|
|
10
|
+
return {
|
|
11
|
+
db,
|
|
12
|
+
transaction: (fn) => db.transaction(fn),
|
|
13
|
+
nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
|
|
14
|
+
retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
|
|
15
|
+
query: async (client, text, params) => client.execute(toSql(text, params), "objects"),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
|
|
19
|
+
const toSql = (text, params) => sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
|
|
20
|
+
/** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
|
|
21
|
+
const RETRYABLE = new Set(["40001", "40P01"]);
|
|
22
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
23
|
+
export function sqlState(error) {
|
|
24
|
+
for (const e of causes(error))
|
|
25
|
+
if ("code" in e && typeof e.code === "string")
|
|
26
|
+
return e.code;
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
|
|
31
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
|
|
32
|
+
* done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
33
|
+
*/
|
|
34
|
+
export const jobsTable = pgTable("logic_jobs", {
|
|
35
|
+
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
36
|
+
id: text("id").primaryKey(),
|
|
37
|
+
job: jsonb("job").$type().notNull(),
|
|
38
|
+
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
39
|
+
status: text("status").$type().notNull().default("pending"),
|
|
40
|
+
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
41
|
+
attempts: integer("attempts").notNull().default(0),
|
|
42
|
+
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
43
|
+
availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
|
|
44
|
+
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
45
|
+
receipt: text("receipt"),
|
|
46
|
+
/** When the claim that owns it started: set while a try runs, empty while it waits (first, or after a backoff). */
|
|
47
|
+
claimedAt: timestamp("claimed_at", { withTimezone: true }),
|
|
48
|
+
/** The last failure, with its stack. */
|
|
49
|
+
lastError: text("last_error"),
|
|
50
|
+
failedAt: timestamp("failed_at", { withTimezone: true }),
|
|
51
|
+
/**
|
|
52
|
+
* One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
|
|
53
|
+
* call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
|
|
54
|
+
*/
|
|
55
|
+
uniqueKey: text("unique_key"),
|
|
56
|
+
/** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, by `seq`. */
|
|
57
|
+
orderKey: text("order_key"),
|
|
58
|
+
/** The insert order, for `orderKey`. */
|
|
59
|
+
seq: bigserial("seq", { mode: "number" }).notNull(),
|
|
60
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
61
|
+
}, (t) => [
|
|
62
|
+
index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
|
|
63
|
+
// one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
64
|
+
uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql `status = 'pending' and attempts = 0`),
|
|
65
|
+
// a key's open rows, for the first of each
|
|
66
|
+
index("logic_jobs_order").on(t.orderKey, t.seq).where(sql `status = 'pending'`),
|
|
67
|
+
// `registry.jobs.failed()` pages newest first by (failed_at, id)
|
|
68
|
+
index("logic_jobs_failed").on(t.failedAt, t.id).where(sql `status = 'failed'`),
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
|
|
72
|
+
* Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
|
|
73
|
+
*/
|
|
74
|
+
export const cronRunsTable = pgTable("logic_cron_runs", {
|
|
75
|
+
/** The cron job's id, `<cron id>@<minute>`. */
|
|
76
|
+
id: text("id").primaryKey(),
|
|
77
|
+
ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
|
|
78
|
+
}, (t) => [index("logic_cron_runs_ran_at").on(t.ranAt)]);
|