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,63 @@
|
|
|
1
|
+
import { jsonSchema, tool, type Tool } from "ai";
|
|
2
|
+
import { isDomainError } from "../core/errors.ts";
|
|
3
|
+
import type { Caller, FnIn, FnOut, ForFunctions, PublishableFn, ScopeOfFn } from "../core/types.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What this adapter reads from a function's `meta` (not a listener's). Add it to your meta shape:
|
|
7
|
+
* `init<{ meta: AIMeta & AppMeta }>()`, then `meta: { ai: { description: "Use when the customer asks to cancel an order" } }`.
|
|
8
|
+
*/
|
|
9
|
+
export type AIMeta = ForFunctions<{
|
|
10
|
+
ai?: {
|
|
11
|
+
/** What the model reads to decide when to call it. Optional, but models pick tools better with one. */
|
|
12
|
+
description?: string;
|
|
13
|
+
};
|
|
14
|
+
}>;
|
|
15
|
+
|
|
16
|
+
export interface AIToolOptions {
|
|
17
|
+
/** Overrides `meta.ai.description` for this tool. */
|
|
18
|
+
description?: string;
|
|
19
|
+
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
20
|
+
onError?: (error: unknown) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `meta.ai` as `AIMeta` types it where you write it (meta is stored loose). */
|
|
24
|
+
const aiMeta = (fn: { meta?: Readonly<Record<string, unknown>> }) => fn.meta?.ai as { description?: string } | undefined;
|
|
25
|
+
|
|
26
|
+
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
27
|
+
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One function as an AI SDK tool, run as `caller`: the agent goes through the same policy, validation, transaction
|
|
31
|
+
* and events as your HTTP API. You name it, like any AI SDK tool, and list the ones an agent gets. It needs
|
|
32
|
+
* `authorize`: the model acts for someone else.
|
|
33
|
+
*
|
|
34
|
+
* ```ts
|
|
35
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
36
|
+
* await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
40
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
41
|
+
*/
|
|
42
|
+
export function toAITool<F extends PublishableFn>(
|
|
43
|
+
caller: Caller<ScopeOfFn<F>>,
|
|
44
|
+
fn: F,
|
|
45
|
+
options: AIToolOptions = {},
|
|
46
|
+
): Tool<FnIn<F>, FnOut<F>> {
|
|
47
|
+
if (!fn.authorize) throw new Error("[logic-sdk] toAITool publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
48
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
49
|
+
return tool({
|
|
50
|
+
description: options.description ?? aiMeta(fn)?.description,
|
|
51
|
+
inputSchema: fn.input ?? noInput,
|
|
52
|
+
outputSchema: fn.output,
|
|
53
|
+
async execute(input, { abortSignal }) {
|
|
54
|
+
try {
|
|
55
|
+
return await caller.run(fn, input, { signal: abortSignal });
|
|
56
|
+
} catch (e) {
|
|
57
|
+
if (isDomainError(e)) throw e;
|
|
58
|
+
onError(e);
|
|
59
|
+
throw new Error("internal_error");
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
}) as Tool<FnIn<F>, FnOut<F>>;
|
|
63
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { isDomainError, type ErrorKind } from "../core/errors.ts";
|
|
2
|
+
|
|
3
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
4
|
+
export const statusOf: Record<ErrorKind, number> = {
|
|
5
|
+
invalid: 400,
|
|
6
|
+
unauthenticated: 401,
|
|
7
|
+
forbidden: 403,
|
|
8
|
+
not_found: 404,
|
|
9
|
+
conflict: 409,
|
|
10
|
+
rejected: 422,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
|
|
15
|
+
* (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
|
|
16
|
+
* and logs it, and its message never reaches the client.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* app.post("/orders", async (c) => {
|
|
20
|
+
* try {
|
|
21
|
+
* return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
|
|
22
|
+
* } catch (e) {
|
|
23
|
+
* return toResponse(e);
|
|
24
|
+
* }
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export function toResponse(error: unknown): Response {
|
|
29
|
+
if (!isDomainError(error)) throw error;
|
|
30
|
+
return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
|
|
31
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ORPCError, os, type DecoratedProcedure } from "@orpc/server";
|
|
2
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
import { isDomainError, type ErrorKind } from "../core/errors.ts";
|
|
4
|
+
import type { Caller, Fn, Kind, PublishableFn, ScopeOfFn } from "../core/types.ts";
|
|
5
|
+
|
|
6
|
+
/** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
|
|
7
|
+
export type ORPCContext<S extends object> = { caller: Caller<S> };
|
|
8
|
+
|
|
9
|
+
/** `toORPCProcedure(fn)`: an oRPC procedure, so `.use`, `.meta` and `.errors` work as on your own. */
|
|
10
|
+
export type ProcedureOf<F> =
|
|
11
|
+
F extends Fn<Kind, infer I, infer O>
|
|
12
|
+
? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
|
|
13
|
+
: never;
|
|
14
|
+
|
|
15
|
+
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
16
|
+
export const orpcCodeOf: Record<ErrorKind, string> = {
|
|
17
|
+
invalid: "BAD_REQUEST",
|
|
18
|
+
unauthenticated: "UNAUTHORIZED",
|
|
19
|
+
forbidden: "FORBIDDEN",
|
|
20
|
+
not_found: "NOT_FOUND",
|
|
21
|
+
conflict: "CONFLICT",
|
|
22
|
+
rejected: "UNPROCESSABLE_CONTENT",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
27
|
+
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
31
|
+
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F> {
|
|
35
|
+
if (!fn.authorize) throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
36
|
+
const base = os.$context<ORPCContext<object>>().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
37
|
+
const withInput = fn.input ? base.input(fn.input) : base;
|
|
38
|
+
const b = fn.output ? withInput.output(fn.output) : withInput;
|
|
39
|
+
return b.handler(async ({ input, context, signal }) => {
|
|
40
|
+
try {
|
|
41
|
+
return await context.caller.run(fn, input, { signal });
|
|
42
|
+
} catch (e) {
|
|
43
|
+
if (isDomainError(e)) throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
|
|
44
|
+
throw e;
|
|
45
|
+
}
|
|
46
|
+
}) as ProcedureOf<F>; // SAFETY: the same procedure, typed from the function: its input, output and init's scope
|
|
47
|
+
}
|
package/src/node.ts
CHANGED
|
@@ -1,99 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export interface TickingOptions {
|
|
4
|
-
/** Seconds between sweeps: databaseQueue's retries, delayed jobs and what a crash left behind. Default 60; 0 turns it off. */
|
|
5
|
-
sweepEvery?: number;
|
|
6
|
-
/** Where a failed tick or sweep goes, and a skipped minute. Default `console.error`. */
|
|
7
|
-
onError?: (error: unknown) => void;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export interface StopOptions {
|
|
11
|
-
/** Seconds to wait for the running ticks and sweeps before giving up on them. Default 30, like pg-boss's `stop()`. */
|
|
12
|
-
timeout?: number;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const MINUTE = 60_000;
|
|
16
|
-
/**
|
|
17
|
-
* Ticks, and sweeps, still running before the next of its kind is skipped (reported). Overlap is normal, like Laravel and
|
|
18
|
-
* 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
|
|
19
|
-
* other workers of a queue. Ten still running means they're stuck (the database is unreachable), and letting them pile
|
|
20
|
-
* up would run a backlog of stale minutes when it comes back.
|
|
21
|
-
*/
|
|
22
|
-
const MAX_RUNNING = 10;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* A long-running process's cron trigger, like Laravel's `schedule:work`: ticks your crons on every minute and sweeps
|
|
26
|
-
* every `sweepEvery` seconds, neither waiting for the last, so a slow cron or a hung job doesn't hold back the rest. A
|
|
27
|
-
* minute the process wasn't running for is skipped, not caught up (Laravel and pg-boss do the same). Returns `stop()`,
|
|
28
|
-
* which resolves once the running ticks and sweeps finish, or after `timeout` seconds (30) if they're stuck.
|
|
29
|
-
*
|
|
30
|
-
* ```ts
|
|
31
|
-
* import { startTicking } from "logic-sdk/node";
|
|
32
|
-
* const stop = startTicking(registry);
|
|
33
|
-
* process.on("SIGTERM", async () => { await stop(); process.exit(0); }); // waits 30 s at most: stop({ timeout })
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export function startTicking(
|
|
37
|
-
registry: { jobs: Pick<Jobs, "tick" | "sweep"> },
|
|
38
|
-
options: TickingOptions = {},
|
|
39
|
-
): (options?: StopOptions) => Promise<void> {
|
|
40
|
-
const sweepEvery = options.sweepEvery ?? 60;
|
|
41
|
-
const reportTo = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
42
|
-
const onError = (error: unknown) => {
|
|
43
|
-
try {
|
|
44
|
-
reportTo(error);
|
|
45
|
-
} catch (inner) {
|
|
46
|
-
console.error("[logic-sdk] onError threw", inner, "while reporting", error); // like the registry's: the loops keep going
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
let tickTimer: ReturnType<typeof setTimeout> | undefined;
|
|
50
|
-
let sweepTimer: ReturnType<typeof setTimeout> | undefined;
|
|
51
|
-
const ticks = new Set<Promise<void>>();
|
|
52
|
-
const sweeps = new Set<Promise<void>>();
|
|
53
|
-
|
|
54
|
-
const startOfMinute = (ms: number) => Math.floor(ms / MINUTE) * MINUTE;
|
|
55
|
-
|
|
56
|
-
const track = (running: Set<Promise<void>>, work: Promise<unknown>) => {
|
|
57
|
-
const run = work.then(() => {}, onError);
|
|
58
|
-
running.add(run);
|
|
59
|
-
void run.finally(() => running.delete(run));
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
const tick = (at: Date) => {
|
|
63
|
-
if (ticks.size >= MAX_RUNNING) {
|
|
64
|
-
onError(new Error(`[logic-sdk] skipped the ${at.toISOString()} tick: ${ticks.size} earlier ticks are still running. Is the database reachable?`));
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
track(ticks, registry.jobs.tick(at));
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
const armTick = (minute: number) => {
|
|
71
|
-
tickTimer = setTimeout(() => {
|
|
72
|
-
// early by a millisecond: still this minute. Late (the machine slept): the current one, not a backlog
|
|
73
|
-
const due = Math.max(minute, startOfMinute(Date.now()));
|
|
74
|
-
armTick(due + MINUTE); // the next one first, so a slow tick can't delay it
|
|
75
|
-
tick(new Date(due));
|
|
76
|
-
}, minute - Date.now());
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
const sweep = () => {
|
|
80
|
-
sweepTimer = setTimeout(sweep, sweepEvery * 1000); // the next one first, so a hung job can't stop the sweeps
|
|
81
|
-
if (sweeps.size >= MAX_RUNNING) {
|
|
82
|
-
onError(new Error(`[logic-sdk] skipped a sweep: ${sweeps.size} earlier sweeps are still running. Is a job hung, or the database unreachable?`));
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
track(sweeps, registry.jobs.sweep());
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
armTick(startOfMinute(Date.now()) + MINUTE);
|
|
89
|
-
if (sweepEvery > 0) sweepTimer = setTimeout(sweep, sweepEvery * 1000);
|
|
90
|
-
|
|
91
|
-
return async ({ timeout = 30 } = {}) => {
|
|
92
|
-
clearTimeout(tickTimer);
|
|
93
|
-
clearTimeout(sweepTimer);
|
|
94
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
95
|
-
const gaveUp = new Promise<void>((resolve) => (timer = setTimeout(resolve, timeout * 1000)));
|
|
96
|
-
await Promise.race([Promise.all([...ticks, ...sweeps]), gaveUp]);
|
|
97
|
-
clearTimeout(timer);
|
|
98
|
-
};
|
|
99
|
-
}
|
|
1
|
+
export { work, type StopOptions, type WorkOptions } from "./hosts/node.ts";
|
package/src/orpc.ts
CHANGED
|
@@ -1,46 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
-
import { isDomainError, type Caller, type ErrorKind, type Fn, type Kind, type PublishableFn, type ScopeOfFn } from "./index.ts";
|
|
4
|
-
|
|
5
|
-
/** oRPC context a procedure expects: bind who is calling per request, in your handler or middleware. */
|
|
6
|
-
export type ORPCContext<S extends object> = { 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> =
|
|
10
|
-
F extends Fn<Kind, infer I, infer O>
|
|
11
|
-
? DecoratedProcedure<ORPCContext<ScopeOfFn<F>>, object, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
|
|
12
|
-
: never;
|
|
13
|
-
|
|
14
|
-
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
15
|
-
export const orpcCodeOf: Record<ErrorKind, string> = {
|
|
16
|
-
invalid: "BAD_REQUEST",
|
|
17
|
-
unauthenticated: "UNAUTHORIZED",
|
|
18
|
-
forbidden: "FORBIDDEN",
|
|
19
|
-
not_found: "NOT_FOUND",
|
|
20
|
-
conflict: "CONFLICT",
|
|
21
|
-
rejected: "UNPROCESSABLE_CONTENT",
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* One function as an oRPC procedure, for your own router: the router is your API surface, one file, next to your
|
|
26
|
-
* own procedures and middleware. Validation runs once, in the registry. It needs `authorize`: callers are untrusted.
|
|
27
|
-
*
|
|
28
|
-
* ```ts
|
|
29
|
-
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
30
|
-
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
31
|
-
* ```
|
|
32
|
-
*/
|
|
33
|
-
export function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F> {
|
|
34
|
-
if (!fn.authorize) throw new Error("[logic-sdk] toORPCProcedure publishes a function, so it needs authorize: say who may call it (everyone is `authorize: anyone`).");
|
|
35
|
-
const base = os.$context<ORPCContext<object>>().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
36
|
-
const withInput = fn.input ? base.input(fn.input) : base;
|
|
37
|
-
const b = fn.output ? withInput.output(fn.output) : withInput;
|
|
38
|
-
return b.handler(async ({ input, context, signal }) => {
|
|
39
|
-
try {
|
|
40
|
-
return await context.caller.run(fn, input, { signal });
|
|
41
|
-
} catch (e) {
|
|
42
|
-
if (isDomainError(e)) throw new ORPCError(orpcCodeOf[e.kind], { message: e.code, data: { kind: e.kind, code: e.code, details: e.details } });
|
|
43
|
-
throw e;
|
|
44
|
-
}
|
|
45
|
-
}) as ProcedureOf<F>; // SAFETY: the same procedure, typed from the function: its input, output and init's scope
|
|
46
|
-
}
|
|
1
|
+
export { orpcCodeOf, toORPCProcedure, type ORPCContext, type ProcedureOf } from "./integrations/orpc.ts";
|
package/src/postgres.ts
CHANGED
|
@@ -1,90 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { storedJobs, type DatabaseQueueOptions, type JobsSql, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
4
|
-
import type { JobsAdapter, SqlDatabase } from "./index.ts";
|
|
5
|
-
|
|
6
|
-
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
7
|
-
|
|
8
|
-
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
9
|
-
export const jobsSchema = `
|
|
10
|
-
CREATE TABLE logic_jobs (
|
|
11
|
-
id text PRIMARY KEY,
|
|
12
|
-
job jsonb NOT NULL,
|
|
13
|
-
status text NOT NULL DEFAULT 'pending',
|
|
14
|
-
attempts integer NOT NULL DEFAULT 0,
|
|
15
|
-
available_at timestamptz NOT NULL DEFAULT now(),
|
|
16
|
-
receipt text,
|
|
17
|
-
last_error text,
|
|
18
|
-
failed_at timestamptz,
|
|
19
|
-
replace_key text,
|
|
20
|
-
created_at timestamptz NOT NULL DEFAULT now()
|
|
21
|
-
);
|
|
22
|
-
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
23
|
-
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
24
|
-
CREATE TABLE logic_cron_runs (
|
|
25
|
-
id text PRIMARY KEY,
|
|
26
|
-
ran_at timestamptz NOT NULL DEFAULT now()
|
|
27
|
-
);
|
|
28
|
-
`;
|
|
29
|
-
|
|
30
|
-
// `$n::text::jsonb`, not `$n::jsonb`: a driver that sees a jsonb parameter encodes our JSON string a second time.
|
|
31
|
-
const ids = (n: number) => `(SELECT jsonb_array_elements_text($${n}::text::jsonb))`;
|
|
32
|
-
const mine = (n: number) => `id IN ${ids(n)} AND receipt = $${n + 1} AND status = 'pending'`;
|
|
33
|
-
const inSeconds = (n: number) => `now() + make_interval(secs => $${n}::float8)`;
|
|
34
|
-
|
|
35
|
-
const statements: JobsSql = {
|
|
36
|
-
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`)
|
|
37
|
-
insert: `
|
|
38
|
-
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
39
|
-
SELECT r->>'id', r->'job', coalesce(to_timestamp((r->>'at')::float8 / 1000), ${inSeconds(1)}), r->>'key'
|
|
40
|
-
FROM jsonb_array_elements($2::text::jsonb) WITH ORDINALITY AS rows(r, n) ORDER BY n
|
|
41
|
-
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
42
|
-
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL`,
|
|
43
|
-
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT jsonb_array_elements_text($1::text::jsonb) ON CONFLICT DO NOTHING RETURNING id`,
|
|
44
|
-
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < now() - interval '1 day'`,
|
|
45
|
-
claimNew: `
|
|
46
|
-
UPDATE logic_jobs SET attempts = 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
47
|
-
WHERE id IN ${ids(3)} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
48
|
-
// `=`, not `IN`: Postgres may run an IN subquery once per row, and lock a new row each time
|
|
49
|
-
claimDue: `
|
|
50
|
-
UPDATE logic_jobs SET attempts = attempts + 1, receipt = $1, available_at = ${inSeconds(2)}
|
|
51
|
-
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
52
|
-
RETURNING job::text AS job, attempts`,
|
|
53
|
-
extend: `UPDATE logic_jobs SET available_at = ${inSeconds(1)} WHERE ${mine(2)}`,
|
|
54
|
-
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds(1)}, last_error = $2 WHERE ${mine(3)}`,
|
|
55
|
-
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = $1, failed_at = now() WHERE ${mine(2)}`,
|
|
56
|
-
remove: `DELETE FROM logic_jobs WHERE ${mine(1)}`,
|
|
57
|
-
// 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
|
|
58
|
-
// a call a newer one replaces (and one may be waiting with it)
|
|
59
|
-
retry: `
|
|
60
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = now(), last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
61
|
-
WHERE id = $1 AND status = 'failed' RETURNING id`,
|
|
62
|
-
fail: `
|
|
63
|
-
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES ($1, $2::text::jsonb, 'failed', $3, now())
|
|
64
|
-
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at`,
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Your database as the queue, like Laravel's `database` driver: jobs are rows written in the mutation's transaction, so
|
|
69
|
-
* a committed one is never lost. After commit the request runs them (through `waitUntil` on serverless), so no worker
|
|
70
|
-
* is needed; `sweep` picks up what a crash or a failure left behind. At least once: a crash between a job finishing and
|
|
71
|
-
* its row being deleted runs it again.
|
|
72
|
-
*
|
|
73
|
-
* ```ts
|
|
74
|
-
* const registry = createRegistry({ modules, database, jobs: { adapter: databaseQueue(database), scope: { store, load } } });
|
|
75
|
-
* startTicking(registry); // from logic-sdk/node, or registry.jobs.sweep() from a platform's cron trigger
|
|
76
|
-
* ```
|
|
77
|
-
*/
|
|
78
|
-
export const databaseQueue = (database: SqlDatabase, options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, database, options);
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* The outbox pattern: a table in front of another queue. Jobs are rows written in the mutation's transaction, kept only
|
|
82
|
-
* until `queue` has them: the jobs of one commit go in one send. Then the queue runs them and redelivers what throws;
|
|
83
|
-
* 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,
|
|
84
|
-
* so a job can run twice, even at once.
|
|
85
|
-
*
|
|
86
|
-
* ```ts
|
|
87
|
-
* jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }
|
|
88
|
-
* ```
|
|
89
|
-
*/
|
|
90
|
-
export const outbox = (database: SqlDatabase, queue: JobsAdapter, options: OutboxOptions = {}): StoredJobs => storedJobs(statements, database, options, queue);
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/postgres.ts";
|
|
2
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
|
package/src/sqlite.ts
CHANGED
|
@@ -1,74 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
|
|
4
|
-
import { storedJobs, type DatabaseQueueOptions, type JobsSql, type OutboxOptions, type StoredJobs } from "./stored-jobs.ts";
|
|
5
|
-
import type { JobsAdapter, SqlDatabase } from "./index.ts";
|
|
6
|
-
|
|
7
|
-
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./stored-jobs.ts";
|
|
8
|
-
|
|
9
|
-
const now = `cast(unixepoch('subsec') * 1000 as integer)`;
|
|
10
|
-
|
|
11
|
-
/** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
|
|
12
|
-
export const jobsSchema = `
|
|
13
|
-
CREATE TABLE logic_jobs (
|
|
14
|
-
id text PRIMARY KEY NOT NULL,
|
|
15
|
-
job text NOT NULL,
|
|
16
|
-
status text NOT NULL DEFAULT 'pending',
|
|
17
|
-
attempts integer NOT NULL DEFAULT 0,
|
|
18
|
-
available_at integer NOT NULL DEFAULT (${now}),
|
|
19
|
-
receipt text,
|
|
20
|
-
last_error text,
|
|
21
|
-
failed_at integer,
|
|
22
|
-
replace_key text,
|
|
23
|
-
created_at integer NOT NULL DEFAULT (${now})
|
|
24
|
-
);
|
|
25
|
-
CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
|
|
26
|
-
CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
|
|
27
|
-
CREATE TABLE logic_cron_runs (
|
|
28
|
-
id text PRIMARY KEY NOT NULL,
|
|
29
|
-
ran_at integer NOT NULL DEFAULT (${now})
|
|
30
|
-
);
|
|
31
|
-
`;
|
|
32
|
-
|
|
33
|
-
const ids = "(SELECT value FROM json_each(?))";
|
|
34
|
-
const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
|
|
35
|
-
const inSeconds = `${now} + cast(? * 1000 as integer)`;
|
|
36
|
-
|
|
37
|
-
const statements: JobsSql = {
|
|
38
|
-
// the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
|
|
39
|
-
// the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
|
|
40
|
-
insert: `
|
|
41
|
-
INSERT INTO logic_jobs (id, job, available_at, replace_key)
|
|
42
|
-
SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
|
|
43
|
-
FROM json_each(?) WHERE true ORDER BY json_each.key
|
|
44
|
-
ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
|
|
45
|
-
DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
|
|
46
|
-
RETURNING id`,
|
|
47
|
-
recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
|
|
48
|
-
pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
|
|
49
|
-
claimNew: `
|
|
50
|
-
UPDATE logic_jobs SET attempts = 1, receipt = ?, available_at = ${inSeconds}
|
|
51
|
-
WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
|
|
52
|
-
// no row locks to skip: SQLite has one writer at a time, and this statement is one write
|
|
53
|
-
claimDue: `
|
|
54
|
-
UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, available_at = ${inSeconds}
|
|
55
|
-
WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
|
|
56
|
-
RETURNING job, attempts`,
|
|
57
|
-
extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
|
|
58
|
-
backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ? WHERE ${mine} RETURNING id`,
|
|
59
|
-
markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now} WHERE ${mine} RETURNING id`,
|
|
60
|
-
remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
|
|
61
|
-
retry: `
|
|
62
|
-
UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
|
|
63
|
-
WHERE id = ? AND status = 'failed' RETURNING id`,
|
|
64
|
-
fail: `
|
|
65
|
-
INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
|
|
66
|
-
ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
|
|
67
|
-
RETURNING id`,
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
/** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
|
|
71
|
-
export const databaseQueue = (database: SqlDatabase, options: DatabaseQueueOptions = {}): StoredJobs => storedJobs(statements, database, options);
|
|
72
|
-
|
|
73
|
-
/** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
|
|
74
|
-
export const outbox = (database: SqlDatabase, queue: JobsAdapter, options: OutboxOptions = {}): StoredJobs => storedJobs(statements, database, options, queue);
|
|
1
|
+
export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.ts";
|
|
2
|
+
export type { DatabaseQueueOptions, OutboxOptions, StoredJobs } from "./adapters/stored-jobs.ts";
|