@accelerate/messaging 0.0.0-stage → 0.1.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.
Files changed (48) hide show
  1. package/README.md +25 -2
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +1 -0
  4. package/dist/modules/events-core/dist/index.d.ts +14 -0
  5. package/dist/modules/events-core/dist/index.js +3 -0
  6. package/dist/modules/events-core/dist/journal.d.ts +57 -0
  7. package/dist/modules/events-core/dist/journal.js +124 -0
  8. package/dist/modules/events-memory/dist/index.d.ts +3 -0
  9. package/dist/modules/events-memory/dist/index.js +7 -0
  10. package/dist/modules/events-memory/dist/journal.d.ts +37 -0
  11. package/dist/modules/events-memory/dist/journal.js +42 -0
  12. package/dist/modules/events-postgres/dist/index.d.ts +8 -0
  13. package/dist/modules/events-postgres/dist/index.js +4 -0
  14. package/dist/modules/events-postgres/dist/journal.d.ts +21 -0
  15. package/dist/modules/events-postgres/dist/journal.js +72 -0
  16. package/dist/modules/events-postgres/dist/schema.d.ts +1 -0
  17. package/dist/modules/events-postgres/dist/schema.js +1 -0
  18. package/dist/modules/events-redis/dist/index.d.ts +15 -0
  19. package/dist/modules/events-redis/dist/index.js +15 -0
  20. package/dist/modules/events-redis/dist/journal.d.ts +25 -0
  21. package/dist/modules/events-redis/dist/journal.js +45 -0
  22. package/dist/modules/jobs-core/dist/index.d.ts +21 -0
  23. package/dist/modules/jobs-core/dist/index.js +2 -0
  24. package/dist/modules/jobs-postgres/dist/index.d.ts +20 -0
  25. package/dist/modules/jobs-postgres/dist/index.js +123 -0
  26. package/dist/modules/jobs-postgres/dist/testing.d.ts +23 -0
  27. package/dist/modules/jobs-postgres/dist/testing.js +62 -0
  28. package/dist/modules/outbox-core/dist/index.d.ts +32 -0
  29. package/dist/modules/outbox-core/dist/index.js +34 -0
  30. package/dist/modules/outbox-postgres/dist/index.d.ts +13 -0
  31. package/dist/modules/outbox-postgres/dist/index.js +104 -0
  32. package/dist/modules/scheduler-core/dist/durable.d.ts +52 -0
  33. package/dist/modules/scheduler-core/dist/durable.js +153 -0
  34. package/dist/modules/scheduler-core/dist/index.d.ts +18 -0
  35. package/dist/modules/scheduler-core/dist/index.js +29 -0
  36. package/dist/modules/scheduler-postgres/dist/index.d.ts +19 -0
  37. package/dist/modules/scheduler-postgres/dist/index.js +97 -0
  38. package/dist/modules/workflows-core/dist/definition.d.ts +58 -0
  39. package/dist/modules/workflows-core/dist/definition.js +105 -0
  40. package/dist/modules/workflows-core/dist/durable.d.ts +60 -0
  41. package/dist/modules/workflows-core/dist/durable.js +300 -0
  42. package/dist/modules/workflows-core/dist/index.d.ts +19 -0
  43. package/dist/modules/workflows-core/dist/index.js +13 -0
  44. package/dist/modules/workflows-memory/dist/index.d.ts +2 -0
  45. package/dist/modules/workflows-memory/dist/index.js +32 -0
  46. package/dist/modules/workflows-postgres/dist/index.d.ts +5 -0
  47. package/dist/modules/workflows-postgres/dist/index.js +49 -0
  48. package/package.json +116 -4
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # Accelerate Messaging
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Events, jobs, workflows, scheduling and transactional outbox.
4
+
5
+ Install with `npm install @accelerate/messaging`. See the [Accelerate SDK catalog](https://www.npmjs.com/package/@accelerate/sdk) for the other packages.
6
+
7
+ ## Import migration
8
+
9
+ Use the subpaths below. Update related imports together wherever your app shares class or provider identity.
10
+
11
+ | Existing import | Replacement import |
12
+ | --- | --- |
13
+ | `@accelerate/events-core` | `@accelerate/messaging/events` |
14
+ | `@accelerate/events-memory` | `@accelerate/messaging/events/memory` |
15
+ | `@accelerate/events-postgres` | `@accelerate/messaging/events/postgres` |
16
+ | `@accelerate/events-redis` | `@accelerate/messaging/events/redis` |
17
+ | `@accelerate/jobs-core` | `@accelerate/messaging/jobs` |
18
+ | `@accelerate/jobs-postgres` | `@accelerate/messaging/jobs/postgres` |
19
+ | `@accelerate/jobs-postgres/testing` | `@accelerate/messaging/jobs/postgres/testing` |
20
+ | `@accelerate/outbox-core` | `@accelerate/messaging/outbox` |
21
+ | `@accelerate/outbox-postgres` | `@accelerate/messaging/outbox/postgres` |
22
+ | `@accelerate/scheduler-core` | `@accelerate/messaging/scheduler` |
23
+ | `@accelerate/scheduler-postgres` | `@accelerate/messaging/scheduler/postgres` |
24
+ | `@accelerate/workflows-core` | `@accelerate/messaging/workflows` |
25
+ | `@accelerate/workflows-memory` | `@accelerate/messaging/workflows/memory` |
26
+ | `@accelerate/workflows-postgres` | `@accelerate/messaging/workflows/postgres` |
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ /** Framework-neutral typed event dispatch and subscription. */
2
+ export interface DomainEvent<T = unknown> {
3
+ readonly type: string;
4
+ readonly payload: T;
5
+ readonly occurredAt: string;
6
+ readonly id: string;
7
+ }
8
+ export type EventHandler<T> = (event: DomainEvent<T>) => void | Promise<void>;
9
+ export interface EventBus {
10
+ publish<T>(event: DomainEvent<T>): Promise<void>;
11
+ subscribe<T>(type: string, handler: EventHandler<T>): () => void;
12
+ }
13
+ export declare function createEvent<T>(type: string, payload: T, id: string, occurredAt?: string): DomainEvent<T>;
14
+ export * from "./journal.js";
@@ -0,0 +1,3 @@
1
+ export function createEvent(type, payload, id, occurredAt = new Date().toISOString()) { if (!type || !id)
2
+ throw new Error('Event type and id are required'); return { type, payload, id, occurredAt }; }
3
+ export * from "./journal.js";
@@ -0,0 +1,57 @@
1
+ import type { DomainEvent } from "./index.js";
2
+ export interface JournalEvent extends DomainEvent {
3
+ readonly schemaVersion: number;
4
+ readonly correlationId?: string;
5
+ readonly causationId?: string;
6
+ }
7
+ export interface JournalRecord {
8
+ cursor: number;
9
+ event: JournalEvent;
10
+ }
11
+ export interface SubscriptionState {
12
+ checkpoint: number;
13
+ attempt: number;
14
+ token: string | null;
15
+ availableAt: number;
16
+ deadCursor: number | null;
17
+ }
18
+ export interface Snapshot {
19
+ revision: number;
20
+ now: number;
21
+ state: SubscriptionState;
22
+ }
23
+ /** Each successful swap advances the revision and enforces the optional exclusive server-time deadline. */
24
+ export interface JournalStorage {
25
+ append(event: JournalEvent): Promise<void>;
26
+ read(after: number, limit: number): Promise<JournalRecord[]>;
27
+ load(name: string): Promise<Snapshot>;
28
+ swap(name: string, revision: number, state: SubscriptionState, deadline?: number): Promise<boolean>;
29
+ }
30
+ export interface Receipt {
31
+ subscription: string;
32
+ token: string;
33
+ cursor: number;
34
+ }
35
+ export interface Delivery extends JournalRecord {
36
+ attempt: number;
37
+ receipt: Receipt;
38
+ }
39
+ export declare function initialSubscription(): SubscriptionState;
40
+ export declare function createEventJournal(storage: JournalStorage): {
41
+ append: (event: DomainEvent & Partial<JournalEvent>) => Promise<void>;
42
+ replay(after?: number, limit?: number): Promise<JournalRecord[]>;
43
+ inspect(name: string): Promise<{
44
+ checkpoint: number;
45
+ attempt: number;
46
+ availableAt: number;
47
+ deadCursor: number | null;
48
+ }>;
49
+ claim(name: string, leaseMs: number): Promise<Delivery | undefined>;
50
+ ack: (receipt: Receipt) => Promise<boolean>;
51
+ nack(receipt: Receipt, options: {
52
+ maxAttempts: number;
53
+ delayMs: number;
54
+ }): Promise<boolean>;
55
+ redrive(name: string, cursor: number): Promise<boolean>;
56
+ };
57
+ export type EventJournal = ReturnType<typeof createEventJournal>;
@@ -0,0 +1,124 @@
1
+ export function initialSubscription() {
2
+ return {
3
+ checkpoint: 0,
4
+ attempt: 0,
5
+ token: null,
6
+ availableAt: 0,
7
+ deadCursor: null,
8
+ };
9
+ }
10
+ function integer(n, min, max, field) {
11
+ if (!Number.isSafeInteger(n) || n < min || n > max)
12
+ throw new RangeError("Invalid " + field);
13
+ }
14
+ function identifier(s) {
15
+ if (typeof s !== "string" || !s.trim() || s.length > 256 || s.includes("\0"))
16
+ throw new TypeError("Invalid event identifier");
17
+ }
18
+ function normalize(event) {
19
+ identifier(event.id);
20
+ identifier(event.type);
21
+ if (typeof event.occurredAt !== "string" ||
22
+ !Number.isFinite(Date.parse(event.occurredAt)))
23
+ throw new TypeError("Invalid event time");
24
+ const schemaVersion = event.schemaVersion === undefined ? 1 : event.schemaVersion;
25
+ integer(schemaVersion, 1, 2147483647, "schema version");
26
+ const normalized = {
27
+ id: event.id,
28
+ type: event.type,
29
+ payload: event.payload,
30
+ occurredAt: new Date(event.occurredAt).toISOString(),
31
+ schemaVersion,
32
+ ...(event.correlationId === undefined
33
+ ? {}
34
+ : { correlationId: event.correlationId }),
35
+ ...(event.causationId === undefined
36
+ ? {}
37
+ : { causationId: event.causationId }),
38
+ };
39
+ if (normalized.correlationId !== undefined)
40
+ identifier(normalized.correlationId);
41
+ if (normalized.causationId !== undefined)
42
+ identifier(normalized.causationId);
43
+ return JSON.parse(JSON.stringify(normalized, (_key, value) => {
44
+ if (["undefined", "function", "symbol"].includes(typeof value) ||
45
+ (typeof value === "number" && !Number.isFinite(value)))
46
+ throw new TypeError("Invalid JSON event");
47
+ return value;
48
+ }));
49
+ }
50
+ export function createEventJournal(storage) {
51
+ async function settle(receipt, action, maxAttempts, delayMs) {
52
+ identifier(receipt.subscription);
53
+ identifier(receipt.token);
54
+ const { state, revision, now } = await storage.load(receipt.subscription);
55
+ if (state.token !== receipt.token || now >= state.availableAt)
56
+ return false;
57
+ const [record] = await storage.read(state.checkpoint, 1);
58
+ if (!record || record.cursor !== receipt.cursor)
59
+ return false;
60
+ const next = action === "ack"
61
+ ? { ...initialSubscription(), checkpoint: record.cursor }
62
+ : {
63
+ ...state,
64
+ token: null,
65
+ availableAt: now + delayMs,
66
+ deadCursor: state.attempt >= maxAttempts ? record.cursor : null,
67
+ };
68
+ return storage.swap(receipt.subscription, revision, next, state.availableAt);
69
+ }
70
+ return {
71
+ append: (event) => storage.append(normalize(event)),
72
+ replay(after = 0, limit = 100) {
73
+ integer(after, 0, Number.MAX_SAFE_INTEGER, "cursor");
74
+ integer(limit, 1, 1000, "page size");
75
+ return storage.read(after, limit);
76
+ },
77
+ async inspect(name) {
78
+ identifier(name);
79
+ const { checkpoint, attempt, availableAt, deadCursor } = (await storage.load(name)).state;
80
+ return { checkpoint, attempt, availableAt, deadCursor };
81
+ },
82
+ async claim(name, leaseMs) {
83
+ identifier(name);
84
+ integer(leaseMs, 1, 2147483647, "lease duration");
85
+ const { state, revision, now } = await storage.load(name);
86
+ if (state.deadCursor !== null || state.availableAt > now)
87
+ return;
88
+ const [record] = await storage.read(state.checkpoint, 1);
89
+ if (!record)
90
+ return;
91
+ const token = crypto.randomUUID();
92
+ const next = {
93
+ ...state,
94
+ token,
95
+ attempt: state.attempt + 1,
96
+ availableAt: now + leaseMs,
97
+ };
98
+ if (await storage.swap(name, revision, next, next.availableAt)) {
99
+ return {
100
+ ...record,
101
+ attempt: next.attempt,
102
+ receipt: { subscription: name, token, cursor: record.cursor },
103
+ };
104
+ }
105
+ },
106
+ ack: (receipt) => settle(receipt, "ack", 1, 0),
107
+ nack(receipt, options) {
108
+ integer(options.maxAttempts, 1, 2147483647, "attempt limit");
109
+ integer(options.delayMs, 0, 2147483647, "retry delay");
110
+ return settle(receipt, "nack", options.maxAttempts, options.delayMs);
111
+ },
112
+ async redrive(name, cursor) {
113
+ identifier(name);
114
+ integer(cursor, 1, Number.MAX_SAFE_INTEGER, "cursor");
115
+ const { state, revision } = await storage.load(name);
116
+ if (state.deadCursor !== cursor)
117
+ return false;
118
+ return storage.swap(name, revision, {
119
+ ...initialSubscription(),
120
+ checkpoint: state.checkpoint,
121
+ });
122
+ },
123
+ };
124
+ }
@@ -0,0 +1,3 @@
1
+ import type { EventBus } from "../../events-core/dist/index.js";
2
+ export declare function createMemoryEventBus(): EventBus;
3
+ export * from "./journal.js";
@@ -0,0 +1,7 @@
1
+ export function createMemoryEventBus() { const handlers = new Map(); return { async publish(event) { for (const handler of [...(handlers.get(event.type) ?? [])])
2
+ await handler(event); }, subscribe(type, handler) { let set = handlers.get(type); if (!set) {
3
+ set = new Set();
4
+ handlers.set(type, set);
5
+ } const h = handler; set.add(h); return () => { set?.delete(h); if (!set?.size)
6
+ handlers.delete(type); }; } }; }
7
+ export * from "./journal.js";
@@ -0,0 +1,37 @@
1
+ import { type JournalRecord, type SubscriptionState } from "../../events-core/dist/index.js";
2
+ export declare function createMemoryJournalStorage(now?: () => number): {
3
+ append(event: JournalRecord["event"]): Promise<void>;
4
+ read(after: number, limit: number): Promise<JournalRecord[]>;
5
+ load(name: string): Promise<{
6
+ now: number;
7
+ revision: number;
8
+ state: SubscriptionState;
9
+ }>;
10
+ swap(name: string, revision: number, state: SubscriptionState, deadline?: number): Promise<boolean>;
11
+ };
12
+ export declare function createMemoryEventJournal(storage?: {
13
+ append(event: JournalRecord["event"]): Promise<void>;
14
+ read(after: number, limit: number): Promise<JournalRecord[]>;
15
+ load(name: string): Promise<{
16
+ now: number;
17
+ revision: number;
18
+ state: SubscriptionState;
19
+ }>;
20
+ swap(name: string, revision: number, state: SubscriptionState, deadline?: number): Promise<boolean>;
21
+ }): {
22
+ append: (event: import("../../events-core/dist/index.js").DomainEvent & Partial<import("../../events-core/dist/index.js").JournalEvent>) => Promise<void>;
23
+ replay(after?: number, limit?: number): Promise<JournalRecord[]>;
24
+ inspect(name: string): Promise<{
25
+ checkpoint: number;
26
+ attempt: number;
27
+ availableAt: number;
28
+ deadCursor: number | null;
29
+ }>;
30
+ claim(name: string, leaseMs: number): Promise<import("../../events-core/dist/index.js").Delivery | undefined>;
31
+ ack: (receipt: import("../../events-core/dist/index.js").Receipt) => Promise<boolean>;
32
+ nack(receipt: import("../../events-core/dist/index.js").Receipt, options: {
33
+ maxAttempts: number;
34
+ delayMs: number;
35
+ }): Promise<boolean>;
36
+ redrive(name: string, cursor: number): Promise<boolean>;
37
+ };
@@ -0,0 +1,42 @@
1
+ import { createEventJournal, initialSubscription, } from "../../events-core/dist/index.js";
2
+ export function createMemoryJournalStorage(now = Date.now) {
3
+ const records = [];
4
+ const ids = new Set();
5
+ const subscriptions = new Map();
6
+ return {
7
+ async append(event) {
8
+ if (ids.has(event.id))
9
+ return;
10
+ records.push({
11
+ cursor: records.length + 1,
12
+ event: structuredClone(event),
13
+ });
14
+ ids.add(event.id);
15
+ },
16
+ async read(after, limit) {
17
+ return structuredClone(records.slice(after, after + limit));
18
+ },
19
+ async load(name) {
20
+ return {
21
+ ...structuredClone(subscriptions.get(name) ?? {
22
+ revision: 0,
23
+ state: initialSubscription(),
24
+ }),
25
+ now: now(),
26
+ };
27
+ },
28
+ async swap(name, revision, state, deadline) {
29
+ if ((subscriptions.get(name)?.revision ?? 0) !== revision ||
30
+ (deadline !== undefined && now() >= deadline))
31
+ return false;
32
+ subscriptions.set(name, {
33
+ revision: revision + 1,
34
+ state: structuredClone(state),
35
+ });
36
+ return true;
37
+ },
38
+ };
39
+ }
40
+ export function createMemoryEventJournal(storage = createMemoryJournalStorage()) {
41
+ return createEventJournal(storage);
42
+ }
@@ -0,0 +1,8 @@
1
+ import type { DomainEvent } from "../../events-core/dist/index.js";
2
+ import type { Database } from "@accelerate/data/core";
3
+ export { EVENTS_SCHEMA } from "./schema.js";
4
+ export declare function createPostgresEventStore(db: Pick<Database, "query">): {
5
+ append<T>(event: DomainEvent<T>): Promise<void>;
6
+ list(type: string, limit?: number): Promise<DomainEvent[]>;
7
+ };
8
+ export * from "./journal.js";
@@ -0,0 +1,4 @@
1
+ export { EVENTS_SCHEMA } from "./schema.js";
2
+ export function createPostgresEventStore(db) { return { async append(event) { await db.query("INSERT INTO accelerate_events (id,type,payload,occurred_at) VALUES ($1,$2,$3::jsonb,$4::timestamptz) ON CONFLICT (id) DO NOTHING", [event.id, event.type, JSON.stringify(event.payload), event.occurredAt]); }, async list(type, limit = 100) { if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
3
+ throw new RangeError("limit must be 1..1000"); const result = await db.query("SELECT id,type,payload,occurred_at FROM accelerate_events WHERE type=$1 ORDER BY occurred_at,id LIMIT $2", [type, limit]); return result.rows.map(row => ({ id: row.id, type: row.type, payload: row.payload, occurredAt: new Date(row.occurred_at).toISOString() })); } }; }
4
+ export * from "./journal.js";
@@ -0,0 +1,21 @@
1
+ import type { Database } from "@accelerate/data/core";
2
+ import type { Migration } from "@accelerate/data/migrations";
3
+ /** Apply atomically through migrations-postgres; existing IDs and legacy writers are preserved. */
4
+ export declare const eventJournalMigration: Migration;
5
+ export declare function createPostgresEventJournal(db: Database): {
6
+ append: (event: import("../../events-core/dist/index.js").DomainEvent & Partial<import("../../events-core/dist/index.js").JournalEvent>) => Promise<void>;
7
+ replay(after?: number, limit?: number): Promise<import("../../events-core/dist/index.js").JournalRecord[]>;
8
+ inspect(name: string): Promise<{
9
+ checkpoint: number;
10
+ attempt: number;
11
+ availableAt: number;
12
+ deadCursor: number | null;
13
+ }>;
14
+ claim(name: string, leaseMs: number): Promise<import("../../events-core/dist/index.js").Delivery | undefined>;
15
+ ack: (receipt: import("../../events-core/dist/index.js").Receipt) => Promise<boolean>;
16
+ nack(receipt: import("../../events-core/dist/index.js").Receipt, options: {
17
+ maxAttempts: number;
18
+ delayMs: number;
19
+ }): Promise<boolean>;
20
+ redrive(name: string, cursor: number): Promise<boolean>;
21
+ };
@@ -0,0 +1,72 @@
1
+ import { createEventJournal, initialSubscription, } from "../../events-core/dist/index.js";
2
+ import { EVENTS_SCHEMA } from "./schema.js";
3
+ /** Apply atomically through migrations-postgres; existing IDs and legacy writers are preserved. */
4
+ export const eventJournalMigration = {
5
+ id: "accelerate-events/1",
6
+ statements: [
7
+ EVENTS_SCHEMA,
8
+ "ALTER TABLE accelerate_events ADD COLUMN cursor bigint, ADD COLUMN schema_version integer NOT NULL DEFAULT 1, ADD COLUMN correlation_id text, ADD COLUMN causation_id text",
9
+ `WITH history AS (SELECT id,row_number() OVER (ORDER BY occurred_at,id) AS position FROM accelerate_events)
10
+ UPDATE accelerate_events e SET cursor=history.position FROM history WHERE e.id=history.id`,
11
+ "ALTER TABLE accelerate_events ALTER COLUMN cursor SET NOT NULL, ADD UNIQUE (cursor)",
12
+ "CREATE TABLE accelerate_event_sequence (singleton boolean PRIMARY KEY CHECK(singleton), position bigint NOT NULL CHECK(position BETWEEN 0 AND 9007199254740991))",
13
+ "INSERT INTO accelerate_event_sequence SELECT true,COALESCE(MAX(cursor),0) FROM accelerate_events",
14
+ `CREATE FUNCTION accelerate_assign_event_cursor() RETURNS trigger LANGUAGE plpgsql AS $$
15
+ BEGIN UPDATE accelerate_event_sequence SET position=position+1 WHERE singleton RETURNING position INTO NEW.cursor; RETURN NEW; END; $$`,
16
+ "CREATE TRIGGER accelerate_event_cursor BEFORE INSERT ON accelerate_events FOR EACH ROW EXECUTE FUNCTION accelerate_assign_event_cursor()",
17
+ "CREATE TABLE accelerate_event_subscriptions (name text PRIMARY KEY, revision bigint NOT NULL, state jsonb NOT NULL)",
18
+ ],
19
+ };
20
+ export function createPostgresEventJournal(db) {
21
+ return createEventJournal({
22
+ async append(event) {
23
+ await db.query(`INSERT INTO accelerate_events (id,type,payload,occurred_at,schema_version,correlation_id,causation_id)
24
+ VALUES ($1,$2,$3::jsonb,$4,$5,$6,$7) ON CONFLICT (id) DO NOTHING`, [
25
+ event.id,
26
+ event.type,
27
+ JSON.stringify(event.payload),
28
+ event.occurredAt,
29
+ event.schemaVersion,
30
+ event.correlationId ?? null,
31
+ event.causationId ?? null,
32
+ ]);
33
+ },
34
+ async read(after, limit) {
35
+ const { rows } = await db.query("SELECT cursor,id,type,payload,occurred_at,schema_version,correlation_id,causation_id FROM accelerate_events WHERE cursor>$1 ORDER BY cursor LIMIT $2", [after, limit]);
36
+ return rows.map((row) => ({
37
+ cursor: Number(row.cursor),
38
+ event: {
39
+ id: row.id,
40
+ type: row.type,
41
+ payload: row.payload,
42
+ occurredAt: new Date(row.occurred_at).toISOString(),
43
+ schemaVersion: row.schema_version,
44
+ ...(row.correlation_id !== null && {
45
+ correlationId: row.correlation_id,
46
+ }),
47
+ ...(row.causation_id !== null && { causationId: row.causation_id }),
48
+ },
49
+ }));
50
+ },
51
+ async load(name) {
52
+ const { rows: [row], } = await db.query(`SELECT floor(extract(epoch from clock_timestamp())*1000)::bigint AS now,s.revision,s.state
53
+ FROM (VALUES (1)) AS anchor(i) LEFT JOIN accelerate_event_subscriptions s ON s.name=$1`, [name]);
54
+ return {
55
+ now: Number(row.now),
56
+ revision: Number(row.revision ?? 0),
57
+ state: row.state ?? initialSubscription(),
58
+ };
59
+ },
60
+ async swap(name, revision, state, deadline) {
61
+ return db.transaction(async (tx) => {
62
+ if (revision === 0)
63
+ await tx.query("INSERT INTO accelerate_event_subscriptions VALUES ($1,0,$2::jsonb) ON CONFLICT DO NOTHING", [name, JSON.stringify(initialSubscription())]);
64
+ // Lock before evaluating the time fence, including after waiting for a competing worker.
65
+ await tx.query("SELECT name FROM accelerate_event_subscriptions WHERE name=$1 FOR UPDATE", [name]);
66
+ const result = await tx.query(`UPDATE accelerate_event_subscriptions SET revision=revision+1,state=$3::jsonb
67
+ WHERE name=$1 AND revision=$2 AND ($4::bigint IS NULL OR extract(epoch from clock_timestamp())*1000<$4)`, [name, revision, JSON.stringify(state), deadline ?? null]);
68
+ return result.rowCount === 1;
69
+ }, { isolationLevel: "read committed" });
70
+ },
71
+ });
72
+ }
@@ -0,0 +1 @@
1
+ export declare const EVENTS_SCHEMA = "CREATE TABLE IF NOT EXISTS accelerate_events (id text PRIMARY KEY, type text NOT NULL, payload jsonb NOT NULL, occurred_at timestamptz NOT NULL)";
@@ -0,0 +1 @@
1
+ export const EVENTS_SCHEMA = "CREATE TABLE IF NOT EXISTS accelerate_events (id text PRIMARY KEY, type text NOT NULL, payload jsonb NOT NULL, occurred_at timestamptz NOT NULL)";
@@ -0,0 +1,15 @@
1
+ import type { DomainEvent, EventBus, EventHandler } from "../../events-core/dist/index.js";
2
+ export interface RedisEventBridge {
3
+ publish(channel: string, message: string): Promise<unknown>;
4
+ subscribe(channel: string, listener: (message: string) => void): () => void;
5
+ }
6
+ export declare class RedisEventBus implements EventBus {
7
+ private readonly bridge;
8
+ private readonly namespace;
9
+ private readonly onError;
10
+ constructor(bridge: RedisEventBridge, namespace: string, onError: (error: unknown) => void);
11
+ private channel;
12
+ publish<T>(event: DomainEvent<T>): Promise<void>;
13
+ subscribe<T>(type: string, handler: EventHandler<T>): () => void;
14
+ }
15
+ export * from "./journal.js";
@@ -0,0 +1,15 @@
1
+ export class RedisEventBus {
2
+ constructor(bridge, namespace, onError) {
3
+ this.bridge = bridge;
4
+ this.namespace = namespace;
5
+ this.onError = onError;
6
+ if (!namespace.trim())
7
+ throw new Error("Namespace required");
8
+ }
9
+ channel(type) { if (!type.trim())
10
+ throw new Error("Event type required"); return this.namespace + ":" + type; }
11
+ async publish(event) { await this.bridge.publish(this.channel(event.type), JSON.stringify(event)); }
12
+ subscribe(type, handler) { return this.bridge.subscribe(this.channel(type), message => { void Promise.resolve().then(() => { const event = JSON.parse(message); if (!event || event.type !== type || typeof event.id !== "string" || typeof event.occurredAt !== "string")
13
+ throw new Error("Invalid event"); return handler(event); }).catch(this.onError); }); }
14
+ }
15
+ export * from "./journal.js";
@@ -0,0 +1,25 @@
1
+ import { type JournalEvent } from "../../events-core/dist/index.js";
2
+ /** Inject the node-redis EVAL signature or bridge an equivalent client. */
3
+ export interface RedisJournalClient {
4
+ eval(script: string, options: {
5
+ keys: string[];
6
+ arguments: string[];
7
+ }): Promise<unknown>;
8
+ }
9
+ export declare function createRedisEventJournal(client: RedisJournalClient, namespace: string): {
10
+ append: (event: import("../../events-core/dist/index.js").DomainEvent & Partial<JournalEvent>) => Promise<void>;
11
+ replay(after?: number, limit?: number): Promise<import("../../events-core/dist/index.js").JournalRecord[]>;
12
+ inspect(name: string): Promise<{
13
+ checkpoint: number;
14
+ attempt: number;
15
+ availableAt: number;
16
+ deadCursor: number | null;
17
+ }>;
18
+ claim(name: string, leaseMs: number): Promise<import("../../events-core/dist/index.js").Delivery | undefined>;
19
+ ack: (receipt: import("../../events-core/dist/index.js").Receipt) => Promise<boolean>;
20
+ nack(receipt: import("../../events-core/dist/index.js").Receipt, options: {
21
+ maxAttempts: number;
22
+ delayMs: number;
23
+ }): Promise<boolean>;
24
+ redrive(name: string, cursor: number): Promise<boolean>;
25
+ };
@@ -0,0 +1,45 @@
1
+ import { createEventJournal, initialSubscription, } from "../../events-core/dist/index.js";
2
+ const time = "local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000); ";
3
+ export function createRedisEventJournal(client, namespace) {
4
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(namespace))
5
+ throw new TypeError("Invalid journal namespace");
6
+ const prefix = "accelerate:events:{" + namespace + "}:";
7
+ const call = (script, keys, args) => client.eval(script, { keys: keys.map((k) => prefix + k), arguments: args });
8
+ return createEventJournal({
9
+ async append(event) {
10
+ await call(`if redis.call('HEXISTS',KEYS[1],ARGV[1])==0 then
11
+ redis.call('RPUSH',KEYS[2],ARGV[2]); redis.call('HSET',KEYS[1],ARGV[1],'1'); end; return 1`, ["ids", "log"], [event.id, JSON.stringify(event)]);
12
+ },
13
+ async read(after, limit) {
14
+ const rows = (await call("return redis.call('LRANGE',KEYS[1],ARGV[1],ARGV[2])", ["log"], [
15
+ String(after),
16
+ String(Math.min(Number.MAX_SAFE_INTEGER, after + limit - 1)),
17
+ ]));
18
+ return rows.map((row, i) => ({
19
+ cursor: after + i + 1,
20
+ event: JSON.parse(row),
21
+ }));
22
+ },
23
+ async load(name) {
24
+ const [revision, data, now] = (await call(time +
25
+ "return {redis.call('HGET',KEYS[1],'revision') or '0',redis.call('HGET',KEYS[1],'state') or '',now}", ["sub:" + name], []));
26
+ return {
27
+ now,
28
+ revision: Number(revision),
29
+ state: data
30
+ ? JSON.parse(data)
31
+ : initialSubscription(),
32
+ };
33
+ },
34
+ async swap(name, revision, state, deadline) {
35
+ return (Number(await call(time +
36
+ `if (redis.call('HGET',KEYS[1],'revision') or '0')~=ARGV[1]
37
+ or (ARGV[3]~='' and now>=tonumber(ARGV[3])) then return 0 end
38
+ redis.call('HSET',KEYS[1],'state',ARGV[2]); redis.call('HINCRBY',KEYS[1],'revision',1); return 1`, ["sub:" + name], [
39
+ String(revision),
40
+ JSON.stringify(state),
41
+ deadline === undefined ? "" : String(deadline),
42
+ ])) === 1);
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,21 @@
1
+ /** Durable-job adapter contracts; persistence is provided by integrations. */
2
+ export interface Job<T = unknown> {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ readonly payload: T;
6
+ readonly attempts: number;
7
+ readonly createdAt: string;
8
+ }
9
+ export type JobHandler<T> = (job: Job<T>, signal: AbortSignal) => Promise<void>;
10
+ export interface JobQueue {
11
+ enqueue<T>(name: string, payload: T, options?: {
12
+ id?: string;
13
+ delayMs?: number;
14
+ }): Promise<string>;
15
+ }
16
+ export interface JobWorker {
17
+ register<T>(name: string, handler: JobHandler<T>): () => void;
18
+ start(): Promise<void>;
19
+ stop(): Promise<void>;
20
+ }
21
+ export declare function validateJob(job: Job): void;
@@ -0,0 +1,2 @@
1
+ export function validateJob(job) { if (!job.id || !job.name || !Number.isInteger(job.attempts) || job.attempts < 0)
2
+ throw new Error('Invalid job'); }
@@ -0,0 +1,20 @@
1
+ import type { Job, JobQueue, JobWorker } from "../../jobs-core/dist/index.js";
2
+ import type { Database } from "@accelerate/data/core";
3
+ export declare const JOBS_SCHEMA = "CREATE TABLE IF NOT EXISTS accelerate_jobs (\n id text PRIMARY KEY,\n name text NOT NULL,\n payload jsonb NOT NULL,\n attempts integer NOT NULL DEFAULT 0,\n created_at timestamptz NOT NULL DEFAULT now(),\n available_at timestamptz NOT NULL DEFAULT now(),\n status text NOT NULL DEFAULT 'pending',\n locked_by text,\n locked_until timestamptz,\n last_error text\n);\nCREATE INDEX IF NOT EXISTS accelerate_jobs_ready_idx ON accelerate_jobs (available_at, created_at) WHERE status = 'pending';";
4
+ type Queryable = Pick<Database, "query">;
5
+ export interface PostgresJobWorkerOptions {
6
+ workerId: string;
7
+ pollIntervalMs?: number;
8
+ leaseMs?: number;
9
+ heartbeatMs?: number;
10
+ maxAttempts?: number;
11
+ retryDelayMs?: number;
12
+ onError?: (error: unknown, job: Job) => void;
13
+ }
14
+ export declare function createPostgresJobQueue(db: Queryable, idFactory?: () => string): JobQueue;
15
+ /** Polling worker with atomic claims, leases and bounded retries.
16
+ * Run migrations before starting. Handlers must be idempotent: a crashed worker
17
+ * can be retried after its lease expires, yielding at-least-once delivery.
18
+ */
19
+ export declare function createPostgresJobWorker(db: Queryable, options: PostgresJobWorkerOptions): JobWorker;
20
+ export {};