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
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { type SQL } from "drizzle-orm";
|
|
2
|
+
import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
|
|
3
|
+
/** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
|
|
4
|
+
interface SyncSqlite {
|
|
5
|
+
all<T>(query: SQL): T[];
|
|
6
|
+
run(query: SQL): unknown;
|
|
7
|
+
$client: {
|
|
8
|
+
close(): unknown;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/** What mutations get: a connection of their own, inside the transaction the adapter opened. */
|
|
12
|
+
export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
|
|
13
|
+
/** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
|
|
14
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
|
|
15
|
+
/** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
|
|
16
|
+
export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
17
|
+
/**
|
|
18
|
+
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
19
|
+
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
20
|
+
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function drizzleAdapter<Db extends SyncSqlite>(open: () => Db): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>>;
|
|
27
|
+
/**
|
|
28
|
+
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
29
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
30
|
+
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
31
|
+
*/
|
|
32
|
+
export declare const jobsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
33
|
+
name: "logic_jobs";
|
|
34
|
+
schema: undefined;
|
|
35
|
+
columns: {
|
|
36
|
+
id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
37
|
+
name: string;
|
|
38
|
+
tableName: "logic_jobs";
|
|
39
|
+
dataType: "string";
|
|
40
|
+
data: string;
|
|
41
|
+
driverParam: string;
|
|
42
|
+
notNull: true;
|
|
43
|
+
hasDefault: false;
|
|
44
|
+
isPrimaryKey: true;
|
|
45
|
+
isAutoincrement: false;
|
|
46
|
+
hasRuntimeDefault: false;
|
|
47
|
+
enumValues: [string, ...string[]];
|
|
48
|
+
baseColumn: never;
|
|
49
|
+
identity: undefined;
|
|
50
|
+
generated: undefined;
|
|
51
|
+
}, {}>;
|
|
52
|
+
job: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
53
|
+
name: string;
|
|
54
|
+
tableName: "logic_jobs";
|
|
55
|
+
dataType: "object json";
|
|
56
|
+
data: Job;
|
|
57
|
+
driverParam: string;
|
|
58
|
+
notNull: true;
|
|
59
|
+
hasDefault: false;
|
|
60
|
+
isPrimaryKey: false;
|
|
61
|
+
isAutoincrement: false;
|
|
62
|
+
hasRuntimeDefault: false;
|
|
63
|
+
enumValues: undefined;
|
|
64
|
+
baseColumn: never;
|
|
65
|
+
identity: undefined;
|
|
66
|
+
generated: undefined;
|
|
67
|
+
}, {}>;
|
|
68
|
+
status: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
69
|
+
name: string;
|
|
70
|
+
tableName: "logic_jobs";
|
|
71
|
+
dataType: "string";
|
|
72
|
+
data: "failed" | "pending";
|
|
73
|
+
driverParam: string;
|
|
74
|
+
notNull: true;
|
|
75
|
+
hasDefault: true;
|
|
76
|
+
isPrimaryKey: false;
|
|
77
|
+
isAutoincrement: false;
|
|
78
|
+
hasRuntimeDefault: false;
|
|
79
|
+
enumValues: [string, ...string[]];
|
|
80
|
+
baseColumn: never;
|
|
81
|
+
identity: undefined;
|
|
82
|
+
generated: undefined;
|
|
83
|
+
}, {}>;
|
|
84
|
+
attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
85
|
+
name: string;
|
|
86
|
+
tableName: "logic_jobs";
|
|
87
|
+
dataType: "number int53";
|
|
88
|
+
data: number;
|
|
89
|
+
driverParam: number;
|
|
90
|
+
notNull: true;
|
|
91
|
+
hasDefault: true;
|
|
92
|
+
isPrimaryKey: false;
|
|
93
|
+
isAutoincrement: false;
|
|
94
|
+
hasRuntimeDefault: false;
|
|
95
|
+
enumValues: undefined;
|
|
96
|
+
baseColumn: never;
|
|
97
|
+
identity: undefined;
|
|
98
|
+
generated: undefined;
|
|
99
|
+
}, {}>;
|
|
100
|
+
availableAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
101
|
+
name: string;
|
|
102
|
+
tableName: "logic_jobs";
|
|
103
|
+
dataType: "object date";
|
|
104
|
+
data: Date;
|
|
105
|
+
driverParam: number;
|
|
106
|
+
notNull: true;
|
|
107
|
+
hasDefault: true;
|
|
108
|
+
isPrimaryKey: false;
|
|
109
|
+
isAutoincrement: false;
|
|
110
|
+
hasRuntimeDefault: false;
|
|
111
|
+
enumValues: undefined;
|
|
112
|
+
baseColumn: never;
|
|
113
|
+
identity: undefined;
|
|
114
|
+
generated: undefined;
|
|
115
|
+
}, {}>;
|
|
116
|
+
receipt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
117
|
+
name: string;
|
|
118
|
+
tableName: "logic_jobs";
|
|
119
|
+
dataType: "string";
|
|
120
|
+
data: string;
|
|
121
|
+
driverParam: string;
|
|
122
|
+
notNull: false;
|
|
123
|
+
hasDefault: false;
|
|
124
|
+
isPrimaryKey: false;
|
|
125
|
+
isAutoincrement: false;
|
|
126
|
+
hasRuntimeDefault: false;
|
|
127
|
+
enumValues: [string, ...string[]];
|
|
128
|
+
baseColumn: never;
|
|
129
|
+
identity: undefined;
|
|
130
|
+
generated: undefined;
|
|
131
|
+
}, {}>;
|
|
132
|
+
claimedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
133
|
+
name: string;
|
|
134
|
+
tableName: "logic_jobs";
|
|
135
|
+
dataType: "object date";
|
|
136
|
+
data: Date;
|
|
137
|
+
driverParam: number;
|
|
138
|
+
notNull: false;
|
|
139
|
+
hasDefault: false;
|
|
140
|
+
isPrimaryKey: false;
|
|
141
|
+
isAutoincrement: false;
|
|
142
|
+
hasRuntimeDefault: false;
|
|
143
|
+
enumValues: undefined;
|
|
144
|
+
baseColumn: never;
|
|
145
|
+
identity: undefined;
|
|
146
|
+
generated: undefined;
|
|
147
|
+
}, {}>;
|
|
148
|
+
lastError: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
149
|
+
name: string;
|
|
150
|
+
tableName: "logic_jobs";
|
|
151
|
+
dataType: "string";
|
|
152
|
+
data: string;
|
|
153
|
+
driverParam: string;
|
|
154
|
+
notNull: false;
|
|
155
|
+
hasDefault: false;
|
|
156
|
+
isPrimaryKey: false;
|
|
157
|
+
isAutoincrement: false;
|
|
158
|
+
hasRuntimeDefault: false;
|
|
159
|
+
enumValues: [string, ...string[]];
|
|
160
|
+
baseColumn: never;
|
|
161
|
+
identity: undefined;
|
|
162
|
+
generated: undefined;
|
|
163
|
+
}, {}>;
|
|
164
|
+
failedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
165
|
+
name: string;
|
|
166
|
+
tableName: "logic_jobs";
|
|
167
|
+
dataType: "object date";
|
|
168
|
+
data: Date;
|
|
169
|
+
driverParam: number;
|
|
170
|
+
notNull: false;
|
|
171
|
+
hasDefault: false;
|
|
172
|
+
isPrimaryKey: false;
|
|
173
|
+
isAutoincrement: false;
|
|
174
|
+
hasRuntimeDefault: false;
|
|
175
|
+
enumValues: undefined;
|
|
176
|
+
baseColumn: never;
|
|
177
|
+
identity: undefined;
|
|
178
|
+
generated: undefined;
|
|
179
|
+
}, {}>;
|
|
180
|
+
uniqueKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
181
|
+
name: string;
|
|
182
|
+
tableName: "logic_jobs";
|
|
183
|
+
dataType: "string";
|
|
184
|
+
data: string;
|
|
185
|
+
driverParam: string;
|
|
186
|
+
notNull: false;
|
|
187
|
+
hasDefault: false;
|
|
188
|
+
isPrimaryKey: false;
|
|
189
|
+
isAutoincrement: false;
|
|
190
|
+
hasRuntimeDefault: false;
|
|
191
|
+
enumValues: [string, ...string[]];
|
|
192
|
+
baseColumn: never;
|
|
193
|
+
identity: undefined;
|
|
194
|
+
generated: undefined;
|
|
195
|
+
}, {}>;
|
|
196
|
+
orderKey: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
197
|
+
name: string;
|
|
198
|
+
tableName: "logic_jobs";
|
|
199
|
+
dataType: "string";
|
|
200
|
+
data: string;
|
|
201
|
+
driverParam: string;
|
|
202
|
+
notNull: false;
|
|
203
|
+
hasDefault: false;
|
|
204
|
+
isPrimaryKey: false;
|
|
205
|
+
isAutoincrement: false;
|
|
206
|
+
hasRuntimeDefault: false;
|
|
207
|
+
enumValues: [string, ...string[]];
|
|
208
|
+
baseColumn: never;
|
|
209
|
+
identity: undefined;
|
|
210
|
+
generated: undefined;
|
|
211
|
+
}, {}>;
|
|
212
|
+
createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
213
|
+
name: string;
|
|
214
|
+
tableName: "logic_jobs";
|
|
215
|
+
dataType: "object date";
|
|
216
|
+
data: Date;
|
|
217
|
+
driverParam: number;
|
|
218
|
+
notNull: true;
|
|
219
|
+
hasDefault: true;
|
|
220
|
+
isPrimaryKey: false;
|
|
221
|
+
isAutoincrement: false;
|
|
222
|
+
hasRuntimeDefault: false;
|
|
223
|
+
enumValues: undefined;
|
|
224
|
+
baseColumn: never;
|
|
225
|
+
identity: undefined;
|
|
226
|
+
generated: undefined;
|
|
227
|
+
}, {}>;
|
|
228
|
+
};
|
|
229
|
+
dialect: 'sqlite';
|
|
230
|
+
isAlias: false;
|
|
231
|
+
}>;
|
|
232
|
+
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
233
|
+
export declare const cronRunsTable: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
|
|
234
|
+
name: "logic_cron_runs";
|
|
235
|
+
schema: undefined;
|
|
236
|
+
columns: {
|
|
237
|
+
id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
238
|
+
name: string;
|
|
239
|
+
tableName: "logic_cron_runs";
|
|
240
|
+
dataType: "string";
|
|
241
|
+
data: string;
|
|
242
|
+
driverParam: string;
|
|
243
|
+
notNull: true;
|
|
244
|
+
hasDefault: false;
|
|
245
|
+
isPrimaryKey: true;
|
|
246
|
+
isAutoincrement: false;
|
|
247
|
+
hasRuntimeDefault: false;
|
|
248
|
+
enumValues: [string, ...string[]];
|
|
249
|
+
baseColumn: never;
|
|
250
|
+
identity: undefined;
|
|
251
|
+
generated: undefined;
|
|
252
|
+
}, {}>;
|
|
253
|
+
ranAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
254
|
+
name: string;
|
|
255
|
+
tableName: "logic_cron_runs";
|
|
256
|
+
dataType: "object date";
|
|
257
|
+
data: Date;
|
|
258
|
+
driverParam: number;
|
|
259
|
+
notNull: true;
|
|
260
|
+
hasDefault: true;
|
|
261
|
+
isPrimaryKey: false;
|
|
262
|
+
isAutoincrement: false;
|
|
263
|
+
hasRuntimeDefault: false;
|
|
264
|
+
enumValues: undefined;
|
|
265
|
+
baseColumn: never;
|
|
266
|
+
identity: undefined;
|
|
267
|
+
generated: undefined;
|
|
268
|
+
}, {}>;
|
|
269
|
+
};
|
|
270
|
+
dialect: 'sqlite';
|
|
271
|
+
isAlias: false;
|
|
272
|
+
}>;
|
|
273
|
+
export {};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import { causes } from "../core/errors.js";
|
|
4
|
+
/** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
|
|
5
|
+
const BUSY_TIMEOUT = 5000;
|
|
6
|
+
/**
|
|
7
|
+
* Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
|
|
8
|
+
* `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
|
|
9
|
+
* ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* const database = drizzleAdapter(() => drizzle("app.db"));
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export function drizzleAdapter(open) {
|
|
16
|
+
const reader = open();
|
|
17
|
+
checkOpen(open, reader);
|
|
18
|
+
exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
|
|
19
|
+
exec(reader, "PRAGMA query_only = ON");
|
|
20
|
+
const takeTurn = turns();
|
|
21
|
+
const transaction = (fn) => takeTurn(async (restartClock) => {
|
|
22
|
+
const tx = await begin(open, restartClock);
|
|
23
|
+
try {
|
|
24
|
+
const out = await fn(tx);
|
|
25
|
+
exec(tx, "COMMIT");
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
undo(tx, "ROLLBACK");
|
|
30
|
+
throw e;
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
tx.$client.close();
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
return {
|
|
37
|
+
db: reader,
|
|
38
|
+
transaction,
|
|
39
|
+
nest: (tx) => savepoints(tx),
|
|
40
|
+
retryable: isBusy,
|
|
41
|
+
// on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
|
|
42
|
+
query: async (client, text, params) => client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Transactions inside a transaction, as savepoints: the test registry's. */
|
|
46
|
+
function savepoints(tx) {
|
|
47
|
+
const takeTurn = turns();
|
|
48
|
+
return {
|
|
49
|
+
db: tx,
|
|
50
|
+
transaction: (fn) => takeTurn(async () => {
|
|
51
|
+
exec(tx, "SAVEPOINT logic_sdk");
|
|
52
|
+
try {
|
|
53
|
+
const out = await fn(tx);
|
|
54
|
+
exec(tx, "RELEASE logic_sdk");
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
|
|
59
|
+
throw e;
|
|
60
|
+
}
|
|
61
|
+
}),
|
|
62
|
+
nest: savepoints,
|
|
63
|
+
query: async (client, text, params) => rowsOf(client, text, params),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const exec = (db, text) => db.run(sql.raw(text));
|
|
67
|
+
/** SQL text with `?` parameters as a Drizzle query. */
|
|
68
|
+
const toSql = (text, params) => sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
|
|
69
|
+
const rowsOf = (db, text, params) => db.all(toSql(text, params));
|
|
70
|
+
/** 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. */
|
|
71
|
+
function undo(db, ...statements) {
|
|
72
|
+
try {
|
|
73
|
+
for (const statement of statements)
|
|
74
|
+
exec(db, statement);
|
|
75
|
+
}
|
|
76
|
+
catch { }
|
|
77
|
+
}
|
|
78
|
+
/** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
|
|
79
|
+
function checkOpen(open, reader) {
|
|
80
|
+
const another = open();
|
|
81
|
+
if (another.$client === reader.$client)
|
|
82
|
+
throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
|
|
83
|
+
const [main] = another.all(sql `PRAGMA database_list`);
|
|
84
|
+
another.$client.close();
|
|
85
|
+
if (!main?.file)
|
|
86
|
+
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.");
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
|
|
90
|
+
* since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
|
|
91
|
+
*/
|
|
92
|
+
async function begin(open, restartClock) {
|
|
93
|
+
const deadline = Date.now() + BUSY_TIMEOUT;
|
|
94
|
+
for (;;) {
|
|
95
|
+
restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
|
|
96
|
+
let tx;
|
|
97
|
+
try {
|
|
98
|
+
tx = open();
|
|
99
|
+
exec(tx, "PRAGMA busy_timeout = 0");
|
|
100
|
+
exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
|
|
101
|
+
exec(tx, "BEGIN IMMEDIATE");
|
|
102
|
+
return tx;
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
tx?.$client.close();
|
|
106
|
+
if (!isBusy(e) || Date.now() >= deadline)
|
|
107
|
+
throw e;
|
|
108
|
+
}
|
|
109
|
+
await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
|
|
114
|
+
* when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
|
|
115
|
+
*/
|
|
116
|
+
function turns() {
|
|
117
|
+
let last = Promise.resolve();
|
|
118
|
+
let startedAt = 0;
|
|
119
|
+
const restartClock = () => {
|
|
120
|
+
startedAt = Date.now();
|
|
121
|
+
};
|
|
122
|
+
return async (work) => {
|
|
123
|
+
const arrived = Date.now();
|
|
124
|
+
const ahead = last;
|
|
125
|
+
const done = Promise.withResolvers();
|
|
126
|
+
last = ahead.then(() => done.promise);
|
|
127
|
+
try {
|
|
128
|
+
const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
|
|
129
|
+
while (!(await settlesBy(ahead, giveUpAt()))) {
|
|
130
|
+
// the one ahead may have changed while we waited: the line moved
|
|
131
|
+
if (Date.now() >= giveUpAt())
|
|
132
|
+
throw new Error(HELD);
|
|
133
|
+
}
|
|
134
|
+
restartClock();
|
|
135
|
+
return await work(restartClock);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
done.resolve();
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
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?";
|
|
143
|
+
/** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
|
|
144
|
+
const settlesBy = (promise, time) => new Promise((resolve) => {
|
|
145
|
+
const timer = setTimeout(() => resolve(false), time - Date.now());
|
|
146
|
+
void promise.then(() => {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
resolve(true);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
/** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
|
|
152
|
+
function isBusy(error) {
|
|
153
|
+
for (const e of causes(error))
|
|
154
|
+
if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message)))
|
|
155
|
+
return true;
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
const now = sql `(cast(unixepoch('subsec') * 1000 as integer))`;
|
|
159
|
+
/**
|
|
160
|
+
* The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
|
|
161
|
+
* drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
|
|
162
|
+
* job; done rows are deleted, failed ones stay so you can query them and `retry` them.
|
|
163
|
+
*/
|
|
164
|
+
export const jobsTable = sqliteTable("logic_jobs", {
|
|
165
|
+
/** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
|
|
166
|
+
id: text("id").primaryKey(),
|
|
167
|
+
job: text("job", { mode: "json" }).$type().notNull(),
|
|
168
|
+
/** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
|
|
169
|
+
status: text("status").$type().notNull().default("pending"),
|
|
170
|
+
/** Incremented when a runner claims it, so a crash still uses an attempt. */
|
|
171
|
+
attempts: integer("attempts").notNull().default(0),
|
|
172
|
+
/** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
|
|
173
|
+
availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
174
|
+
/** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
|
|
175
|
+
receipt: text("receipt"),
|
|
176
|
+
/** When the claim that owns it started: set while a try runs, empty while it waits (first, or after a backoff). */
|
|
177
|
+
claimedAt: integer("claimed_at", { mode: "timestamp_ms" }),
|
|
178
|
+
/** The last failure, with its stack. */
|
|
179
|
+
lastError: text("last_error"),
|
|
180
|
+
failedAt: integer("failed_at", { mode: "timestamp_ms" }),
|
|
181
|
+
/**
|
|
182
|
+
* One waiting row per key: a scheduled call's `replace` key (`<function id>@<sha-256 of its input>`), which a newer
|
|
183
|
+
* call replaces, or a listener's `unique` value (`<listener id>@<value>`), which drops later ones.
|
|
184
|
+
*/
|
|
185
|
+
uniqueKey: text("unique_key"),
|
|
186
|
+
/** Its listener's `key`, `<listener id>@<key>`: rows with the same one run one at a time, in insert order (`rowid`). */
|
|
187
|
+
orderKey: text("order_key"),
|
|
188
|
+
createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
189
|
+
}, (t) => [
|
|
190
|
+
index("logic_jobs_due").on(t.availableAt).where(sql `${t.status} = 'pending'`),
|
|
191
|
+
// one waiting row per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
|
|
192
|
+
uniqueIndex("logic_jobs_unique").on(t.uniqueKey).where(sql `status = 'pending' and attempts = 0`),
|
|
193
|
+
// a key's open rows, for the first of each
|
|
194
|
+
index("logic_jobs_order").on(t.orderKey).where(sql `status = 'pending'`),
|
|
195
|
+
// `registry.jobs.failed()` pages newest first by (failed_at, id)
|
|
196
|
+
index("logic_jobs_failed").on(t.failedAt, t.id).where(sql `status = 'failed'`),
|
|
197
|
+
]);
|
|
198
|
+
/** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
|
|
199
|
+
export const cronRunsTable = sqliteTable("logic_cron_runs", {
|
|
200
|
+
/** The cron job's id, `<cron id>@<minute>`. */
|
|
201
|
+
id: text("id").primaryKey(),
|
|
202
|
+
ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
|
|
203
|
+
}, (t) => [index("logic_cron_runs_ran_at").on(t.ranAt)]);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
3
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
4
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY,\n job jsonb NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at timestamptz NOT NULL DEFAULT now(),\n receipt text,\n claimed_at timestamptz,\n last_error text,\n failed_at timestamptz,\n unique_key text,\n order_key text,\n seq bigserial NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_order ON logic_jobs (order_key, seq) WHERE status = 'pending';\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
|
|
5
|
+
/**
|
|
6
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
7
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
8
|
+
* is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
|
|
9
|
+
* behind. With `runIn: "worker"`, requests only write rows and workers in other processes run them. At least once: a crash between a job finishing and its row being deleted runs it again.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
13
|
+
* work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
|
|
17
|
+
/**
|
|
18
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, and stay
|
|
19
|
+
* rows until they're done: the queue gets a signal per job (per key, for a listener's `key`), and the consumer that gets
|
|
20
|
+
* one runs the row from the table and records how it went there. So tries, failed rows and a key's order are the
|
|
21
|
+
* table's, as with `databaseQueue`. A failed try gets a new signal for when its backoff ends; what no signal covers, the
|
|
22
|
+
* sweep runs 30 seconds past due. At least once: a consumer that dies after the work leaves the row to run again.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare const outbox: (queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
29
|
+
/**
|
|
30
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
31
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
32
|
+
*/
|
|
33
|
+
export declare const failedJobs: () => FailedJobs;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// The jobs table on Postgres, in SQL. With Drizzle, import from `logic-sdk/drizzle/pg` instead: the same two
|
|
2
|
+
// functions, plus the table for your schema.
|
|
3
|
+
import { failedStore, storedJobs } from "./stored-jobs.js";
|
|
4
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
+
export const jobsSchema = `
|
|
6
|
+
CREATE TABLE logic_jobs (
|
|
7
|
+
id text PRIMARY KEY,
|
|
8
|
+
job jsonb NOT NULL,
|
|
9
|
+
status text NOT NULL DEFAULT 'pending',
|
|
10
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
11
|
+
available_at timestamptz NOT NULL DEFAULT now(),
|
|
12
|
+
receipt text,
|
|
13
|
+
claimed_at timestamptz,
|
|
14
|
+
last_error text,
|
|
15
|
+
failed_at timestamptz,
|
|
16
|
+
unique_key text,
|
|
17
|
+
order_key text,
|
|
18
|
+
seq bigserial NOT NULL,
|
|
19
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
20
|
+
);
|
|
21
|
+
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
22
|
+
CREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;
|
|
23
|
+
CREATE INDEX logic_jobs_order ON logic_jobs (order_key, seq) WHERE status = 'pending';
|
|
24
|
+
CREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';
|
|
25
|
+
CREATE TABLE logic_cron_runs (
|
|
26
|
+
id text PRIMARY KEY,
|
|
27
|
+
ran_at timestamptz NOT NULL DEFAULT now()
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);
|
|
30
|
+
`;
|
|
31
|
+
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
32
|
+
const mine = (n) => `id = $${n} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
33
|
+
const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
|
|
34
|
+
/**
|
|
35
|
+
* A row may run when it has started already (one per key: a retry backing off), or when no other open row of its key
|
|
36
|
+
* started or came before it (`seq`, the insert order). A failed row put back by `retry(id)` waits behind one that started.
|
|
37
|
+
*/
|
|
38
|
+
const firstOfKey = `(order_key IS NULL OR attempts > 0 OR NOT EXISTS (
|
|
39
|
+
SELECT 1 FROM logic_jobs o WHERE o.order_key = logic_jobs.order_key AND o.status = 'pending' AND o.id <> logic_jobs.id AND (o.seq < logic_jobs.seq OR o.attempts > 0)))`;
|
|
40
|
+
const statements = {
|
|
41
|
+
// a waiting row with this key: a call replaces it (its id, job and time: Oban's `replace`), a unique delivery is
|
|
42
|
+
// dropped. Postgres locks the row either way, so it can't start before this transaction ends and miss its change
|
|
43
|
+
insert: `
|
|
44
|
+
INSERT INTO logic_jobs (id, job, available_at, unique_key, order_key)
|
|
45
|
+
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'unique', r->>'order'
|
|
46
|
+
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
47
|
+
ON CONFLICT (unique_key) WHERE status = 'pending' and attempts = 0
|
|
48
|
+
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
49
|
+
WHERE excluded.job->>'kind' = 'call'`,
|
|
50
|
+
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
51
|
+
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
52
|
+
claimNew: `
|
|
53
|
+
UPDATE logic_jobs SET attempts = 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
54
|
+
WHERE id = $3 AND attempts = 0 AND status = 'pending' AND ${firstOfKey} RETURNING id`,
|
|
55
|
+
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
56
|
+
claimDue: `
|
|
57
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
58
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() - make_interval(secs => $3::float8) AND ${firstOfKey}
|
|
59
|
+
AND coalesce(nullif($4::text, ''), coalesce(job ->> 'queue', 'default')) = coalesce(job ->> 'queue', 'default') ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
60
|
+
RETURNING job::text AS job, attempts`,
|
|
61
|
+
// the row a queue's signal names, if it's due. It waits for a transaction holding the row (a replace) rather than
|
|
62
|
+
// skip it: there's no other row to take
|
|
63
|
+
claimOne: `
|
|
64
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
65
|
+
WHERE id = $3 AND status = 'pending' AND available_at <= now()
|
|
66
|
+
RETURNING job::text AS job, attempts`,
|
|
67
|
+
// due, or never tried and waiting only for its turn (not for a `delay`): no need to wait for a sweep
|
|
68
|
+
claimNext: `
|
|
69
|
+
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, claimed_at = now(), available_at = ${inSeconds(2)}
|
|
70
|
+
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND order_key = $3 AND (available_at <= now() OR (attempts = 0 AND job->>'runAt' IS NULL))
|
|
71
|
+
AND ${firstOfKey} ORDER BY seq LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
72
|
+
RETURNING job::text AS job, attempts`,
|
|
73
|
+
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
74
|
+
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2, claimed_at = NULL WHERE ${mine(3)}`,
|
|
75
|
+
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now(), claimed_at = NULL WHERE ${mine(2)}`,
|
|
76
|
+
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
77
|
+
// its receipt goes, so the runner that lost it can't finish the new run. Its key goes: it has run, so it's no longer
|
|
78
|
+
// a call a newer one replaces (and one may be waiting with it)
|
|
79
|
+
retry: `
|
|
80
|
+
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, claimed_at = NULL, available_at = now(), last_error = NULL, failed_at = NULL, unique_key = NULL
|
|
81
|
+
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
82
|
+
fail: `
|
|
83
|
+
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
84
|
+
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
85
|
+
// field by field, as SQLite matches, so both databases agree; `failed_at` back as text to the microsecond, for the cursor
|
|
86
|
+
failed: `
|
|
87
|
+
WITH p AS (SELECT NULLIF($1, '') AS source, NULLIF($2, '') AS want, NULLIF($3, '')::timestamptz AS at, NULLIF($4, '') AS after_id)
|
|
88
|
+
SELECT j.id, j.job::text AS job, j.last_error, to_char(j.failed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS failed_at
|
|
89
|
+
FROM logic_jobs j, p
|
|
90
|
+
WHERE j.status = 'failed'
|
|
91
|
+
AND (p.source IS NULL OR coalesce(j.job ->> 'listener', j.job ->> 'cron', j.job ->> 'fn') = p.source)
|
|
92
|
+
AND (p.want IS NULL OR NOT EXISTS (
|
|
93
|
+
SELECT 1 FROM jsonb_array_elements(p.want::jsonb) AS w(m)
|
|
94
|
+
WHERE (coalesce(j.job -> 'scope', j.job #> '{envelope,scope}') #> ARRAY(SELECT jsonb_array_elements_text(w.m -> 'path'))) IS DISTINCT FROM (w.m -> 'value')))
|
|
95
|
+
AND (p.at IS NULL OR (j.failed_at, j.id) < (p.at, p.after_id))
|
|
96
|
+
ORDER BY j.failed_at DESC, j.id DESC
|
|
97
|
+
LIMIT $5::int`,
|
|
98
|
+
forget: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
99
|
+
take: `DELETE FROM logic_jobs WHERE id = $1 AND status = 'failed' RETURNING job::text AS job`,
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
103
|
+
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
104
|
+
* is needed, or `work(registry)` in the same process takes them; `sweep` picks up what a crash, a retry or a delay left
|
|
105
|
+
* behind. With `runIn: "worker"`, requests only write rows and workers in other processes run them. At least once: a crash between a job finishing and its row being deleted runs it again.
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(), scope: { store, load } } });
|
|
109
|
+
* work(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export const databaseQueue = (options = {}) => storedJobs(statements, options);
|
|
113
|
+
/**
|
|
114
|
+
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, and stay
|
|
115
|
+
* rows until they're done: the queue gets a signal per job (per key, for a listener's `key`), and the consumer that gets
|
|
116
|
+
* one runs the row from the table and records how it went there. So tries, failed rows and a key's order are the
|
|
117
|
+
* table's, as with `databaseQueue`. A failed try gets a new signal for when its backoff ends; what no signal covers, the
|
|
118
|
+
* sweep runs 30 seconds past due. At least once: a consumer that dies after the work leaves the row to run again.
|
|
119
|
+
*
|
|
120
|
+
* ```ts
|
|
121
|
+
* jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export const outbox = (queue, options = {}) => storedJobs(statements, options, queue);
|
|
125
|
+
/**
|
|
126
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
127
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
128
|
+
*/
|
|
129
|
+
export const failedJobs = () => failedStore(statements);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
2
|
+
import type { FailedJobs, JobsAdapter } from "../core/types.ts";
|
|
3
|
+
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
4
|
+
export declare const jobsSchema = "\nCREATE TABLE logic_jobs (\n id text PRIMARY KEY NOT NULL,\n job text NOT NULL,\n status text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n available_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer)),\n receipt text,\n claimed_at integer,\n last_error text,\n failed_at integer,\n unique_key text,\n order_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_unique ON logic_jobs (unique_key) WHERE status = 'pending' and attempts = 0;\nCREATE INDEX logic_jobs_order ON logic_jobs (order_key) WHERE status = 'pending';\nCREATE INDEX logic_jobs_failed ON logic_jobs (failed_at, id) WHERE status = 'failed';\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY NOT NULL,\n ran_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_cron_runs_ran_at ON logic_cron_runs (ran_at);\n";
|
|
5
|
+
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
6
|
+
export declare const databaseQueue: (options?: DatabaseQueueOptions) => StoredJobs;
|
|
7
|
+
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
8
|
+
export declare const outbox: (queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
9
|
+
/**
|
|
10
|
+
* Failed jobs in your jobs table, for a queue that can't keep them itself: `jobs: { adapter: cloudflareQueue(env.JOBS),
|
|
11
|
+
* failed: failedJobs() }`. Like Laravel's `failed` driver. `databaseQueue` and `outbox` keep their own.
|
|
12
|
+
*/
|
|
13
|
+
export declare const failedJobs: () => FailedJobs;
|