@accelerate/messaging 0.0.0-stage → 0.1.0-next.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 +25 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/modules/events-core/dist/index.d.ts +14 -0
- package/dist/modules/events-core/dist/index.js +3 -0
- package/dist/modules/events-core/dist/journal.d.ts +57 -0
- package/dist/modules/events-core/dist/journal.js +124 -0
- package/dist/modules/events-memory/dist/index.d.ts +3 -0
- package/dist/modules/events-memory/dist/index.js +7 -0
- package/dist/modules/events-memory/dist/journal.d.ts +37 -0
- package/dist/modules/events-memory/dist/journal.js +42 -0
- package/dist/modules/events-postgres/dist/index.d.ts +8 -0
- package/dist/modules/events-postgres/dist/index.js +4 -0
- package/dist/modules/events-postgres/dist/journal.d.ts +21 -0
- package/dist/modules/events-postgres/dist/journal.js +72 -0
- package/dist/modules/events-postgres/dist/schema.d.ts +1 -0
- package/dist/modules/events-postgres/dist/schema.js +1 -0
- package/dist/modules/events-redis/dist/index.d.ts +15 -0
- package/dist/modules/events-redis/dist/index.js +15 -0
- package/dist/modules/events-redis/dist/journal.d.ts +25 -0
- package/dist/modules/events-redis/dist/journal.js +45 -0
- package/dist/modules/jobs-core/dist/index.d.ts +21 -0
- package/dist/modules/jobs-core/dist/index.js +2 -0
- package/dist/modules/jobs-postgres/dist/index.d.ts +20 -0
- package/dist/modules/jobs-postgres/dist/index.js +123 -0
- package/dist/modules/jobs-postgres/dist/testing.d.ts +23 -0
- package/dist/modules/jobs-postgres/dist/testing.js +62 -0
- package/dist/modules/outbox-core/dist/index.d.ts +32 -0
- package/dist/modules/outbox-core/dist/index.js +34 -0
- package/dist/modules/outbox-postgres/dist/index.d.ts +13 -0
- package/dist/modules/outbox-postgres/dist/index.js +104 -0
- package/dist/modules/scheduler-core/dist/durable.d.ts +52 -0
- package/dist/modules/scheduler-core/dist/durable.js +153 -0
- package/dist/modules/scheduler-core/dist/index.d.ts +18 -0
- package/dist/modules/scheduler-core/dist/index.js +29 -0
- package/dist/modules/scheduler-postgres/dist/index.d.ts +19 -0
- package/dist/modules/scheduler-postgres/dist/index.js +97 -0
- package/dist/modules/workflows-core/dist/definition.d.ts +58 -0
- package/dist/modules/workflows-core/dist/definition.js +105 -0
- package/dist/modules/workflows-core/dist/durable.d.ts +60 -0
- package/dist/modules/workflows-core/dist/durable.js +300 -0
- package/dist/modules/workflows-core/dist/index.d.ts +19 -0
- package/dist/modules/workflows-core/dist/index.js +13 -0
- package/dist/modules/workflows-memory/dist/index.d.ts +2 -0
- package/dist/modules/workflows-memory/dist/index.js +32 -0
- package/dist/modules/workflows-postgres/dist/index.d.ts +5 -0
- package/dist/modules/workflows-postgres/dist/index.js +49 -0
- package/package.json +116 -4
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export const JOBS_SCHEMA = `CREATE TABLE IF NOT EXISTS accelerate_jobs (
|
|
2
|
+
id text PRIMARY KEY,
|
|
3
|
+
name text NOT NULL,
|
|
4
|
+
payload jsonb NOT NULL,
|
|
5
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
6
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
7
|
+
available_at timestamptz NOT NULL DEFAULT now(),
|
|
8
|
+
status text NOT NULL DEFAULT 'pending',
|
|
9
|
+
locked_by text,
|
|
10
|
+
locked_until timestamptz,
|
|
11
|
+
last_error text
|
|
12
|
+
);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS accelerate_jobs_ready_idx ON accelerate_jobs (available_at, created_at) WHERE status = 'pending';`;
|
|
14
|
+
export function createPostgresJobQueue(db, idFactory = () => crypto.randomUUID()) {
|
|
15
|
+
return {
|
|
16
|
+
async enqueue(name, payload, options = {}) {
|
|
17
|
+
if (!name)
|
|
18
|
+
throw new Error("Job name required");
|
|
19
|
+
const delay = options.delayMs ?? 0;
|
|
20
|
+
if (!Number.isFinite(delay) || delay < 0)
|
|
21
|
+
throw new RangeError("Invalid delay");
|
|
22
|
+
const id = options.id ?? idFactory();
|
|
23
|
+
await db.query("INSERT INTO accelerate_jobs (id,name,payload,available_at) VALUES ($1,$2,$3::jsonb,now()+($4 * interval '1 millisecond'))", [id, name, JSON.stringify(payload), delay]);
|
|
24
|
+
return id;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** Polling worker with atomic claims, leases and bounded retries.
|
|
29
|
+
* Run migrations before starting. Handlers must be idempotent: a crashed worker
|
|
30
|
+
* can be retried after its lease expires, yielding at-least-once delivery.
|
|
31
|
+
*/
|
|
32
|
+
export function createPostgresJobWorker(db, options) {
|
|
33
|
+
if (!options.workerId)
|
|
34
|
+
throw new Error("workerId is required");
|
|
35
|
+
const pollMs = options.pollIntervalMs ?? 1000;
|
|
36
|
+
const leaseMs = options.leaseMs ?? 30000;
|
|
37
|
+
const heartbeatMs = options.heartbeatMs ?? Math.floor(leaseMs / 3);
|
|
38
|
+
const maxAttempts = options.maxAttempts ?? 5;
|
|
39
|
+
const retryMs = options.retryDelayMs ?? 1000;
|
|
40
|
+
if (![pollMs, leaseMs, retryMs, heartbeatMs].every(n => Number.isFinite(n) && n > 0) || heartbeatMs >= leaseMs || !Number.isInteger(maxAttempts) || maxAttempts < 1)
|
|
41
|
+
throw new RangeError("Invalid worker options");
|
|
42
|
+
const handlers = new Map();
|
|
43
|
+
let running = false;
|
|
44
|
+
let controller;
|
|
45
|
+
let loop;
|
|
46
|
+
async function claim() {
|
|
47
|
+
const result = await db.query(`UPDATE accelerate_jobs SET status='running', attempts=attempts+1, locked_by=$1,
|
|
48
|
+
locked_until=now()+($2 * interval '1 millisecond')
|
|
49
|
+
WHERE id=(SELECT id FROM accelerate_jobs
|
|
50
|
+
WHERE (status='pending' AND available_at<=now()) OR (status='running' AND locked_until<now())
|
|
51
|
+
ORDER BY available_at, created_at FOR UPDATE SKIP LOCKED LIMIT 1)
|
|
52
|
+
RETURNING id,name,payload,attempts,created_at`, [options.workerId, leaseMs]);
|
|
53
|
+
const row = result.rows[0];
|
|
54
|
+
return row && { id: row.id, name: row.name, payload: row.payload, attempts: row.attempts, createdAt: new Date(row.created_at).toISOString() };
|
|
55
|
+
}
|
|
56
|
+
async function process(job, signal) {
|
|
57
|
+
let leaseLost = false;
|
|
58
|
+
let renewing = false;
|
|
59
|
+
const heartbeat = setInterval(() => {
|
|
60
|
+
if (renewing || leaseLost)
|
|
61
|
+
return;
|
|
62
|
+
renewing = true;
|
|
63
|
+
void db.query("UPDATE accelerate_jobs SET locked_until=now()+($3 * interval '1 millisecond') WHERE id=$1 AND locked_by=$2 AND status='running' AND locked_until>now()", [job.id, options.workerId, leaseMs])
|
|
64
|
+
.then(result => { if (result.rowCount !== 1)
|
|
65
|
+
leaseLost = true; })
|
|
66
|
+
.catch(error => { leaseLost = true; options.onError?.(error, job); })
|
|
67
|
+
.finally(() => { renewing = false; });
|
|
68
|
+
}, heartbeatMs);
|
|
69
|
+
try {
|
|
70
|
+
const handler = handlers.get(job.name);
|
|
71
|
+
if (!handler)
|
|
72
|
+
throw new Error(`No handler registered for ${job.name}`);
|
|
73
|
+
await handler(job, signal);
|
|
74
|
+
if (leaseLost)
|
|
75
|
+
throw new Error("Job lease lost during execution");
|
|
76
|
+
await db.query("UPDATE accelerate_jobs SET status='completed', locked_by=NULL, locked_until=NULL WHERE id=$1 AND locked_by=$2 AND status='running'", [job.id, options.workerId]);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
const terminal = job.attempts >= maxAttempts;
|
|
80
|
+
await db.query(`UPDATE accelerate_jobs SET status=$3, locked_by=NULL, locked_until=NULL,
|
|
81
|
+
last_error=$4, available_at=now()+($5 * interval '1 millisecond')
|
|
82
|
+
WHERE id=$1 AND locked_by=$2 AND status='running'`, [job.id, options.workerId, terminal ? "failed" : "pending", String(error), retryMs * Math.min(job.attempts, 60)]);
|
|
83
|
+
options.onError?.(error, job);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
clearInterval(heartbeat);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function run(signal) {
|
|
90
|
+
while (!signal.aborted) {
|
|
91
|
+
try {
|
|
92
|
+
const job = await claim();
|
|
93
|
+
if (job) {
|
|
94
|
+
await process(job, signal);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
options.onError?.(error, { id: "", name: "poll", payload: null, attempts: 0, createdAt: new Date().toISOString() });
|
|
100
|
+
}
|
|
101
|
+
await new Promise(resolve => {
|
|
102
|
+
const timer = setTimeout(done, pollMs);
|
|
103
|
+
function done() { clearTimeout(timer); signal.removeEventListener("abort", done); resolve(); }
|
|
104
|
+
signal.addEventListener("abort", done, { once: true });
|
|
105
|
+
if (signal.aborted)
|
|
106
|
+
done();
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
register(name, handler) {
|
|
112
|
+
if (!name || handlers.has(name))
|
|
113
|
+
throw new Error("Handler already registered or name missing");
|
|
114
|
+
handlers.set(name, handler);
|
|
115
|
+
return () => { if (handlers.get(name) === handler)
|
|
116
|
+
handlers.delete(name); };
|
|
117
|
+
},
|
|
118
|
+
async start() { if (running)
|
|
119
|
+
return; running = true; controller = new AbortController(); loop = run(controller.signal); },
|
|
120
|
+
async stop() { if (!running)
|
|
121
|
+
return; running = false; controller?.abort(); await loop; }
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Deterministic in-memory implementation of the SQL statements used by jobs-postgres.
|
|
2
|
+
* This is a behavioral test double, NOT a PostgreSQL SQL parser.
|
|
3
|
+
* Unsupported SQL fails loudly so production query changes cannot silently pass.
|
|
4
|
+
*/
|
|
5
|
+
import type { QueryExecutor } from "@accelerate/data/core";
|
|
6
|
+
export interface SimulatedJob {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
payload: unknown;
|
|
10
|
+
attempts: number;
|
|
11
|
+
created_at: Date;
|
|
12
|
+
available_at: number;
|
|
13
|
+
status: "pending" | "running" | "completed" | "failed";
|
|
14
|
+
locked_by: string | null;
|
|
15
|
+
locked_until: number | null;
|
|
16
|
+
last_error: string | null;
|
|
17
|
+
}
|
|
18
|
+
export interface MemoryJobsDatabase extends QueryExecutor {
|
|
19
|
+
readonly jobs: Map<string, SimulatedJob>;
|
|
20
|
+
advance(ms: number): void;
|
|
21
|
+
readonly now: number;
|
|
22
|
+
}
|
|
23
|
+
export declare function createMemoryJobsDatabase(initialTime?: number): MemoryJobsDatabase;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export function createMemoryJobsDatabase(initialTime = 0) {
|
|
2
|
+
let now = initialTime;
|
|
3
|
+
const jobs = new Map();
|
|
4
|
+
function result(rows, rowCount = rows.length) { return { rows, rowCount }; }
|
|
5
|
+
return {
|
|
6
|
+
jobs,
|
|
7
|
+
get now() { return now; },
|
|
8
|
+
advance(ms) { if (!Number.isFinite(ms) || ms < 0)
|
|
9
|
+
throw new RangeError("Invalid advance"); now += ms; },
|
|
10
|
+
async query(sql, parameters = []) {
|
|
11
|
+
if (sql.startsWith("INSERT INTO accelerate_jobs")) {
|
|
12
|
+
const [id, name, payload, delay] = parameters;
|
|
13
|
+
if (jobs.has(id))
|
|
14
|
+
throw new Error("duplicate job id");
|
|
15
|
+
jobs.set(id, { id, name, payload: JSON.parse(payload), attempts: 0, created_at: new Date(now), available_at: now + delay, status: "pending", locked_by: null, locked_until: null, last_error: null });
|
|
16
|
+
return result([], 1);
|
|
17
|
+
}
|
|
18
|
+
if (sql.includes("RETURNING id,name,payload,attempts,created_at")) {
|
|
19
|
+
const [owner, leaseMs] = parameters;
|
|
20
|
+
const candidate = [...jobs.values()].filter(j => (j.status === "pending" && j.available_at <= now) || (j.status === "running" && j.locked_until !== null && j.locked_until < now)).sort((a, b) => a.available_at - b.available_at || a.created_at.getTime() - b.created_at.getTime())[0];
|
|
21
|
+
if (!candidate)
|
|
22
|
+
return result([]);
|
|
23
|
+
candidate.status = "running";
|
|
24
|
+
candidate.attempts++;
|
|
25
|
+
candidate.locked_by = owner;
|
|
26
|
+
candidate.locked_until = now + leaseMs;
|
|
27
|
+
return result([{ id: candidate.id, name: candidate.name, payload: candidate.payload, attempts: candidate.attempts, created_at: candidate.created_at }]);
|
|
28
|
+
}
|
|
29
|
+
if (sql.includes("SET locked_until=")) {
|
|
30
|
+
const [id, owner, leaseMs] = parameters;
|
|
31
|
+
const j = jobs.get(id);
|
|
32
|
+
if (!j || j.status !== "running" || j.locked_by !== owner || j.locked_until === null || j.locked_until <= now)
|
|
33
|
+
return result([]);
|
|
34
|
+
j.locked_until = now + leaseMs;
|
|
35
|
+
return result([], 1);
|
|
36
|
+
}
|
|
37
|
+
if (sql.includes("status='completed'")) {
|
|
38
|
+
const [id, owner] = parameters;
|
|
39
|
+
const j = jobs.get(id);
|
|
40
|
+
if (!j || j.status !== "running" || j.locked_by !== owner)
|
|
41
|
+
return result([]);
|
|
42
|
+
j.status = "completed";
|
|
43
|
+
j.locked_by = null;
|
|
44
|
+
j.locked_until = null;
|
|
45
|
+
return result([], 1);
|
|
46
|
+
}
|
|
47
|
+
if (sql.includes("last_error=$4")) {
|
|
48
|
+
const [id, owner, status, error, delay] = parameters;
|
|
49
|
+
const j = jobs.get(id);
|
|
50
|
+
if (!j || j.status !== "running" || j.locked_by !== owner)
|
|
51
|
+
return result([]);
|
|
52
|
+
j.status = status;
|
|
53
|
+
j.last_error = error;
|
|
54
|
+
j.available_at = now + delay;
|
|
55
|
+
j.locked_by = null;
|
|
56
|
+
j.locked_until = null;
|
|
57
|
+
return result([], 1);
|
|
58
|
+
}
|
|
59
|
+
throw new Error("Unsupported SQL in in-memory jobs simulator: " + sql);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { DomainEvent } from "../../events-core/dist/index.js";
|
|
2
|
+
export interface OutboxEvent<T = unknown> extends DomainEvent<T> {
|
|
3
|
+
readonly correlationId?: string;
|
|
4
|
+
readonly metadata?: Readonly<Record<string, string>>;
|
|
5
|
+
}
|
|
6
|
+
export interface Delivery {
|
|
7
|
+
readonly event: OutboxEvent;
|
|
8
|
+
readonly token: string;
|
|
9
|
+
readonly attempt: number;
|
|
10
|
+
}
|
|
11
|
+
export interface PublisherStore {
|
|
12
|
+
claim(leaseMs: number): Promise<Delivery | undefined>;
|
|
13
|
+
acknowledge(delivery: Delivery): Promise<boolean>;
|
|
14
|
+
retry(delivery: Delivery, delayMs: number): Promise<boolean>;
|
|
15
|
+
deadLetter(delivery: Delivery): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export interface PublishOptions {
|
|
18
|
+
leaseMs: number;
|
|
19
|
+
maxAttempts: number;
|
|
20
|
+
retryDelayMs: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function validateInteger(value: number, min: number, label: string): void;
|
|
23
|
+
export type PublishResult = {
|
|
24
|
+
status: "idle";
|
|
25
|
+
} | {
|
|
26
|
+
status: "published" | "retry" | "dead-letter" | "lease-lost";
|
|
27
|
+
eventId: string;
|
|
28
|
+
correlationId?: string;
|
|
29
|
+
attempt: number;
|
|
30
|
+
};
|
|
31
|
+
/** Perform one delivery. Store failures propagate so a lease can recover the record. */
|
|
32
|
+
export declare function publishNext(store: PublisherStore, publish: (event: OutboxEvent) => Promise<void>, options: PublishOptions): Promise<PublishResult>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export function validateInteger(value, min, label) {
|
|
2
|
+
if (!Number.isSafeInteger(value) || value < min || value > 2147483647) {
|
|
3
|
+
throw new RangeError(`Invalid ${label}`);
|
|
4
|
+
}
|
|
5
|
+
}
|
|
6
|
+
/** Perform one delivery. Store failures propagate so a lease can recover the record. */
|
|
7
|
+
export async function publishNext(store, publish, options) {
|
|
8
|
+
validateInteger(options.leaseMs, 1, "lease");
|
|
9
|
+
validateInteger(options.maxAttempts, 1, "attempt limit");
|
|
10
|
+
validateInteger(options.retryDelayMs, 0, "retry delay");
|
|
11
|
+
const delivery = await store.claim(options.leaseMs);
|
|
12
|
+
if (!delivery)
|
|
13
|
+
return { status: "idle" };
|
|
14
|
+
const context = {
|
|
15
|
+
eventId: delivery.event.id,
|
|
16
|
+
correlationId: delivery.event.correlationId,
|
|
17
|
+
attempt: delivery.attempt,
|
|
18
|
+
};
|
|
19
|
+
try {
|
|
20
|
+
await publish(delivery.event);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
const exhausted = delivery.attempt >= options.maxAttempts;
|
|
24
|
+
const settled = exhausted
|
|
25
|
+
? await store.deadLetter(delivery)
|
|
26
|
+
: await store.retry(delivery, options.retryDelayMs);
|
|
27
|
+
return {
|
|
28
|
+
...context,
|
|
29
|
+
status: settled ? (exhausted ? "dead-letter" : "retry") : "lease-lost",
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const settled = await store.acknowledge(delivery);
|
|
33
|
+
return { ...context, status: settled ? "published" : "lease-lost" };
|
|
34
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Database, QueryExecutor, Transaction } from "@accelerate/data/core";
|
|
2
|
+
import type { Migration } from "@accelerate/data/migrations";
|
|
3
|
+
import { type OutboxEvent, type PublisherStore } from "../../outbox-core/dist/index.js";
|
|
4
|
+
export declare const outboxMigration: Migration;
|
|
5
|
+
/** Use the transaction that is applying the business write. Duplicate IDs fail the transaction. */
|
|
6
|
+
export declare function enqueueOutbox(tx: Transaction, event: OutboxEvent): Promise<void>;
|
|
7
|
+
export interface PostgresOutbox extends PublisherStore {
|
|
8
|
+
redrive(eventId: string): Promise<boolean>;
|
|
9
|
+
purgePublished(before: Date, limit: number): Promise<number>;
|
|
10
|
+
}
|
|
11
|
+
export declare function postgresOutbox(db: QueryExecutor): PostgresOutbox;
|
|
12
|
+
/** Commit the receipt and local effect in the same database transaction. */
|
|
13
|
+
export declare function consumeOnce(db: Database, consumer: string, event: OutboxEvent, apply: (tx: Transaction, event: OutboxEvent) => Promise<void>): Promise<boolean>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { validateInteger, } from "../../outbox-core/dist/index.js";
|
|
2
|
+
export const outboxMigration = {
|
|
3
|
+
id: "accelerate-outbox/1",
|
|
4
|
+
statements: [
|
|
5
|
+
`CREATE TABLE accelerate_outbox (
|
|
6
|
+
id text PRIMARY KEY, envelope jsonb NOT NULL, status text NOT NULL DEFAULT 'pending'
|
|
7
|
+
CHECK (status IN ('pending','leased','published','dead')), attempt integer NOT NULL DEFAULT 0,
|
|
8
|
+
available_at timestamptz NOT NULL DEFAULT clock_timestamp(), token uuid, published_at timestamptz)`,
|
|
9
|
+
`CREATE INDEX accelerate_outbox_ready ON accelerate_outbox (available_at,id)
|
|
10
|
+
WHERE status IN ('pending','leased')`,
|
|
11
|
+
`CREATE INDEX accelerate_outbox_published ON accelerate_outbox (published_at,id) WHERE status='published'`,
|
|
12
|
+
`CREATE TABLE accelerate_outbox_receipts (consumer text NOT NULL, event_id text NOT NULL,
|
|
13
|
+
PRIMARY KEY (consumer,event_id))`,
|
|
14
|
+
],
|
|
15
|
+
};
|
|
16
|
+
function identifier(value) {
|
|
17
|
+
if (typeof value !== "string" || !value.trim() || value.length > 256)
|
|
18
|
+
throw new TypeError("Invalid outbox identifier");
|
|
19
|
+
}
|
|
20
|
+
/** Use the transaction that is applying the business write. Duplicate IDs fail the transaction. */
|
|
21
|
+
export async function enqueueOutbox(tx, event) {
|
|
22
|
+
identifier(event.id);
|
|
23
|
+
identifier(event.type);
|
|
24
|
+
if (event.correlationId !== undefined)
|
|
25
|
+
identifier(event.correlationId);
|
|
26
|
+
if (typeof event.occurredAt !== "string" ||
|
|
27
|
+
!Number.isFinite(Date.parse(event.occurredAt)))
|
|
28
|
+
throw new TypeError("Invalid event timestamp");
|
|
29
|
+
if (event.metadata !== undefined &&
|
|
30
|
+
(!event.metadata ||
|
|
31
|
+
typeof event.metadata !== "object" ||
|
|
32
|
+
Array.isArray(event.metadata) ||
|
|
33
|
+
Object.values(event.metadata).some((value) => typeof value !== "string"))) {
|
|
34
|
+
throw new TypeError("Invalid event metadata");
|
|
35
|
+
}
|
|
36
|
+
const { id, type, occurredAt, payload, correlationId, metadata } = event;
|
|
37
|
+
const envelope = JSON.stringify({
|
|
38
|
+
id,
|
|
39
|
+
type,
|
|
40
|
+
occurredAt,
|
|
41
|
+
payload,
|
|
42
|
+
...(correlationId !== undefined && { correlationId }),
|
|
43
|
+
...(metadata !== undefined && { metadata }),
|
|
44
|
+
}, (_key, value) => {
|
|
45
|
+
if (value === undefined ||
|
|
46
|
+
typeof value === "function" ||
|
|
47
|
+
typeof value === "symbol" ||
|
|
48
|
+
(typeof value === "number" && !Number.isFinite(value)))
|
|
49
|
+
throw new TypeError("Invalid JSON event value");
|
|
50
|
+
return value;
|
|
51
|
+
});
|
|
52
|
+
await tx.query("INSERT INTO accelerate_outbox (id,envelope) VALUES ($1,$2::jsonb)", [id, envelope]);
|
|
53
|
+
}
|
|
54
|
+
export function postgresOutbox(db) {
|
|
55
|
+
async function settle(delivery, status, delayMs = 0) {
|
|
56
|
+
validateInteger(delayMs, 0, "retry delay");
|
|
57
|
+
const result = await db.query(`UPDATE accelerate_outbox SET status=$3,token=NULL,
|
|
58
|
+
available_at=clock_timestamp()+$4 * interval '1 millisecond',
|
|
59
|
+
published_at=CASE WHEN $3='published' THEN clock_timestamp() END
|
|
60
|
+
WHERE id=$1 AND token=$2 AND status='leased' AND available_at>clock_timestamp()`, [delivery.event.id, delivery.token, status, delayMs]);
|
|
61
|
+
return result.rowCount === 1;
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
async claim(leaseMs) {
|
|
65
|
+
validateInteger(leaseMs, 1, "lease");
|
|
66
|
+
const result = await db.query(`WITH candidate AS (SELECT id FROM accelerate_outbox WHERE status IN ('pending','leased')
|
|
67
|
+
AND available_at<=clock_timestamp() ORDER BY available_at,id LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
68
|
+
UPDATE accelerate_outbox o SET status='leased',token=$1,attempt=o.attempt+1,
|
|
69
|
+
available_at=clock_timestamp()+$2 * interval '1 millisecond' FROM candidate
|
|
70
|
+
WHERE o.id=candidate.id RETURNING o.envelope,o.token,o.attempt`, [crypto.randomUUID(), leaseMs]);
|
|
71
|
+
const row = result.rows[0];
|
|
72
|
+
return (row && { event: row.envelope, token: row.token, attempt: row.attempt });
|
|
73
|
+
},
|
|
74
|
+
acknowledge: (delivery) => settle(delivery, "published"),
|
|
75
|
+
retry: (delivery, delayMs) => settle(delivery, "pending", delayMs),
|
|
76
|
+
deadLetter: (delivery) => settle(delivery, "dead"),
|
|
77
|
+
async redrive(eventId) {
|
|
78
|
+
identifier(eventId);
|
|
79
|
+
const result = await db.query(`UPDATE accelerate_outbox SET status='pending', attempt=0,
|
|
80
|
+
available_at=clock_timestamp() WHERE id=$1 AND status='dead'`, [eventId]);
|
|
81
|
+
return result.rowCount === 1;
|
|
82
|
+
},
|
|
83
|
+
async purgePublished(before, limit) {
|
|
84
|
+
validateInteger(limit, 1, "retention batch size");
|
|
85
|
+
const result = await db.query(`WITH expired AS (SELECT id FROM accelerate_outbox
|
|
86
|
+
WHERE status='published' AND published_at<$1 ORDER BY published_at,id LIMIT $2 FOR UPDATE SKIP LOCKED)
|
|
87
|
+
DELETE FROM accelerate_outbox o USING expired WHERE o.id=expired.id`, [before.toISOString(), limit]);
|
|
88
|
+
return result.rowCount;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** Commit the receipt and local effect in the same database transaction. */
|
|
93
|
+
export function consumeOnce(db, consumer, event, apply) {
|
|
94
|
+
identifier(consumer);
|
|
95
|
+
identifier(event.id);
|
|
96
|
+
return db.transaction(async (tx) => {
|
|
97
|
+
const receipt = await tx.query(`INSERT INTO accelerate_outbox_receipts (consumer,event_id)
|
|
98
|
+
VALUES ($1,$2) ON CONFLICT DO NOTHING`, [consumer, event.id]);
|
|
99
|
+
if (!receipt.rowCount)
|
|
100
|
+
return false;
|
|
101
|
+
await apply(tx, event);
|
|
102
|
+
return true;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type Json } from "@accelerate/data/idempotency";
|
|
2
|
+
export type Timing = {
|
|
3
|
+
kind: "once";
|
|
4
|
+
} | {
|
|
5
|
+
kind: "interval";
|
|
6
|
+
everyMs: number;
|
|
7
|
+
} | {
|
|
8
|
+
kind: "cron";
|
|
9
|
+
expression: string;
|
|
10
|
+
gap?: "skip" | "offset";
|
|
11
|
+
overlap?: "first" | "both";
|
|
12
|
+
};
|
|
13
|
+
export interface ScheduleDefinition {
|
|
14
|
+
id: string;
|
|
15
|
+
startAt: number;
|
|
16
|
+
timing: Timing;
|
|
17
|
+
/** Zone for cron and calendar exclusions. Defaults to UTC. */
|
|
18
|
+
zone?: string;
|
|
19
|
+
excludeDates?: string[];
|
|
20
|
+
missed: {
|
|
21
|
+
kind: "catch-up";
|
|
22
|
+
} | {
|
|
23
|
+
kind: "skip";
|
|
24
|
+
graceMs: number;
|
|
25
|
+
};
|
|
26
|
+
payload: Json;
|
|
27
|
+
}
|
|
28
|
+
export type ScheduleStatus = "active" | "paused" | "cancelled" | "completed";
|
|
29
|
+
export interface ScheduleState {
|
|
30
|
+
definition: ScheduleDefinition;
|
|
31
|
+
status: ScheduleStatus;
|
|
32
|
+
nextAt: number | null;
|
|
33
|
+
}
|
|
34
|
+
export interface ScheduleRun {
|
|
35
|
+
id: string;
|
|
36
|
+
scheduleId: string;
|
|
37
|
+
scheduledAt: number;
|
|
38
|
+
payload: Json;
|
|
39
|
+
}
|
|
40
|
+
export interface ScheduleDecision {
|
|
41
|
+
nextAt: number | null;
|
|
42
|
+
run?: ScheduleRun;
|
|
43
|
+
/** All eligible slots from the old cursor up to this instant were skipped. */
|
|
44
|
+
skippedBefore?: number;
|
|
45
|
+
}
|
|
46
|
+
export declare function scheduleTime(ms: number): number;
|
|
47
|
+
/** Compile once to inspect any number of occurrences without writing state. */
|
|
48
|
+
export declare function compileSchedule(def: ScheduleDefinition): {
|
|
49
|
+
atOrAfter: (minimum: number) => number | null;
|
|
50
|
+
};
|
|
51
|
+
export declare function upcoming(def: ScheduleDefinition, from: number, limit?: number): number[];
|
|
52
|
+
export declare function decideSchedule(state: ScheduleState, now: number): ScheduleDecision | null;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { Temporal } from "@js-temporal/polyfill";
|
|
2
|
+
import { CronosExpression } from "cronosjs";
|
|
3
|
+
import { serializeOutcome } from "@accelerate/data/idempotency";
|
|
4
|
+
export function scheduleTime(ms) {
|
|
5
|
+
if (!Number.isSafeInteger(ms) || ms < 0 || ms > 253402300799999)
|
|
6
|
+
throw new RangeError("Expected epoch milliseconds in years 1970–9999");
|
|
7
|
+
return ms;
|
|
8
|
+
}
|
|
9
|
+
function choice(value, allowed) {
|
|
10
|
+
if (!allowed.includes(value))
|
|
11
|
+
throw new TypeError("Invalid scheduling policy");
|
|
12
|
+
}
|
|
13
|
+
// Evaluate wall-clock cron fields only inside segments with a constant UTC offset.
|
|
14
|
+
function zonedCron(cron, zone, timing, minimum) {
|
|
15
|
+
const zoned = (ms) => Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(zone);
|
|
16
|
+
const candidate = (from, offset) => {
|
|
17
|
+
const local = cron.nextDate(new Date(from + offset - 1));
|
|
18
|
+
return local ? local.getTime() - offset : Infinity;
|
|
19
|
+
};
|
|
20
|
+
let from = minimum;
|
|
21
|
+
while (from <= 253402300799999) {
|
|
22
|
+
const here = zoned(from);
|
|
23
|
+
const offset = here.offsetNanoseconds / 1e6;
|
|
24
|
+
const boundary = here.getTimeZoneTransition("next")?.epochMilliseconds ?? Infinity;
|
|
25
|
+
const previous = zoned(from + 1).getTimeZoneTransition("previous")?.epochMilliseconds;
|
|
26
|
+
let next = candidate(from, offset);
|
|
27
|
+
if (previous !== undefined) {
|
|
28
|
+
const oldOffset = zoned(previous - 1).offsetNanoseconds / 1e6;
|
|
29
|
+
const delta = offset - oldOffset;
|
|
30
|
+
if (delta < 0 && timing.overlap !== "both" && from < previous - delta)
|
|
31
|
+
next = candidate(previous - delta, offset);
|
|
32
|
+
if (delta > 0 && timing.gap === "offset" && from < previous + delta) {
|
|
33
|
+
const shifted = candidate(from, oldOffset);
|
|
34
|
+
if (shifted < previous + delta)
|
|
35
|
+
next = Math.min(next, shifted);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (next < boundary)
|
|
39
|
+
return next;
|
|
40
|
+
// No subsequent matching wall time exists for this expression.
|
|
41
|
+
if (!Number.isFinite(next))
|
|
42
|
+
return null;
|
|
43
|
+
from = boundary;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** Compile once to inspect any number of occurrences without writing state. */
|
|
48
|
+
export function compileSchedule(def) {
|
|
49
|
+
scheduleTime(def.startAt);
|
|
50
|
+
if (typeof def.id !== "string" ||
|
|
51
|
+
!def.id.trim() ||
|
|
52
|
+
def.id.length > 200 ||
|
|
53
|
+
def.id.includes("\u0000"))
|
|
54
|
+
throw new TypeError("Invalid schedule ID");
|
|
55
|
+
serializeOutcome({ status: "completed", result: def.payload });
|
|
56
|
+
choice(def.missed.kind, ["catch-up", "skip"]);
|
|
57
|
+
if (def.missed.kind === "skip")
|
|
58
|
+
scheduleTime(def.missed.graceMs);
|
|
59
|
+
const zone = def.zone ?? "UTC";
|
|
60
|
+
const format = new Intl.DateTimeFormat("sv-SE", {
|
|
61
|
+
timeZone: zone,
|
|
62
|
+
year: "numeric",
|
|
63
|
+
month: "2-digit",
|
|
64
|
+
day: "2-digit",
|
|
65
|
+
});
|
|
66
|
+
const excluded = new Set(def.excludeDates ?? []);
|
|
67
|
+
for (const date of excluded) {
|
|
68
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
|
69
|
+
new Date(date + "T00:00:00Z").toISOString().slice(0, 10) !== date)
|
|
70
|
+
throw new RangeError("Invalid calendar date");
|
|
71
|
+
}
|
|
72
|
+
const timing = def.timing;
|
|
73
|
+
choice(timing.kind, ["once", "interval", "cron"]);
|
|
74
|
+
let cron;
|
|
75
|
+
if (timing.kind === "interval" &&
|
|
76
|
+
(!Number.isSafeInteger(timing.everyMs) || timing.everyMs < 1))
|
|
77
|
+
throw new RangeError("Invalid interval");
|
|
78
|
+
if (timing.kind === "cron") {
|
|
79
|
+
if (timing.expression.trim().split(/\s+/).length !== 5)
|
|
80
|
+
throw new RangeError("Expected five cron fields");
|
|
81
|
+
choice(timing.gap ?? "skip", ["skip", "offset"]);
|
|
82
|
+
choice(timing.overlap ?? "first", ["first", "both"]);
|
|
83
|
+
cron = CronosExpression.parse(timing.expression, {
|
|
84
|
+
timezone: 0,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function atOrAfter(minimum) {
|
|
88
|
+
let from = Math.max(minimum, def.startAt);
|
|
89
|
+
while (from <= 253402300799999) {
|
|
90
|
+
let slot;
|
|
91
|
+
if (timing.kind === "once")
|
|
92
|
+
slot = def.startAt;
|
|
93
|
+
else if (timing.kind === "interval")
|
|
94
|
+
slot =
|
|
95
|
+
def.startAt +
|
|
96
|
+
Math.ceil((from - def.startAt) / timing.everyMs) * timing.everyMs;
|
|
97
|
+
else {
|
|
98
|
+
const next = zonedCron(cron, zone, timing, from);
|
|
99
|
+
if (next === null)
|
|
100
|
+
return null;
|
|
101
|
+
slot = next;
|
|
102
|
+
}
|
|
103
|
+
if (slot < from || slot > 253402300799999)
|
|
104
|
+
return null;
|
|
105
|
+
if (!excluded.size || !excluded.has(format.format(slot)))
|
|
106
|
+
return slot;
|
|
107
|
+
// Find the first millisecond after this local date, including non-24-hour days.
|
|
108
|
+
const day = format.format(slot);
|
|
109
|
+
let low = slot, high = slot + 3600000;
|
|
110
|
+
while (format.format(high) === day)
|
|
111
|
+
high += 3600000;
|
|
112
|
+
while (high - low > 1) {
|
|
113
|
+
const mid = Math.floor((low + high) / 2);
|
|
114
|
+
if (format.format(mid) === day)
|
|
115
|
+
low = mid;
|
|
116
|
+
else
|
|
117
|
+
high = mid;
|
|
118
|
+
}
|
|
119
|
+
from = high;
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
return { atOrAfter };
|
|
124
|
+
}
|
|
125
|
+
export function upcoming(def, from, limit = 10) {
|
|
126
|
+
scheduleTime(from);
|
|
127
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
|
|
128
|
+
throw new RangeError("Expected limit 1–1000");
|
|
129
|
+
const plan = compileSchedule(def), result = [];
|
|
130
|
+
for (let at = plan.atOrAfter(from); at !== null && result.length < limit; at = plan.atOrAfter(at + 1))
|
|
131
|
+
result.push(at);
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
export function decideSchedule(state, now) {
|
|
135
|
+
scheduleTime(now);
|
|
136
|
+
const { definition: def, nextAt } = state;
|
|
137
|
+
if (state.status !== "active" || nextAt === null || nextAt > now)
|
|
138
|
+
return null;
|
|
139
|
+
const plan = compileSchedule(def);
|
|
140
|
+
if (def.missed.kind === "skip" && now - nextAt > def.missed.graceMs) {
|
|
141
|
+
const cutoff = now - def.missed.graceMs;
|
|
142
|
+
return { nextAt: plan.atOrAfter(cutoff), skippedBefore: cutoff };
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
nextAt: plan.atOrAfter(nextAt + 1),
|
|
146
|
+
run: {
|
|
147
|
+
id: def.id + ":" + nextAt,
|
|
148
|
+
scheduleId: def.id,
|
|
149
|
+
scheduledAt: nextAt,
|
|
150
|
+
payload: def.payload,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { JobQueue } from "../../jobs-core/dist/index.js";
|
|
2
|
+
export interface Schedule<T = unknown> {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
payload: T;
|
|
6
|
+
intervalMs: number;
|
|
7
|
+
startAt: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class Scheduler {
|
|
10
|
+
private readonly queue;
|
|
11
|
+
private readonly now;
|
|
12
|
+
private readonly schedules;
|
|
13
|
+
private running;
|
|
14
|
+
constructor(queue: JobQueue, now?: () => number);
|
|
15
|
+
register<T>(schedule: Schedule<T>): () => void;
|
|
16
|
+
tick(): Promise<number>;
|
|
17
|
+
}
|
|
18
|
+
export * from "./durable.js";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export class Scheduler {
|
|
2
|
+
constructor(queue, now = Date.now) {
|
|
3
|
+
this.queue = queue;
|
|
4
|
+
this.now = now;
|
|
5
|
+
this.schedules = new Map();
|
|
6
|
+
this.running = false;
|
|
7
|
+
}
|
|
8
|
+
register(schedule) { if (!schedule.id || !schedule.name || !Number.isSafeInteger(schedule.intervalMs) || schedule.intervalMs <= 0 || !Number.isSafeInteger(schedule.startAt) || this.schedules.has(schedule.id))
|
|
9
|
+
throw new Error("Invalid or duplicate schedule"); const entry = { schedule: { ...schedule }, next: schedule.startAt }; this.schedules.set(schedule.id, entry); return () => { if (this.schedules.get(schedule.id) === entry)
|
|
10
|
+
this.schedules.delete(schedule.id); }; }
|
|
11
|
+
async tick() { if (this.running)
|
|
12
|
+
throw new Error("Tick already running"); this.running = true; let count = 0; try {
|
|
13
|
+
const now = this.now();
|
|
14
|
+
for (const entry of this.schedules.values()) {
|
|
15
|
+
if (entry.next > now)
|
|
16
|
+
continue;
|
|
17
|
+
const { schedule } = entry;
|
|
18
|
+
const slot = entry.next + Math.floor((now - entry.next) / schedule.intervalMs) * schedule.intervalMs;
|
|
19
|
+
await this.queue.enqueue(schedule.name, schedule.payload, { id: schedule.id + ":" + slot });
|
|
20
|
+
entry.next = slot + schedule.intervalMs;
|
|
21
|
+
count++;
|
|
22
|
+
}
|
|
23
|
+
return count;
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
this.running = false;
|
|
27
|
+
} }
|
|
28
|
+
}
|
|
29
|
+
export * from "./durable.js";
|