logic-sdk 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/core/jobs.d.ts +57 -0
- package/dist/{jobs.js → core/jobs.js} +161 -42
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +224 -49
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -124
- package/dist/index.js +4 -495
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -55
- package/dist/pg-boss.js +2 -211
- 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 -67
- package/dist/testing.js +1 -214
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +7 -6
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +166 -43
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +219 -46
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +17 -655
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -242
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -288
- package/dist/jobs.d.ts +0 -44
- /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,37 @@
|
|
|
1
|
+
import { ORPCError, os } from "@orpc/server";
|
|
2
|
+
import { isDomainError } from "../core/errors.js";
|
|
3
|
+
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
4
|
+
export const orpcCodeOf = {
|
|
5
|
+
invalid: "BAD_REQUEST",
|
|
6
|
+
unauthenticated: "UNAUTHORIZED",
|
|
7
|
+
forbidden: "FORBIDDEN",
|
|
8
|
+
not_found: "NOT_FOUND",
|
|
9
|
+
conflict: "CONFLICT",
|
|
10
|
+
rejected: "UNPROCESSABLE_CONTENT",
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
14
|
+
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
18
|
+
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export function toORPCProcedure(fn) {
|
|
22
|
+
if (!fn.authorize)
|
|
23
|
+
throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
24
|
+
const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
25
|
+
const withInput = fn.input ? base.input(fn.input) : base;
|
|
26
|
+
const b = fn.output ? withInput.output(fn.output) : withInput;
|
|
27
|
+
return b.handler(async ({ input, context, signal }) => {
|
|
28
|
+
try {
|
|
29
|
+
return await context.caller.run(fn, input, { signal });
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
if (isDomainError(e))
|
|
33
|
+
throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
}); // SAFETY: the same procedure, typed from the function: its input, output and init's scope
|
|
37
|
+
}
|
package/dist/node.d.ts
CHANGED
|
@@ -1,26 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export interface TickingOptions {
|
|
3
|
-
/** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
|
|
4
|
-
sweepEvery?: number;
|
|
5
|
-
/** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
|
|
6
|
-
onError?: (error: unknown) => void;
|
|
7
|
-
}
|
|
8
|
-
export interface StopOptions {
|
|
9
|
-
/** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
|
|
10
|
-
timeout?: number;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
|
|
14
|
-
* every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
|
|
15
|
-
* minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
|
|
16
|
-
* which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
|
|
17
|
-
*
|
|
18
|
-
* ```ts
|
|
19
|
-
* import { startTicking } from "logic-sdk/node";
|
|
20
|
-
* const stop = startTicking(registry);
|
|
21
|
-
* process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
export declare function startTicking(registry: {
|
|
25
|
-
jobs: Pick<Jobs, "tick" | "sweep">;
|
|
26
|
-
}, options?: TickingOptions): (options?: StopOptions) => Promise<void>;
|
|
1
|
+
export { startTicking, type StopOptions, type TickingOptions } from "./hosts/node.ts";
|
package/dist/node.js
CHANGED
|
@@ -1,76 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/**
|
|
3
|
-
* Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
|
|
4
|
-
* Oban: a slow cron doesn't hold back the next minute, and a hung job doesn't stop the sweeps, as it wouldn't stop the
|
|
5
|
-
* other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
|
|
6
|
-
* up would run a backlog of stale minutes when it comes back.
|
|
7
|
-
*/
|
|
8
|
-
const MAX_RUNNING = 10;
|
|
9
|
-
/**
|
|
10
|
-
* A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
|
|
11
|
-
* every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
|
|
12
|
-
* minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
|
|
13
|
-
* which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
|
|
14
|
-
*
|
|
15
|
-
* ```ts
|
|
16
|
-
* import { startTicking } from "logic-sdk/node";
|
|
17
|
-
* const stop = startTicking(registry);
|
|
18
|
-
* process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
export function startTicking(registry, options = {}) {
|
|
22
|
-
const sweepEvery = options.sweepEvery ?? 60;
|
|
23
|
-
const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
24
|
-
const onError = (error) => {
|
|
25
|
-
try {
|
|
26
|
-
reportTo(error);
|
|
27
|
-
}
|
|
28
|
-
catch (inner) {
|
|
29
|
-
console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
let tickTimer;
|
|
33
|
-
let sweepTimer;
|
|
34
|
-
const ticks = new Set();
|
|
35
|
-
const sweeps = new Set();
|
|
36
|
-
const startOfMinute = (ms) => Math.floor(ms / MINUTE) * MINUTE;
|
|
37
|
-
const track = (running, work) => {
|
|
38
|
-
const run = work.then(() => { }, onError);
|
|
39
|
-
running.add(run);
|
|
40
|
-
void run.finally(() => running.delete(run));
|
|
41
|
-
};
|
|
42
|
-
const tick = (at) => {
|
|
43
|
-
if (ticks.size >= MAX_RUNNING) {
|
|
44
|
-
onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
track(ticks, registry.jobs.tick(at));
|
|
48
|
-
};
|
|
49
|
-
const armTick = (minute) => {
|
|
50
|
-
tickTimer = setTimeout(() => {
|
|
51
|
-
// early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
|
|
52
|
-
const due = Math.max(minute, startOfMinute(Date.now()));
|
|
53
|
-
armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
|
|
54
|
-
tick(new Date(due));
|
|
55
|
-
}, minute - Date.now());
|
|
56
|
-
};
|
|
57
|
-
const sweep = () => {
|
|
58
|
-
sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
|
|
59
|
-
if (sweeps.size >= MAX_RUNNING) {
|
|
60
|
-
onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
track(sweeps, registry.jobs.sweep());
|
|
64
|
-
};
|
|
65
|
-
armTick(startOfMinute(Date.now()) + MINUTE);
|
|
66
|
-
if (sweepEvery > 0)
|
|
67
|
-
sweepTimer = setTimeout(sweep, sweepEvery * 1000);
|
|
68
|
-
return async ({ timeout = 30 } = {}) => {
|
|
69
|
-
clearTimeout(tickTimer);
|
|
70
|
-
clearTimeout(sweepTimer);
|
|
71
|
-
let timer;
|
|
72
|
-
const gaveUp = new Promise((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
|
|
73
|
-
await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
|
|
74
|
-
clearTimeout(timer);
|
|
75
|
-
};
|
|
76
|
-
}
|
|
1
|
+
export { startTicking } from "./hosts/node.js";
|
package/dist/orpc.d.ts
CHANGED
|
@@ -1,21 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
-
import { type Caller, type ErrorKind, type Fn, type Kind, type PublishableFn, type ScopeOfFn } from "./index.ts";
|
|
4
|
-
/** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
|
|
5
|
-
export type ORPCContext<S extends object> = {
|
|
6
|
-
caller: Caller<S>;
|
|
7
|
-
};
|
|
8
|
-
/** `toORPCProcedure(fn)`: an oRPC procedure, so `.use`, `.meta` and `.errors` work as on your own. */
|
|
9
|
-
export type ProcedureOf<F> = F extends Fn<Kind, infer I, infer O> ? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
|
|
10
|
-
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
11
|
-
export declare const orpcCodeOf: Record<ErrorKind, string>;
|
|
12
|
-
/**
|
|
13
|
-
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
14
|
-
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
15
|
-
*
|
|
16
|
-
* ```ts
|
|
17
|
-
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
18
|
-
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
export declare function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F>;
|
|
1
|
+
export { orpcCodeOf, toORPCProcedure, type ORPCContext, type ProcedureOf } from "./integrations/orpc.ts";
|
package/dist/orpc.js
CHANGED
|
@@ -1,37 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { isDomainError } from "./index.js";
|
|
3
|
-
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
4
|
-
export const orpcCodeOf = {
|
|
5
|
-
invalid: "BAD_REQUEST",
|
|
6
|
-
unauthenticated: "UNAUTHORIZED",
|
|
7
|
-
forbidden: "FORBIDDEN",
|
|
8
|
-
not_found: "NOT_FOUND",
|
|
9
|
-
conflict: "CONFLICT",
|
|
10
|
-
rejected: "UNPROCESSABLE_CONTENT",
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
14
|
-
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
15
|
-
*
|
|
16
|
-
* ```ts
|
|
17
|
-
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
18
|
-
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
export function toORPCProcedure(fn) {
|
|
22
|
-
if (!fn.authorize)
|
|
23
|
-
throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
24
|
-
const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
25
|
-
const withInput = fn.input ? base.input(fn.input) : base;
|
|
26
|
-
const b = fn.output ? withInput.output(fn.output) : withInput;
|
|
27
|
-
return b.handler(async ({ input, context, signal }) => {
|
|
28
|
-
try {
|
|
29
|
-
return await context.caller.run(fn, input, { signal });
|
|
30
|
-
}
|
|
31
|
-
catch (e) {
|
|
32
|
-
if (isDomainError(e))
|
|
33
|
-
throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
|
|
34
|
-
throw e;
|
|
35
|
-
}
|
|
36
|
-
}); // SAFETY: the same procedure, typed from the function: its input, output and init's scope
|
|
37
|
-
}
|
|
1
|
+
export { orpcCodeOf, toORPCProcedure } from "./integrations/orpc.js";
|
package/dist/pg-boss.d.ts
CHANGED
|
@@ -1,55 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** One queue's tuning: `meta.pgBoss`, and `work()`'s `calls` and `crons`. */
|
|
4
|
-
export interface PgBossTuning {
|
|
5
|
-
/** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
|
|
6
|
-
queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
|
|
7
|
-
/** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
|
|
8
|
-
worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* What this adapter reads from a listener's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
12
|
-
* `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
|
|
13
|
-
* listener's `attempts`, and the other adapters ignore it.
|
|
14
|
-
*/
|
|
15
|
-
export type PgBossMeta = ForListeners<{
|
|
16
|
-
pgBoss?: PgBossTuning;
|
|
17
|
-
}>;
|
|
18
|
-
/**
|
|
19
|
-
* The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
|
|
20
|
-
* minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
|
|
21
|
-
*/
|
|
22
|
-
export declare function pgBossId(id: string): string;
|
|
23
|
-
/**
|
|
24
|
-
* Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
|
|
25
|
-
* like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
|
|
26
|
-
* `await boss.start()` first.
|
|
27
|
-
*
|
|
28
|
-
* ```ts
|
|
29
|
-
* const boss = new PgBoss(process.env.DATABASE_URL!);
|
|
30
|
-
* boss.on("error", console.error);
|
|
31
|
-
* const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
export declare function pgBoss(boss: PgBoss): JobsAdapter;
|
|
35
|
-
export interface PgBossWorkOptions {
|
|
36
|
-
/** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
|
|
37
|
-
calls?: PgBossTuning;
|
|
38
|
-
/** Every cron's queue, tuned the same way (crons have no `meta`): `{ queue: { expireInSeconds: 3600 } }` for a long one. */
|
|
39
|
-
crons?: PgBossTuning;
|
|
40
|
-
/** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
|
|
41
|
-
onError?: (error: unknown) => void;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
45
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
46
|
-
*
|
|
47
|
-
* ```ts
|
|
48
|
-
* await boss.start();
|
|
49
|
-
* await work(registry, boss);
|
|
50
|
-
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
export declare function work(registry: Pick<Registry, "definitions"> & {
|
|
54
|
-
jobs: Pick<Jobs, "run" | "tick" | "sweep">;
|
|
55
|
-
}, boss: PgBoss, options?: PgBossWorkOptions): Promise<void>;
|
|
1
|
+
export { pgBoss, pgBossId, type PgBossMeta, type PgBossTuning } from "./adapters/pg-boss.ts";
|
|
2
|
+
export { work, type PgBossWorkOptions } from "./hosts/pg-boss.ts";
|
package/dist/pg-boss.js
CHANGED
|
@@ -1,211 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { createHash } from "node:crypto";
|
|
4
|
-
import { sql } from "drizzle-orm";
|
|
5
|
-
import { fromDrizzle } from "pg-boss";
|
|
6
|
-
import { replaceKeyOf } from "./index.js";
|
|
7
|
-
import { startTicking } from "./node.js";
|
|
8
|
-
/** Our queues' names start with it, so they can't collide with your own pg-boss queues, and `work()` can find ours. */
|
|
9
|
-
const PREFIX = "logic-sdk.";
|
|
10
|
-
/** A listener's or cron's queue: `logic-sdk.notifications.send`. */
|
|
11
|
-
const queueName = (id) => `${PREFIX}${id}`;
|
|
12
|
-
/** Where scheduled calls (`ctx.schedule`) wait: one queue for all of them, so no function needs a worker of its own. */
|
|
13
|
-
const CALLS_QUEUE = `${PREFIX}calls`; // ids always have a dot, so no listener's queue is this one
|
|
14
|
-
/** A job's queue: its listener's or its cron's, or the shared one for scheduled calls. */
|
|
15
|
-
const queueOf = (job) => (job.kind === "delivery" ? queueName(job.listener) : job.kind === "cron" ? queueName(job.cron) : CALLS_QUEUE);
|
|
16
|
-
/** A queue as `meta.pgBoss.queue` tunes it. Backoff on, as on every job we insert, which `retryDelayMax` needs. */
|
|
17
|
-
const queueConfig = (queue) => ({ ...queue, retryBackoff: true });
|
|
18
|
-
/** `meta.pgBoss` as `PgBossMeta` types it where you write it (meta is stored loose). */
|
|
19
|
-
const tuningOf = (meta) => meta?.pgBoss;
|
|
20
|
-
// A UUID of our own, so the v5 ids below can't collide with anyone else's.
|
|
21
|
-
const NAMESPACE = Buffer.from("408a95afcd954c069af0d15cb1dfc0db", "hex");
|
|
22
|
-
/**
|
|
23
|
-
* The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
|
|
24
|
-
* minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
|
|
25
|
-
*/
|
|
26
|
-
export function pgBossId(id) {
|
|
27
|
-
const hash = createHash("sha1").update(NAMESPACE).update(id).digest();
|
|
28
|
-
hash.writeUInt8((hash.readUInt8(6) & 0x0f) | 0x50, 6); // version 5
|
|
29
|
-
hash.writeUInt8((hash.readUInt8(8) & 0x3f) | 0x80, 8); // RFC 4122 variant
|
|
30
|
-
const hex = hash.toString("hex", 0, 16);
|
|
31
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* A job as a pg-boss row. Its tries are stamped here, as pg-boss counts them (retries after the first), plus one that
|
|
35
|
-
* never runs: when the last try's worker dies, pg-boss's supervisor expires the job without our code, and with a retry
|
|
36
|
-
* left it comes back to `registry.jobs.run`, which fails it past its attempts and reports it, as Laravel's worker does
|
|
37
|
-
* at pickup. A last try that throws is `deadletter`, so it never uses the spare.
|
|
38
|
-
*/
|
|
39
|
-
const rowOf = (job, replaceKey) => ({
|
|
40
|
-
id: pgBossId(job.id),
|
|
41
|
-
data: job,
|
|
42
|
-
startAfter: job.runAt,
|
|
43
|
-
retryLimit: job.attempts,
|
|
44
|
-
retryBackoff: true, // pg-boss retries at once by default; this waits 1 to 2 s, then 2 to 4 s, 4 to 8 s…
|
|
45
|
-
singletonKey: replaceKey,
|
|
46
|
-
});
|
|
47
|
-
// SAFETY: `check` requires a database adapter. Only `drizzleAdapter`'s (Postgres) transactions run pg-boss's SQL: another
|
|
48
|
-
// adapter fails at the first enqueue. Any adapter's `query` is for after 0.5.0 (pg-boss passes arrays and JSON).
|
|
49
|
-
const inTx = (tx) => fromDrizzle(tx, sql);
|
|
50
|
-
/**
|
|
51
|
-
* Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
|
|
52
|
-
* like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
|
|
53
|
-
* `await boss.start()` first.
|
|
54
|
-
*
|
|
55
|
-
* ```ts
|
|
56
|
-
* const boss = new PgBoss(process.env.DATABASE_URL!);
|
|
57
|
-
* boss.on("error", console.error);
|
|
58
|
-
* const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
|
|
59
|
-
* ```
|
|
60
|
-
*/
|
|
61
|
-
export function pgBoss(boss) {
|
|
62
|
-
let database;
|
|
63
|
-
const queueOptions = new Map();
|
|
64
|
-
/**
|
|
65
|
-
* pg-boss needs a job's queue to exist, and `work()` creates them all; this covers a process that enqueues first (a
|
|
66
|
-
* new listener, deployed before its worker). pg-boss looks it up and creates it on its own connection, before any SQL
|
|
67
|
-
* on your transaction, so the transaction is fine (on PGlite, with one connection, it would wait: run `work()` first).
|
|
68
|
-
*/
|
|
69
|
-
async function inQueue(name, write) {
|
|
70
|
-
try {
|
|
71
|
-
await write();
|
|
72
|
-
}
|
|
73
|
-
catch (error) {
|
|
74
|
-
if (!(error instanceof Error && "code" in error && error.code === "PGBOSS_QUEUE_NOT_FOUND"))
|
|
75
|
-
throw error;
|
|
76
|
-
await boss.createQueue(name, queueConfig(queueOptions.get(name)));
|
|
77
|
-
await write();
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* The waiting calls with these keys go, inside the transaction, so the new ones take their place. Only `created` ones:
|
|
82
|
-
* a job in `retry` has started, and isn't touched.
|
|
83
|
-
*/
|
|
84
|
-
async function replaceWaiting(db, keys) {
|
|
85
|
-
// in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
|
|
86
|
-
for (const key of [...new Set(keys)].sort()) {
|
|
87
|
-
// one replacer per key at a time, so the second sees the first's call and replaces it (databaseQueue's unique index)
|
|
88
|
-
await db.executeSql("select pg_advisory_xact_lock(hashtextextended($1, 0))", [`logic-sdk.replace:${key}`]);
|
|
89
|
-
// a no-op edit that locks the key's queued jobs: a worker's fetch skips locked rows, so none starts while we look
|
|
90
|
-
const { jobs: locked } = await boss.update(CALLS_QUEUE, undefined, { singletonKey: key, match: "all", db });
|
|
91
|
-
if (!locked.length)
|
|
92
|
-
continue;
|
|
93
|
-
const queued = await boss.findJobs(CALLS_QUEUE, { key, queued: true, db });
|
|
94
|
-
const waiting = queued.filter((j) => j.state === "created").map((j) => j.id); // `retry` ones have started
|
|
95
|
-
if (waiting.length)
|
|
96
|
-
await boss.deleteJob(CALLS_QUEUE, waiting, { db });
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
return {
|
|
100
|
-
holds: true, // `startAfter`, however far ahead
|
|
101
|
-
replaces: true,
|
|
102
|
-
/** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
103
|
-
check({ listeners, database: given }) {
|
|
104
|
-
if (!given)
|
|
105
|
-
throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
|
|
106
|
-
database = given;
|
|
107
|
-
for (const l of listeners)
|
|
108
|
-
queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
109
|
-
},
|
|
110
|
-
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
111
|
-
async enqueue(tx, jobs) {
|
|
112
|
-
const db = inTx(tx);
|
|
113
|
-
for (const [name, list] of Map.groupBy(jobs, queueOf)) {
|
|
114
|
-
const keys = list.map(replaceKeyOf).filter((key) => key !== undefined);
|
|
115
|
-
await inQueue(name, async () => {
|
|
116
|
-
if (keys.length)
|
|
117
|
-
await replaceWaiting(db, keys);
|
|
118
|
-
await boss.insert(name, list.map((job) => rowOf(job, replaceKeyOf(job))), { db });
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
/** pg-boss's workers pick jobs up (`work()`), so there's nothing to do after commit. */
|
|
123
|
-
async deliver() { },
|
|
124
|
-
/**
|
|
125
|
-
* A failed job, back in line with a fresh set of attempts (pg-boss's own `retry` gives one more). Its replace key goes:
|
|
126
|
-
* it has run, so it's no longer a call a newer one replaces.
|
|
127
|
-
*/
|
|
128
|
-
async retry(id) {
|
|
129
|
-
// its queue: the listener's or cron's (the id's prefix), or the calls queue. Looked up first: inside the
|
|
130
|
-
// transaction, a lookup on pg-boss's own connection would wait for it on PGlite.
|
|
131
|
-
const at = id.lastIndexOf("@");
|
|
132
|
-
if (at < 0)
|
|
133
|
-
return false; // not a job id
|
|
134
|
-
const names = [queueName(id.slice(0, at)), CALLS_QUEUE].filter((name) => /^[\w.\-/]+$/.test(name)); // pg-boss's rule: an id from anywhere
|
|
135
|
-
const queues = await boss.getQueues(names);
|
|
136
|
-
if (!database || !queues.length)
|
|
137
|
-
return false;
|
|
138
|
-
const uuid = pgBossId(id);
|
|
139
|
-
return database.transaction(async (tx) => {
|
|
140
|
-
const db = inTx(tx);
|
|
141
|
-
for (const { name } of queues) {
|
|
142
|
-
// failed to retry, under the row's lock: one retry(id) gets it, and no worker starts it until it's reset below
|
|
143
|
-
const { affected } = await boss.retry(name, uuid, { db });
|
|
144
|
-
if (!affected)
|
|
145
|
-
continue;
|
|
146
|
-
const [failed] = await boss.findJobs(name, { id: uuid, db });
|
|
147
|
-
if (!failed)
|
|
148
|
-
continue;
|
|
149
|
-
// as new: retry count 0, and its retries again
|
|
150
|
-
await boss.deleteJob(name, uuid, { db });
|
|
151
|
-
await boss.insert(name, [rowOf(failed.data)], { db });
|
|
152
|
-
return true;
|
|
153
|
-
}
|
|
154
|
-
return false;
|
|
155
|
-
});
|
|
156
|
-
},
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
161
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
162
|
-
*
|
|
163
|
-
* ```ts
|
|
164
|
-
* await boss.start();
|
|
165
|
-
* await work(registry, boss);
|
|
166
|
-
* process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
|
|
167
|
-
* ```
|
|
168
|
-
*/
|
|
169
|
-
export async function work(registry, boss, options = {}) {
|
|
170
|
-
const { listeners, crons } = registry.definitions;
|
|
171
|
-
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
172
|
-
const queues = [
|
|
173
|
-
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
174
|
-
...crons.map((c) => ({ name: queueName(c.id), tuning: options.crons })),
|
|
175
|
-
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
176
|
-
];
|
|
177
|
-
/** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
|
|
178
|
-
const settle = async (job) => {
|
|
179
|
-
let reason;
|
|
180
|
-
const fail = async (error) => {
|
|
181
|
-
reason = error; // kept by pg-boss as the failed job's output
|
|
182
|
-
};
|
|
183
|
-
try {
|
|
184
|
-
const outcome = await registry.jobs.run(job.data, { attempt: job.retryCount + 1, fail });
|
|
185
|
-
if (outcome === "failed")
|
|
186
|
-
return { id: job.id, status: "deadletter", output: reason };
|
|
187
|
-
return { id: job.id, status: "completed" };
|
|
188
|
-
}
|
|
189
|
-
catch (error) {
|
|
190
|
-
return { id: job.id, status: "failed", output: error }; // reported already; pg-boss retries it after a backoff
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
for (const { name, tuning } of queues) {
|
|
194
|
-
const config = queueConfig(tuning?.queue);
|
|
195
|
-
const { partition: _createOnly, ...updatable } = config;
|
|
196
|
-
await boss.createQueue(name, config); // a no-op when it exists, so its options are updated below
|
|
197
|
-
await boss.updateQueue(name, updatable);
|
|
198
|
-
await boss.work(name, { ...tuning?.worker, perJobResults: true }, (jobs) => Promise.all(jobs.map(settle)));
|
|
199
|
-
}
|
|
200
|
-
// a renamed or removed listener leaves its queue with no worker, and pg-boss's retention deletes those jobs unrun.
|
|
201
|
-
// They never get a try that could report, so say so here
|
|
202
|
-
const ours = new Set(queues.map((q) => q.name));
|
|
203
|
-
for (const q of await boss.getQueues())
|
|
204
|
-
if (q.name.startsWith(PREFIX) && !ours.has(q.name) && q.queuedCount > 0)
|
|
205
|
-
onError(new Error(`[logic-sdk] pg-boss queue ${q.name} has ${q.queuedCount} job(s) and no listener or cron here (renamed or removed?). Give it its old id back, or delete the queue.`));
|
|
206
|
-
if (!crons.length)
|
|
207
|
-
return;
|
|
208
|
-
// ticked by every worker: the minute's job id is the same everywhere, so pg-boss inserts one row
|
|
209
|
-
const stop = startTicking(registry, { sweepEvery: 0, onError });
|
|
210
|
-
boss.once("stopped", () => void stop());
|
|
211
|
-
}
|
|
1
|
+
export { pgBoss, pgBossId } from "./adapters/pg-boss.js";
|
|
2
|
+
export { work } from "./hosts/pg-boss.js";
|
package/dist/postgres.d.ts
CHANGED
|
@@ -1,28 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
4
|
-
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
-
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 last_error text,\n failed_at timestamptz,\n replace_key text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE TABLE logic_cron_runs (\n id text PRIMARY KEY,\n ran_at timestamptz NOT NULL DEFAULT now()\n);\n";
|
|
6
|
-
/**
|
|
7
|
-
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
8
|
-
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
9
|
-
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
10
|
-
* its row being deleted runs it again.
|
|
11
|
-
*
|
|
12
|
-
* ```ts
|
|
13
|
-
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
|
|
14
|
-
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
15
|
-
* ```
|
|
16
|
-
*/
|
|
17
|
-
export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
|
|
18
|
-
/**
|
|
19
|
-
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
20
|
-
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
21
|
-
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
22
|
-
* so a job can run twice, even at once.
|
|
23
|
-
*
|
|
24
|
-
* ```ts
|
|
25
|
-
* jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
26
|
-
* ```
|
|
27
|
-
*/
|
|
28
|
-
export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/postgres.ts";
|
|
2
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
|
package/dist/postgres.js
CHANGED
|
@@ -1,82 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// functions, plus the table for your schema.
|
|
3
|
-
import { 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
|
-
last_error text,
|
|
14
|
-
failed_at timestamptz,
|
|
15
|
-
replace_key text,
|
|
16
|
-
created_at timestamptz NOT NULL DEFAULT now()
|
|
17
|
-
);
|
|
18
|
-
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
19
|
-
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
20
|
-
CREATE TABLE logic_cron_runs (
|
|
21
|
-
id text PRIMARY KEY,
|
|
22
|
-
ran_at timestamptz NOT NULL DEFAULT now()
|
|
23
|
-
);
|
|
24
|
-
`;
|
|
25
|
-
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
26
|
-
const ids = (n) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
|
|
27
|
-
const mine = (n) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
28
|
-
const inSeconds = (n) => `now() + make_interval(secs => $${n}::float8)`;
|
|
29
|
-
const statements = {
|
|
30
|
-
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
|
|
31
|
-
insert: `
|
|
32
|
-
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
33
|
-
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
|
|
34
|
-
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
35
|
-
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
36
|
-
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
|
|
37
|
-
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
38
|
-
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
39
|
-
claimNew: `
|
|
40
|
-
UPDATE logic_jobs SET attempts = 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
41
|
-
WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
42
|
-
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
43
|
-
claimDue: `
|
|
44
|
-
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
45
|
-
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
46
|
-
RETURNING job::text AS job, attempts`,
|
|
47
|
-
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
48
|
-
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2 WHERE ${mine(3)}`,
|
|
49
|
-
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now() WHERE ${mine(2)}`,
|
|
50
|
-
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
51
|
-
// 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
|
|
52
|
-
// a call a newer one replaces (and one may be waiting with it)
|
|
53
|
-
retry: `
|
|
54
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
55
|
-
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
56
|
-
fail: `
|
|
57
|
-
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
58
|
-
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
59
|
-
};
|
|
60
|
-
/**
|
|
61
|
-
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
62
|
-
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
63
|
-
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
64
|
-
* its row being deleted runs it again.
|
|
65
|
-
*
|
|
66
|
-
* ```ts
|
|
67
|
-
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
|
|
68
|
-
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
69
|
-
* ```
|
|
70
|
-
*/
|
|
71
|
-
export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
|
|
72
|
-
/**
|
|
73
|
-
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
74
|
-
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
75
|
-
* one that fails for good comes back here as a failed row. A send that lands but whose row isn't deleted is sent again,
|
|
76
|
-
* so a job can run twice, even at once.
|
|
77
|
-
*
|
|
78
|
-
* ```ts
|
|
79
|
-
* jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
80
|
-
* ```
|
|
81
|
-
*/
|
|
82
|
-
export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/postgres.js";
|
package/dist/sqlite.d.ts
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
4
|
-
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
5
|
-
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 last_error text,\n failed_at integer,\n replace_key text,\n created_at integer NOT NULL DEFAULT (cast(unixepoch('subsec') * 1000 as integer))\n);\nCREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';\nCREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;\nCREATE 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);\n";
|
|
6
|
-
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
7
|
-
export declare const databaseQueue: (database: SqlDatabase, options?: DatabaseQueueOptions) => StoredJobs;
|
|
8
|
-
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
9
|
-
export declare const outbox: (database: SqlDatabase, queue: JobsAdapter, options?: OutboxOptions) => StoredJobs;
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.ts";
|
|
2
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
|