logic-sdk 0.4.0 → 0.5.0
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 +39 -13
- package/dist/ai.d.ts +16 -26
- package/dist/ai.js +8 -21
- package/dist/cloudflare.d.ts +55 -0
- package/dist/cloudflare.js +85 -0
- package/dist/drizzle/pg.d.ts +237 -0
- package/dist/drizzle/pg.js +67 -0
- package/dist/drizzle/sqlite.d.ts +242 -0
- package/dist/drizzle/sqlite.js +194 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +45 -0
- package/dist/fetch.d.ts +15 -18
- package/dist/fetch.js +18 -55
- package/dist/index.d.ts +75 -379
- package/dist/index.js +228 -181
- package/dist/jobs.d.ts +44 -0
- package/dist/jobs.js +252 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +76 -0
- package/dist/orpc.d.ts +10 -17
- package/dist/orpc.js +19 -28
- package/dist/pg-boss.d.ts +55 -0
- package/dist/pg-boss.js +211 -0
- package/dist/postgres.d.ts +28 -0
- package/dist/postgres.js +82 -0
- package/dist/schedule.d.ts +23 -0
- package/dist/schedule.js +109 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.js +65 -0
- package/dist/stored-jobs.d.ts +64 -0
- package/dist/stored-jobs.js +188 -0
- package/dist/testing.d.ts +50 -14
- package/dist/testing.js +198 -46
- package/dist/types.d.ts +653 -0
- package/dist/types.js +6 -0
- package/package.json +45 -7
- package/skills/logic-sdk/SKILL.md +114 -0
- package/src/ai.ts +23 -46
- package/src/cloudflare.ts +107 -0
- package/src/drizzle/pg.ts +111 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +384 -558
- package/src/jobs.ts +296 -0
- package/src/node.ts +99 -0
- package/src/orpc.ts +24 -42
- package/src/pg-boss.ts +242 -0
- package/src/postgres.ts +90 -0
- package/src/schedule.ts +129 -0
- package/src/sqlite.ts +74 -0
- package/src/stored-jobs.ts +260 -0
- package/src/testing.ts +252 -55
- package/src/types.ts +683 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- package/src/drizzle.ts +0 -39
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { describeIssues, isDomainError, StalePayload } from "./errors.js";
|
|
2
|
+
import { isDue, parseSchedule } from "./schedule.js";
|
|
3
|
+
import { RUNS_NOW } from "./types.js";
|
|
4
|
+
const IN_PROCESS = {
|
|
5
|
+
[RUNS_NOW]: true,
|
|
6
|
+
async deliver(jobs, { run }) {
|
|
7
|
+
// one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
|
|
8
|
+
for (const job of jobs)
|
|
9
|
+
await run({ ...job, attempts: 1 });
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
|
|
14
|
+
* hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
|
|
15
|
+
*/
|
|
16
|
+
export const inProcess = () => IN_PROCESS;
|
|
17
|
+
/** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
|
|
18
|
+
export const runsNow = (adapter) => adapter === IN_PROCESS;
|
|
19
|
+
/**
|
|
20
|
+
* What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
|
|
21
|
+
* waits. Undefined for every other job. For adapters that replace (`replaces: true`).
|
|
22
|
+
*/
|
|
23
|
+
export const replaceKeyOf = (job) => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
|
|
24
|
+
/** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
|
|
25
|
+
export const deliveryOf = (l, e) => ({
|
|
26
|
+
kind: "delivery",
|
|
27
|
+
id: `${l.id}@${e.id}`,
|
|
28
|
+
listener: l.id,
|
|
29
|
+
envelope: e,
|
|
30
|
+
attempts: l.listener.attempts ?? 1,
|
|
31
|
+
});
|
|
32
|
+
/**
|
|
33
|
+
* Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
|
|
34
|
+
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
35
|
+
*/
|
|
36
|
+
export function makeJobs(deps) {
|
|
37
|
+
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, listenerCtx } = deps;
|
|
38
|
+
const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
|
|
39
|
+
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
40
|
+
// ── listeners ────────────────────────────────────────────────────────────
|
|
41
|
+
const byEvent = new Map();
|
|
42
|
+
for (const l of listeners) {
|
|
43
|
+
const name = idOf(l.event);
|
|
44
|
+
byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
|
|
45
|
+
}
|
|
46
|
+
const listenerById = new Map(listeners.map((l) => [l.id, l]));
|
|
47
|
+
const scheduled = crons.map((c) => ({ ...c, schedule: parseSchedule(c.cron.schedule) }));
|
|
48
|
+
const cronById = new Map(crons.map((c) => [c.id, c]));
|
|
49
|
+
const fnById = new Map(functions.map((f) => [f.id, f]));
|
|
50
|
+
/**
|
|
51
|
+
* A job that waits (a listener's `delay`, `ctx.schedule`) needs an adapter that holds it: run early it'd be wrong,
|
|
52
|
+
* kept in memory it'd be lost on restart. Laravel's sync queue drops the delay; we refuse instead.
|
|
53
|
+
*/
|
|
54
|
+
function checkHold(what, seconds) {
|
|
55
|
+
const { holds } = jobsAdapter;
|
|
56
|
+
if (!holds)
|
|
57
|
+
throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
|
|
58
|
+
if (holds !== true && seconds > holds.max)
|
|
59
|
+
throw new Error(`[logic-sdk] ${what} waits ${seconds}s; your jobs adapter holds jobs for at most ${holds.max}s. Put an outbox in front, outbox(database, queue): it holds them as long as needed.`);
|
|
60
|
+
}
|
|
61
|
+
for (const l of listeners)
|
|
62
|
+
if (l.listener.delay)
|
|
63
|
+
checkHold(l.id, l.listener.delay);
|
|
64
|
+
/**
|
|
65
|
+
* What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
|
|
66
|
+
* scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
|
|
67
|
+
* delay) are dropped, reported once.
|
|
68
|
+
*/
|
|
69
|
+
function toJobs(envelopes, calls, parsed) {
|
|
70
|
+
/** Its `when`, if any. A throw is a bug in the app: it fails the mutation, naming the listener. */
|
|
71
|
+
const wants = (l, e, payload) => {
|
|
72
|
+
try {
|
|
73
|
+
return !l.listener.when || l.listener.when(payload);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
const fits = (job) => job.depth <= maxEventDepth;
|
|
80
|
+
const deepEvent = envelopes.find((e) => !fits(e));
|
|
81
|
+
const deepCall = calls.find((c) => !fits(c));
|
|
82
|
+
const loop = (what) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
|
|
83
|
+
if (deepEvent)
|
|
84
|
+
report(loop(deepEvent.name), { source: deepEvent.name });
|
|
85
|
+
else if (deepCall)
|
|
86
|
+
report(loop(deepCall.fn), infoOf(deepCall));
|
|
87
|
+
const deliveries = envelopes.filter(fits).flatMap((e) => (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).map((l) => {
|
|
88
|
+
const job = deliveryOf(l, e);
|
|
89
|
+
const delay = l.listener.delay;
|
|
90
|
+
if (delay)
|
|
91
|
+
job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
|
|
92
|
+
return job;
|
|
93
|
+
}));
|
|
94
|
+
return [...deliveries, ...calls.filter(fits)];
|
|
95
|
+
}
|
|
96
|
+
/** An adapter that couldn't take a commit's jobs: each one may be lost, so each is reported. */
|
|
97
|
+
const reportEach = (error, jobs) => {
|
|
98
|
+
for (const job of jobs)
|
|
99
|
+
report(error, { source: "(jobs adapter)", job });
|
|
100
|
+
};
|
|
101
|
+
/** What `onError` hears about a job. */
|
|
102
|
+
const infoOf = (job, attempt) => job.kind === "delivery"
|
|
103
|
+
? { source: job.listener, job, attempt }
|
|
104
|
+
: { source: job.kind === "cron" ? job.cron : job.fn, job, attempt };
|
|
105
|
+
/** Who a stored job runs as: `jobs.scope.load` rebuilds it; null means discard it (reported). */
|
|
106
|
+
async function scopeOf(job, stored, attempt) {
|
|
107
|
+
if (!jobScope?.load)
|
|
108
|
+
return stored;
|
|
109
|
+
const loaded = await jobScope.load(stored);
|
|
110
|
+
if (loaded === undefined)
|
|
111
|
+
throw new Error(`[logic-sdk] jobs.scope.load returned undefined for ${job.id}. Return the scope, or null to discard the job.`);
|
|
112
|
+
if (loaded === null)
|
|
113
|
+
report(new Error(`[logic-sdk] jobs.scope.load returned null for ${job.id}, so it was discarded.`), { ...infoOf(job, attempt), outcome: "discarded" });
|
|
114
|
+
return loaded;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Run one job: a listener's share of an event, a cron's run, or a scheduled call. Reports every failure; throws only when a retry might
|
|
118
|
+
* help and there are tries left. `fail` keeps a job that failed for good. The jobs it queues land in `queued`, for
|
|
119
|
+
* `deliver` to run once this one is settled; without it (`registry.jobs.run`, in a consumer) they're delivered at once.
|
|
120
|
+
*/
|
|
121
|
+
async function runJob(job, { attempt = 1, fail } = {}, queued) {
|
|
122
|
+
const info = infoOf(job, attempt);
|
|
123
|
+
// read before narrowing: a job queued by another version can have a kind this one doesn't know
|
|
124
|
+
const { id, kind } = job;
|
|
125
|
+
const failed = async (error) => {
|
|
126
|
+
report(error, { ...info, outcome: "failed" });
|
|
127
|
+
await fail?.(error);
|
|
128
|
+
return "failed";
|
|
129
|
+
};
|
|
130
|
+
/** One try of the job's `attempts`. */
|
|
131
|
+
const attemptOnce = async (work) => {
|
|
132
|
+
const { attempts } = job;
|
|
133
|
+
// its last try was claimed but never finished: a crash, or slower than the lease (Laravel checks this too)
|
|
134
|
+
if (attempt > attempts)
|
|
135
|
+
return failed(new Error(`[logic-sdk] ${job.id} has used its ${attempts} attempt(s): the last one never finished (crashed or outlived the lease), or its result wasn't recorded.`));
|
|
136
|
+
try {
|
|
137
|
+
return await work();
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const retrying = attempt < attempts && !(error instanceof StalePayload) && !(isDomainError(error) && error.kind !== "conflict");
|
|
141
|
+
if (!retrying)
|
|
142
|
+
return failed(error);
|
|
143
|
+
report(error, { ...info, outcome: "retry" });
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
// code this process doesn't have (renamed, removed, or not deployed here yet) is a try like any other, as Laravel
|
|
148
|
+
// treats a missing class: in a rolling deploy the new code gets a later one.
|
|
149
|
+
const cantRun = (why) => attemptOnce(async () => {
|
|
150
|
+
throw new Error(`[logic-sdk] ${why}`);
|
|
151
|
+
});
|
|
152
|
+
const missing = (what, id) => cantRun(`${id} isn't a registered ${what} (renamed, removed or not deployed here yet?), so job ${job.id} can't run.`);
|
|
153
|
+
if (job.kind === "cron") {
|
|
154
|
+
const c = cronById.get(job.cron);
|
|
155
|
+
if (!c)
|
|
156
|
+
return missing("cron", job.cron);
|
|
157
|
+
return attemptOnce(async () => {
|
|
158
|
+
await runAs(c.cron.run, c.cron.input, c.cron.scope, 0, queued);
|
|
159
|
+
return "done";
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
if (job.kind === "call") {
|
|
163
|
+
const f = fnById.get(job.fn);
|
|
164
|
+
if (!f)
|
|
165
|
+
return missing("function", job.fn);
|
|
166
|
+
return attemptOnce(async () => {
|
|
167
|
+
const scope = await scopeOf(job, job.scope, attempt);
|
|
168
|
+
if (!scope)
|
|
169
|
+
return "discarded";
|
|
170
|
+
await runAs(f.fn, job.input, scope, job.depth, queued);
|
|
171
|
+
return "done";
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (job.kind !== "delivery")
|
|
175
|
+
return cantRun(`job ${id} has kind ${JSON.stringify(kind)}, which this version can't run.`);
|
|
176
|
+
const l = listenerById.get(job.listener);
|
|
177
|
+
if (!l)
|
|
178
|
+
return missing("listener", job.listener);
|
|
179
|
+
const { envelope } = job;
|
|
180
|
+
return attemptOnce(async () => {
|
|
181
|
+
const scope = await scopeOf(job, envelope.scope, attempt);
|
|
182
|
+
if (!scope)
|
|
183
|
+
return "discarded";
|
|
184
|
+
await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
|
|
185
|
+
// its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
|
|
186
|
+
if (idOf(l.event) !== envelope.name)
|
|
187
|
+
throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
|
|
188
|
+
const r = await l.event.payload["~standard"].validate(envelope.payload);
|
|
189
|
+
if (r.issues)
|
|
190
|
+
throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
191
|
+
const payload = r.value;
|
|
192
|
+
const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
193
|
+
return l.listener.handler({ ...listenerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
|
|
194
|
+
});
|
|
195
|
+
return "done";
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/** A runner whose jobs' own jobs are collected in `queued`. */
|
|
199
|
+
const runnerInto = (queued) => ({
|
|
200
|
+
run: (job, options) => runJob(job, options, queued),
|
|
201
|
+
report: (e, job, attempt) => report(e, infoOf(job, attempt)),
|
|
202
|
+
});
|
|
203
|
+
/**
|
|
204
|
+
* Deliver jobs, then the jobs those queued, and so on. A job is settled before what it queued starts, as a Laravel
|
|
205
|
+
* worker deletes a job before it pops the ones it pushed: a crash in a follow-up can't run the job again.
|
|
206
|
+
*/
|
|
207
|
+
async function deliver(jobs) {
|
|
208
|
+
while (jobs.length) {
|
|
209
|
+
const batch = jobs;
|
|
210
|
+
jobs = [];
|
|
211
|
+
await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once. */
|
|
215
|
+
function due(at) {
|
|
216
|
+
if (Number.isNaN(at.getTime()))
|
|
217
|
+
throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
|
|
218
|
+
const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
|
|
219
|
+
const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
|
|
220
|
+
return scheduled
|
|
221
|
+
.filter((c) => isDue(c.schedule, minute, c.cron.timezone))
|
|
222
|
+
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
223
|
+
}
|
|
224
|
+
const jobs = {
|
|
225
|
+
// a consumer's own `fail` (pg-boss's work(), which records the reason itself) wins over the adapter's
|
|
226
|
+
run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (keepFailed && ((error) => keepFailed(job, error))) }),
|
|
227
|
+
async tick(at = now()) {
|
|
228
|
+
const jobs = due(at);
|
|
229
|
+
if (!jobs.length)
|
|
230
|
+
return [];
|
|
231
|
+
if (enqueue) {
|
|
232
|
+
if (!database)
|
|
233
|
+
throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
|
|
234
|
+
await database.transaction((tx) => enqueue(tx, jobs));
|
|
235
|
+
}
|
|
236
|
+
await deliver(jobs);
|
|
237
|
+
return jobs.map((job) => job.cron);
|
|
238
|
+
},
|
|
239
|
+
async sweep(options) {
|
|
240
|
+
const queued = [];
|
|
241
|
+
const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
|
|
242
|
+
await deliver(queued);
|
|
243
|
+
return result;
|
|
244
|
+
},
|
|
245
|
+
async retry(id) {
|
|
246
|
+
if (!jobsAdapter.retry)
|
|
247
|
+
throw new Error(`[logic-sdk] your jobs adapter keeps no jobs, so there's nothing to retry (${id}). databaseQueue(database), outbox(database, queue) and pgBoss(boss) do.`);
|
|
248
|
+
return jobsAdapter.retry(id);
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
return { toJobs, deliver, jobs, due, checkHold };
|
|
252
|
+
}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Jobs } from "./index.ts";
|
|
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>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const MINUTE = 60_000;
|
|
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
|
+
}
|
package/dist/orpc.d.ts
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type DecoratedProcedure } from "@orpc/server";
|
|
2
2
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
-
import { type Caller, type ErrorKind, type
|
|
4
|
-
/** oRPC context
|
|
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
5
|
export type ORPCContext<S extends object> = {
|
|
6
6
|
caller: Caller<S>;
|
|
7
7
|
};
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export type ORPCRouterOf<S extends object, Mods> = {
|
|
11
|
-
[M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
|
|
12
|
-
[N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
|
|
13
|
-
};
|
|
14
|
-
};
|
|
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;
|
|
15
10
|
/** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
|
|
16
11
|
export declare const orpcCodeOf: Record<ErrorKind, string>;
|
|
17
12
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
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.
|
|
20
15
|
*
|
|
21
16
|
* ```ts
|
|
22
|
-
* const router =
|
|
23
|
-
*
|
|
24
|
-
* handler.handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
17
|
+
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
18
|
+
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
25
19
|
* ```
|
|
26
20
|
*/
|
|
27
|
-
export declare function
|
|
28
|
-
export {};
|
|
21
|
+
export declare function toORPCProcedure<F extends PublishableFn>(fn: F): ProcedureOf<F>;
|
package/dist/orpc.js
CHANGED
|
@@ -10,37 +10,28 @@ export const orpcCodeOf = {
|
|
|
10
10
|
rejected: "UNPROCESSABLE_CONTENT",
|
|
11
11
|
};
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
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
15
|
*
|
|
16
16
|
* ```ts
|
|
17
|
-
* const router =
|
|
18
|
-
*
|
|
19
|
-
* handler.handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
17
|
+
* export const router = { bookings: { confirm: toORPCProcedure(bookings.confirm) } };
|
|
18
|
+
* new RPCHandler(router).handle(request, { prefix: "/rpc", context: { caller: registry.as(await scopeFrom(request)) } });
|
|
20
19
|
* ```
|
|
21
20
|
*/
|
|
22
|
-
export function
|
|
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`).");
|
|
23
24
|
const base = os.$context().$config({ disableInputValidation: true, disableOutputValidation: true });
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (isDomainError(e))
|
|
37
|
-
throw new ORPCError(orpcCodeOf[e.kind], {
|
|
38
|
-
message: e.code,
|
|
39
|
-
data: { kind: e.kind, code: e.code, details: e.details },
|
|
40
|
-
});
|
|
41
|
-
throw e;
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
return router;
|
|
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
|
|
46
37
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
|
|
2
|
+
import { type ForListeners, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
|
|
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>;
|