@shware/workflow 3.0.0 → 3.2.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 +16 -4
- package/dist/aws/engine-step.cjs +2 -3
- package/dist/aws/engine-step.cjs.map +1 -1
- package/dist/aws/engine-step.d.cts +10 -0
- package/dist/aws/engine-step.d.cts.map +1 -1
- package/dist/aws/engine-step.d.mts +10 -0
- package/dist/aws/engine-step.d.mts.map +1 -1
- package/dist/aws/engine-step.mjs +2 -3
- package/dist/aws/engine-step.mjs.map +1 -1
- package/dist/aws/index.cjs +14 -6
- package/dist/aws/index.cjs.map +1 -1
- package/dist/aws/index.d.cts +12 -0
- package/dist/aws/index.d.cts.map +1 -1
- package/dist/aws/index.d.mts +12 -0
- package/dist/aws/index.d.mts.map +1 -1
- package/dist/aws/index.mjs +14 -6
- package/dist/aws/index.mjs.map +1 -1
- package/dist/aws/instances.cjs +29 -9
- package/dist/aws/instances.cjs.map +1 -1
- package/dist/aws/instances.d.cts +24 -5
- package/dist/aws/instances.d.cts.map +1 -1
- package/dist/aws/instances.d.mts +24 -5
- package/dist/aws/instances.d.mts.map +1 -1
- package/dist/aws/instances.mjs +29 -9
- package/dist/aws/instances.mjs.map +1 -1
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +2 -0
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +2 -0
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/runner.cjs +4 -5
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +4 -5
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/engine/duration.cjs +34 -0
- package/dist/engine/duration.cjs.map +1 -0
- package/dist/engine/duration.d.cts +5 -0
- package/dist/engine/duration.d.cts.map +1 -0
- package/dist/engine/duration.d.mts +5 -0
- package/dist/engine/duration.d.mts.map +1 -0
- package/dist/engine/duration.mjs +33 -0
- package/dist/engine/duration.mjs.map +1 -0
- package/dist/engine/index.cjs +5 -0
- package/dist/engine/index.d.cts +3 -1
- package/dist/engine/index.d.mts +3 -1
- package/dist/engine/index.mjs +3 -1
- package/dist/engine/retry.cjs +29 -0
- package/dist/engine/retry.cjs.map +1 -0
- package/dist/engine/retry.d.cts +17 -0
- package/dist/engine/retry.d.cts.map +1 -0
- package/dist/engine/retry.d.mts +17 -0
- package/dist/engine/retry.d.mts.map +1 -0
- package/dist/engine/retry.mjs +27 -0
- package/dist/engine/retry.mjs.map +1 -0
- package/dist/host/execute.cjs +6 -7
- package/dist/host/execute.cjs.map +1 -1
- package/dist/host/execute.d.cts +0 -4
- package/dist/host/execute.d.cts.map +1 -1
- package/dist/host/execute.d.mts +0 -4
- package/dist/host/execute.d.mts.map +1 -1
- package/dist/host/execute.mjs +6 -7
- package/dist/host/execute.mjs.map +1 -1
- package/dist/host/journey-host.cjs +15 -0
- package/dist/host/journey-host.cjs.map +1 -1
- package/dist/host/journey-host.d.cts.map +1 -1
- package/dist/host/journey-host.d.mts.map +1 -1
- package/dist/host/journey-host.mjs +15 -0
- package/dist/host/journey-host.mjs.map +1 -1
- package/dist/host/router.cjs +7 -5
- package/dist/host/router.cjs.map +1 -1
- package/dist/host/router.d.cts.map +1 -1
- package/dist/host/router.d.mts.map +1 -1
- package/dist/host/router.mjs +7 -5
- package/dist/host/router.mjs.map +1 -1
- package/dist/http2-client.cjs +7 -5
- package/dist/http2-client.cjs.map +1 -1
- package/dist/http2-client.d.cts +5 -2
- package/dist/http2-client.d.cts.map +1 -1
- package/dist/http2-client.d.mts +5 -2
- package/dist/http2-client.d.mts.map +1 -1
- package/dist/http2-client.mjs +7 -5
- package/dist/http2-client.mjs.map +1 -1
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +11 -0
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +11 -0
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres.cjs +37 -13
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +6 -0
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +6 -0
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +37 -13
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +6 -3
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +6 -3
- package/dist/store/tables.mjs.map +1 -1
- package/dist/transports/cloudflare-email.cjs +4 -0
- package/dist/transports/cloudflare-email.cjs.map +1 -1
- package/dist/transports/cloudflare-email.d.cts +2 -0
- package/dist/transports/cloudflare-email.d.cts.map +1 -1
- package/dist/transports/cloudflare-email.d.mts +2 -0
- package/dist/transports/cloudflare-email.d.mts.map +1 -1
- package/dist/transports/cloudflare-email.mjs +4 -0
- package/dist/transports/cloudflare-email.mjs.map +1 -1
- package/dist/transports/ses.cjs +4 -0
- package/dist/transports/ses.cjs.map +1 -1
- package/dist/transports/ses.d.cts +2 -0
- package/dist/transports/ses.d.cts.map +1 -1
- package/dist/transports/ses.d.mts +2 -0
- package/dist/transports/ses.d.mts.map +1 -1
- package/dist/transports/ses.mjs +4 -0
- package/dist/transports/ses.mjs.map +1 -1
- package/dist/transports/sigv4.cjs +6 -1
- package/dist/transports/sigv4.cjs.map +1 -1
- package/dist/transports/sigv4.d.cts.map +1 -1
- package/dist/transports/sigv4.d.mts.map +1 -1
- package/dist/transports/sigv4.mjs +6 -1
- package/dist/transports/sigv4.mjs.map +1 -1
- package/package.json +1 -1
package/dist/http2-client.d.cts
CHANGED
|
@@ -22,8 +22,11 @@ import { ClientHttp2Session } from "node:http2";
|
|
|
22
22
|
*/
|
|
23
23
|
export interface Http2Sessions {
|
|
24
24
|
session(origin: string): ClientHttp2Session;
|
|
25
|
-
/**
|
|
26
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Drop a session that stopped answering, so the next request reconnects. Only that session:
|
|
27
|
+
* the pool may already hold a newer one for the origin (after a GOAWAY), which stays.
|
|
28
|
+
*/
|
|
29
|
+
discard(origin: string, session: ClientHttp2Session): void;
|
|
27
30
|
close(): void;
|
|
28
31
|
}
|
|
29
32
|
export declare function http2Sessions(): Http2Sessions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http2-client.d.cts","names":[],"sources":["../src/http2-client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAuBiB;EACf,QAAQ,iBAAiB
|
|
1
|
+
{"version":3,"file":"http2-client.d.cts","names":[],"sources":["../src/http2-client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAuBiB;EACf,QAAQ,iBAAiB;;;;;EAKzB,QAAQ,gBAAgB,SAAS;EACjC;;wBAGc,iBAAiB;;;;;;wBAgCjB,WACd,OAAM,eACN;;;;;;EAME;WAEM"}
|
package/dist/http2-client.d.mts
CHANGED
|
@@ -22,8 +22,11 @@ import { ClientHttp2Session } from "node:http2";
|
|
|
22
22
|
*/
|
|
23
23
|
export interface Http2Sessions {
|
|
24
24
|
session(origin: string): ClientHttp2Session;
|
|
25
|
-
/**
|
|
26
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Drop a session that stopped answering, so the next request reconnects. Only that session:
|
|
27
|
+
* the pool may already hold a newer one for the origin (after a GOAWAY), which stays.
|
|
28
|
+
*/
|
|
29
|
+
discard(origin: string, session: ClientHttp2Session): void;
|
|
27
30
|
close(): void;
|
|
28
31
|
}
|
|
29
32
|
export declare function http2Sessions(): Http2Sessions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http2-client.d.mts","names":[],"sources":["../src/http2-client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAuBiB;EACf,QAAQ,iBAAiB
|
|
1
|
+
{"version":3,"file":"http2-client.d.mts","names":[],"sources":["../src/http2-client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAuBiB;EACf,QAAQ,iBAAiB;;;;;EAKzB,QAAQ,gBAAgB,SAAS;EACjC;;wBAGc,iBAAiB;;;;;;wBAgCjB,WACd,OAAM,eACN;;;;;;EAME;WAEM"}
|
package/dist/http2-client.mjs
CHANGED
|
@@ -16,9 +16,9 @@ function http2Sessions() {
|
|
|
16
16
|
sessions.set(origin, created);
|
|
17
17
|
return created;
|
|
18
18
|
},
|
|
19
|
-
discard(origin) {
|
|
20
|
-
|
|
21
|
-
sessions.delete(origin);
|
|
19
|
+
discard(origin, session) {
|
|
20
|
+
session.destroy();
|
|
21
|
+
if (sessions.get(origin) === session) sessions.delete(origin);
|
|
22
22
|
},
|
|
23
23
|
close() {
|
|
24
24
|
for (const open of sessions.values()) open.close();
|
|
@@ -45,9 +45,11 @@ function http2Fetch(pool = http2Sessions(), options = {}) {
|
|
|
45
45
|
headers[name] = value;
|
|
46
46
|
});
|
|
47
47
|
return new Promise((resolve, reject) => {
|
|
48
|
+
let session;
|
|
48
49
|
let stream;
|
|
49
50
|
try {
|
|
50
|
-
|
|
51
|
+
session = pool.session(url.origin);
|
|
52
|
+
stream = session.request(headers);
|
|
51
53
|
} catch (error) {
|
|
52
54
|
reject(error instanceof Error ? error : new Error(String(error)));
|
|
53
55
|
return;
|
|
@@ -73,7 +75,7 @@ function http2Fetch(pool = http2Sessions(), options = {}) {
|
|
|
73
75
|
stream.on("error", reject);
|
|
74
76
|
stream.setTimeout(timeoutMs, () => {
|
|
75
77
|
stream.close();
|
|
76
|
-
pool.discard(url.origin);
|
|
78
|
+
pool.discard(url.origin, session);
|
|
77
79
|
reject(/* @__PURE__ */ new Error(`HTTP/2 request to ${url.origin} timed out after ${timeoutMs} ms`));
|
|
78
80
|
});
|
|
79
81
|
stream.end(body);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http2-client.mjs","names":[],"sources":["../src/http2-client.ts"],"sourcesContent":["import { type ClientHttp2Session, connect } from 'node:http2';\n\n/**\n * A Node HTTP/2 client: one session per origin, reused while it lives. APNs speaks HTTP/2 only\n * and Node's `fetch` does not negotiate it, so a Node host (a Lambda, the development relay)\n * pushes through this instead. Node-only — a Worker's own `fetch` already speaks HTTP/2.\n *\n * Why it exists, and when the Lambda side can go (as of 2026-10):\n * - Node 24 (Lambda's `nodejs24.x`, the newest GA runtime) bundles undici 7, whose `fetch`\n * leaves HTTP/2 off (`allowH2: false`). A POST to APNs fails there with \"Response does not\n * match the HTTP/1.1 protocol\". The only switch is an undici `Agent({ allowH2: true })`\n * dispatcher, which needs the npm `undici` package (and, set globally, would change every\n * `fetch` in the host's process) — this client needs no dependency and touches nothing global.\n * - undici 8 negotiates HTTP/2 by default (nodejs/undici#4828), and Node 26 bundles it. Lambda's\n * `nodejs26.x` is in public preview only, outside the SLA; it goes GA once Node 26 reaches\n * Active LTS.\n * - Once the function runs on a GA runtime whose built-in `fetch` speaks HTTP/2 (check that\n * durable functions support it, and that a POST to api.push.apple.com answers JSON rather\n * than a protocol error), drop `apnsFetch: http2Fetch()` from `journeyLambda` (aws/index.ts):\n * APNs then uses the platform `fetch` like the other channels. The development relay\n * (`apns-relay.ts`, for workerd, which cannot make HTTP/2 subrequests) keeps using this pool.\n */\n\nexport interface Http2Sessions {\n session(origin: string): ClientHttp2Session;\n
|
|
1
|
+
{"version":3,"file":"http2-client.mjs","names":[],"sources":["../src/http2-client.ts"],"sourcesContent":["import { type ClientHttp2Session, connect } from 'node:http2';\n\n/**\n * A Node HTTP/2 client: one session per origin, reused while it lives. APNs speaks HTTP/2 only\n * and Node's `fetch` does not negotiate it, so a Node host (a Lambda, the development relay)\n * pushes through this instead. Node-only — a Worker's own `fetch` already speaks HTTP/2.\n *\n * Why it exists, and when the Lambda side can go (as of 2026-10):\n * - Node 24 (Lambda's `nodejs24.x`, the newest GA runtime) bundles undici 7, whose `fetch`\n * leaves HTTP/2 off (`allowH2: false`). A POST to APNs fails there with \"Response does not\n * match the HTTP/1.1 protocol\". The only switch is an undici `Agent({ allowH2: true })`\n * dispatcher, which needs the npm `undici` package (and, set globally, would change every\n * `fetch` in the host's process) — this client needs no dependency and touches nothing global.\n * - undici 8 negotiates HTTP/2 by default (nodejs/undici#4828), and Node 26 bundles it. Lambda's\n * `nodejs26.x` is in public preview only, outside the SLA; it goes GA once Node 26 reaches\n * Active LTS.\n * - Once the function runs on a GA runtime whose built-in `fetch` speaks HTTP/2 (check that\n * durable functions support it, and that a POST to api.push.apple.com answers JSON rather\n * than a protocol error), drop `apnsFetch: http2Fetch()` from `journeyLambda` (aws/index.ts):\n * APNs then uses the platform `fetch` like the other channels. The development relay\n * (`apns-relay.ts`, for workerd, which cannot make HTTP/2 subrequests) keeps using this pool.\n */\n\nexport interface Http2Sessions {\n session(origin: string): ClientHttp2Session;\n /**\n * Drop a session that stopped answering, so the next request reconnects. Only that session:\n * the pool may already hold a newer one for the origin (after a GOAWAY), which stays.\n */\n discard(origin: string, session: ClientHttp2Session): void;\n close(): void;\n}\n\nexport function http2Sessions(): Http2Sessions {\n const sessions = new Map<string, ClientHttp2Session>();\n return {\n session(origin) {\n const existing = sessions.get(origin);\n if (existing !== undefined && !existing.closed && !existing.destroyed) return existing;\n const created = connect(origin);\n const forget = () => {\n if (sessions.get(origin) === created) sessions.delete(origin);\n };\n created.on('error', forget);\n created.on('close', forget);\n created.on('goaway', forget);\n sessions.set(origin, created);\n return created;\n },\n discard(origin, session) {\n session.destroy();\n if (sessions.get(origin) === session) sessions.delete(origin);\n },\n close() {\n for (const open of sessions.values()) open.close();\n sessions.clear();\n },\n };\n}\n\n/**\n * `fetch` over HTTP/2, for the senders that take one (`ApnsPushSender({ fetch })`). Only what a\n * JSON API call needs: a method, string headers, a string or byte body, the status, headers and\n * body back.\n */\nexport function http2Fetch(\n pool: Http2Sessions = http2Sessions(),\n options: {\n /**\n * How long a request may go without activity: a session a frozen Lambda left half-dead\n * answers nothing and closes nothing, so without a limit the request hangs until the\n * function's timeout. 10 seconds by default.\n */\n timeoutMs?: number;\n } = {}\n): typeof fetch {\n const timeoutMs = options.timeoutMs ?? 10_000;\n return async (input: string | URL | Request, init?: RequestInit) => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n const body = request.body === null ? undefined : Buffer.from(await request.arrayBuffer());\n const headers: Record<string, string> = {\n ':method': request.method,\n ':path': `${url.pathname}${url.search}`,\n };\n request.headers.forEach((value, name) => {\n headers[name] = value;\n });\n return new Promise<Response>((resolve, reject) => {\n let session: ClientHttp2Session;\n let stream;\n try {\n session = pool.session(url.origin);\n stream = session.request(headers);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n let status = 502;\n const responseHeaders = new Headers();\n const chunks: Buffer[] = [];\n stream.on('response', (received) => {\n status = received[':status'] ?? 502;\n for (const [name, value] of Object.entries(received)) {\n if (name.startsWith(':') || value === undefined) continue;\n responseHeaders.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n });\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n stream.on('end', () => {\n const bytes = Buffer.concat(chunks);\n resolve(\n new Response(status === 204 || status === 304 || bytes.length === 0 ? null : bytes, {\n status,\n headers: responseHeaders,\n })\n );\n });\n stream.on('error', reject);\n stream.setTimeout(timeoutMs, () => {\n stream.close();\n pool.discard(url.origin, session);\n reject(new Error(`HTTP/2 request to ${url.origin} timed out after ${timeoutMs} ms`));\n });\n stream.end(body);\n });\n };\n}\n"],"mappings":";;AAiCA,SAAgB,gBAA+B;CAC7C,MAAM,2BAAW,IAAI,IAAgC;CACrD,OAAO;EACL,QAAQ,QAAQ;GACd,MAAM,WAAW,SAAS,IAAI,MAAM;GACpC,IAAI,aAAa,KAAA,KAAa,CAAC,SAAS,UAAU,CAAC,SAAS,WAAW,OAAO;GAC9E,MAAM,UAAU,QAAQ,MAAM;GAC9B,MAAM,eAAe;IACnB,IAAI,SAAS,IAAI,MAAM,MAAM,SAAS,SAAS,OAAO,MAAM;GAC9D;GACA,QAAQ,GAAG,SAAS,MAAM;GAC1B,QAAQ,GAAG,SAAS,MAAM;GAC1B,QAAQ,GAAG,UAAU,MAAM;GAC3B,SAAS,IAAI,QAAQ,OAAO;GAC5B,OAAO;EACT;EACA,QAAQ,QAAQ,SAAS;GACvB,QAAQ,QAAQ;GAChB,IAAI,SAAS,IAAI,MAAM,MAAM,SAAS,SAAS,OAAO,MAAM;EAC9D;EACA,QAAQ;GACN,KAAK,MAAM,QAAQ,SAAS,OAAO,GAAG,KAAK,MAAM;GACjD,SAAS,MAAM;EACjB;CACF;AACF;;;;;;AAOA,SAAgB,WACd,OAAsB,cAAc,GACpC,UAOI,CAAC,GACS;CACd,MAAM,YAAY,QAAQ,aAAa;CACvC,OAAO,OAAO,OAA+B,SAAuB;EAClE,MAAM,UAAU,IAAI,QAAQ,OAAO,IAAI;EACvC,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,MAAM,OAAO,QAAQ,SAAS,OAAO,KAAA,IAAY,OAAO,KAAK,MAAM,QAAQ,YAAY,CAAC;EACxF,MAAM,UAAkC;GACtC,WAAW,QAAQ;GACnB,SAAS,GAAG,IAAI,WAAW,IAAI;EACjC;EACA,QAAQ,QAAQ,SAAS,OAAO,SAAS;GACvC,QAAQ,QAAQ;EAClB,CAAC;EACD,OAAO,IAAI,SAAmB,SAAS,WAAW;GAChD,IAAI;GACJ,IAAI;GACJ,IAAI;IACF,UAAU,KAAK,QAAQ,IAAI,MAAM;IACjC,SAAS,QAAQ,QAAQ,OAAO;GAClC,SAAS,OAAO;IACd,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;IAChE;GACF;GACA,IAAI,SAAS;GACb,MAAM,kBAAkB,IAAI,QAAQ;GACpC,MAAM,SAAmB,CAAC;GAC1B,OAAO,GAAG,aAAa,aAAa;IAClC,SAAS,SAAS,cAAc;IAChC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,GAAG;KACpD,IAAI,KAAK,WAAW,GAAG,KAAK,UAAU,KAAA,GAAW;KACjD,gBAAgB,IAAI,MAAM,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK,IAAI,IAAI,KAAK;IAC3E;GACF,CAAC;GACD,OAAO,GAAG,SAAS,UAAkB,OAAO,KAAK,KAAK,CAAC;GACvD,OAAO,GAAG,aAAa;IACrB,MAAM,QAAQ,OAAO,OAAO,MAAM;IAClC,QACE,IAAI,SAAS,WAAW,OAAO,WAAW,OAAO,MAAM,WAAW,IAAI,OAAO,OAAO;KAClF;KACA,SAAS;IACX,CAAC,CACH;GACF,CAAC;GACD,OAAO,GAAG,SAAS,MAAM;GACzB,OAAO,WAAW,iBAAiB;IACjC,OAAO,MAAM;IACb,KAAK,QAAQ,IAAI,QAAQ,OAAO;IAChC,uBAAO,IAAI,MAAM,qBAAqB,IAAI,OAAO,mBAAmB,UAAU,IAAI,CAAC;GACrF,CAAC;GACD,OAAO,IAAI,IAAI;EACjB,CAAC;CACH;AACF"}
|
package/dist/store/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried. Only a store with\n * `executions` accepts it.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it. Stores without it (D1) leave every deploy to `POST /bundle/deploy`.\n */\n liveBundleVersion?(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer?(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that needs them (AWS); Postgres only. */\n readonly executions?: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AAyJA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy, or on a store that keeps none. Read in the same row as the hash, so the pair is\n * always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried. Only a store with\n * `executions` accepts it.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it. Stores without it (D1) leave every deploy to `POST /bundle/deploy`.\n */\n liveBundleVersion?(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer?(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that needs them (AWS); Postgres only. */\n readonly executions?: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AAoKA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|
package/dist/store/index.d.cts
CHANGED
|
@@ -39,11 +39,19 @@ export interface TriggerRoute {
|
|
|
39
39
|
where: ConditionIR | null;
|
|
40
40
|
/** Profile gate, or null. */
|
|
41
41
|
filter: ConditionIR | null;
|
|
42
|
+
/**
|
|
43
|
+
* The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced
|
|
44
|
+
* deploy, or on a store that keeps none. Read in the same row as the hash, so the pair is
|
|
45
|
+
* always one deploy's.
|
|
46
|
+
*/
|
|
47
|
+
version?: string | undefined;
|
|
42
48
|
}
|
|
43
49
|
export interface SegmentTriggerRoute {
|
|
44
50
|
workflow: string;
|
|
45
51
|
hash: string;
|
|
46
52
|
segment: string;
|
|
53
|
+
/** As `TriggerRoute.version`. */
|
|
54
|
+
version?: string | undefined;
|
|
47
55
|
}
|
|
48
56
|
/**
|
|
49
57
|
* A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into
|
|
@@ -89,6 +97,7 @@ export interface ExecutionRecord extends ExecutionStart {
|
|
|
89
97
|
generation: number;
|
|
90
98
|
deadlineAt?: number | undefined;
|
|
91
99
|
checkedAt?: number | undefined;
|
|
100
|
+
stoppedAt?: number | undefined;
|
|
92
101
|
}
|
|
93
102
|
/**
|
|
94
103
|
* What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps
|
|
@@ -121,6 +130,8 @@ export interface ExecutionRegistry {
|
|
|
121
130
|
/** Submitted executions whose entry is still running, least recently checked first. */
|
|
122
131
|
toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;
|
|
123
132
|
markChecked(instanceId: string, at: number): Promise<void>;
|
|
133
|
+
/** Record the first stop; a later one keeps it. */
|
|
134
|
+
markStopped(instanceId: string, at: number): Promise<void>;
|
|
124
135
|
}
|
|
125
136
|
/**
|
|
126
137
|
* How an entry attempt ended: a fresh row, a 'failed' row of a dead instance
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/store/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;YAoBY,eAAe,eAAe;iBAEzB;;EAEf;EACA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;EAEA,OAAO;;EAEP,QAAQ;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/store/index.ts"],"mappings":"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"}
|
package/dist/store/index.d.mts
CHANGED
|
@@ -39,11 +39,19 @@ export interface TriggerRoute {
|
|
|
39
39
|
where: ConditionIR | null;
|
|
40
40
|
/** Profile gate, or null. */
|
|
41
41
|
filter: ConditionIR | null;
|
|
42
|
+
/**
|
|
43
|
+
* The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced
|
|
44
|
+
* deploy, or on a store that keeps none. Read in the same row as the hash, so the pair is
|
|
45
|
+
* always one deploy's.
|
|
46
|
+
*/
|
|
47
|
+
version?: string | undefined;
|
|
42
48
|
}
|
|
43
49
|
export interface SegmentTriggerRoute {
|
|
44
50
|
workflow: string;
|
|
45
51
|
hash: string;
|
|
46
52
|
segment: string;
|
|
53
|
+
/** As `TriggerRoute.version`. */
|
|
54
|
+
version?: string | undefined;
|
|
47
55
|
}
|
|
48
56
|
/**
|
|
49
57
|
* A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into
|
|
@@ -89,6 +97,7 @@ export interface ExecutionRecord extends ExecutionStart {
|
|
|
89
97
|
generation: number;
|
|
90
98
|
deadlineAt?: number | undefined;
|
|
91
99
|
checkedAt?: number | undefined;
|
|
100
|
+
stoppedAt?: number | undefined;
|
|
92
101
|
}
|
|
93
102
|
/**
|
|
94
103
|
* What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps
|
|
@@ -121,6 +130,8 @@ export interface ExecutionRegistry {
|
|
|
121
130
|
/** Submitted executions whose entry is still running, least recently checked first. */
|
|
122
131
|
toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;
|
|
123
132
|
markChecked(instanceId: string, at: number): Promise<void>;
|
|
133
|
+
/** Record the first stop; a later one keeps it. */
|
|
134
|
+
markStopped(instanceId: string, at: number): Promise<void>;
|
|
124
135
|
}
|
|
125
136
|
/**
|
|
126
137
|
* How an entry attempt ended: a fresh row, a 'failed' row of a dead instance
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/store/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;YAoBY,eAAe,eAAe;iBAEzB;;EAEf;EACA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;EAEA,OAAO;;EAEP,QAAQ;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/store/index.ts"],"mappings":"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"}
|
package/dist/store/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried. Only a store with\n * `executions` accepts it.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it. Stores without it (D1) leave every deploy to `POST /bundle/deploy`.\n */\n liveBundleVersion?(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer?(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that needs them (AWS); Postgres only. */\n readonly executions?: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;AAyJA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy, or on a store that keeps none. Read in the same row as the hash, so the pair is\n * always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried. Only a store with\n * `executions` accepts it.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it. Stores without it (D1) leave every deploy to `POST /bundle/deploy`.\n */\n liveBundleVersion?(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer?(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that needs them (AWS); Postgres only. */\n readonly executions?: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;AAoKA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|
package/dist/store/postgres.cjs
CHANGED
|
@@ -187,15 +187,21 @@ var PostgresJourneyStore = class {
|
|
|
187
187
|
return row === void 0 ? void 0 : require_ir.ConditionIR.parse(asJson(row.condition));
|
|
188
188
|
}
|
|
189
189
|
async findTriggers(event) {
|
|
190
|
-
return (await this.sql.query(`SELECT workflow, hash, "where" AS where_clause, filter FROM ${this.t.trigger} WHERE event = $1`, [event])).map((row) => ({
|
|
190
|
+
return (await this.sql.query(`SELECT workflow, hash, "where" AS where_clause, filter, version FROM ${this.t.trigger} WHERE event = $1`, [event])).map((row) => ({
|
|
191
191
|
workflow: row.workflow,
|
|
192
192
|
hash: row.hash,
|
|
193
193
|
where: row.where_clause === null ? null : require_ir.ConditionIR.parse(asJson(row.where_clause)),
|
|
194
|
-
filter: row.filter === null ? null : require_ir.ConditionIR.parse(asJson(row.filter))
|
|
194
|
+
filter: row.filter === null ? null : require_ir.ConditionIR.parse(asJson(row.filter)),
|
|
195
|
+
version: row.version ?? void 0
|
|
195
196
|
}));
|
|
196
197
|
}
|
|
197
|
-
listSegmentTriggers() {
|
|
198
|
-
return this.sql.query(`SELECT workflow, hash, segment FROM ${this.t.segmentTrigger}`)
|
|
198
|
+
async listSegmentTriggers() {
|
|
199
|
+
return (await this.sql.query(`SELECT workflow, hash, segment, version FROM ${this.t.segmentTrigger}`)).map((row) => ({
|
|
200
|
+
workflow: row.workflow,
|
|
201
|
+
hash: row.hash,
|
|
202
|
+
segment: row.segment,
|
|
203
|
+
version: row.version ?? void 0
|
|
204
|
+
}));
|
|
199
205
|
}
|
|
200
206
|
async putWorkflowIR(workflow) {
|
|
201
207
|
await this.sql.query(`INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)
|
|
@@ -228,11 +234,12 @@ var PostgresJourneyStore = class {
|
|
|
228
234
|
version.createdAt,
|
|
229
235
|
Date.now()
|
|
230
236
|
])).length === 0) return false;
|
|
231
|
-
await this.swapRoutes(tx, bundle);
|
|
237
|
+
await this.swapRoutes(tx, bundle, version.id);
|
|
232
238
|
return true;
|
|
233
239
|
});
|
|
234
240
|
}
|
|
235
|
-
|
|
241
|
+
/** `version`: the code version applying the bundle, kept on every route it writes. */
|
|
242
|
+
async swapRoutes(tx, bundle, version) {
|
|
236
243
|
await tx.query(`DELETE FROM ${this.t.trigger}`);
|
|
237
244
|
await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);
|
|
238
245
|
await tx.query(`DELETE FROM ${this.t.segment}`);
|
|
@@ -241,17 +248,19 @@ var PostgresJourneyStore = class {
|
|
|
241
248
|
JSON.stringify(segment.condition),
|
|
242
249
|
segment.contentHash
|
|
243
250
|
]);
|
|
244
|
-
for (const workflow of bundle.workflows) if (workflow.trigger.type === "event") await tx.query(`INSERT INTO ${this.t.trigger} (workflow, hash, event, "where", filter) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb)`, [
|
|
251
|
+
for (const workflow of bundle.workflows) if (workflow.trigger.type === "event") await tx.query(`INSERT INTO ${this.t.trigger} (workflow, hash, event, "where", filter, version) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6)`, [
|
|
245
252
|
workflow.id,
|
|
246
253
|
workflow.contentHash,
|
|
247
254
|
workflow.trigger.event,
|
|
248
255
|
workflow.trigger.where === void 0 ? null : JSON.stringify(workflow.trigger.where),
|
|
249
|
-
workflow.trigger.filter === void 0 ? null : JSON.stringify(workflow.trigger.filter)
|
|
256
|
+
workflow.trigger.filter === void 0 ? null : JSON.stringify(workflow.trigger.filter),
|
|
257
|
+
version ?? null
|
|
250
258
|
]);
|
|
251
|
-
else if (workflow.trigger.type === "segment") await tx.query(`INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment) VALUES ($1, $2, $3)`, [
|
|
259
|
+
else if (workflow.trigger.type === "segment") await tx.query(`INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment, version) VALUES ($1, $2, $3, $4)`, [
|
|
252
260
|
workflow.id,
|
|
253
261
|
workflow.contentHash,
|
|
254
|
-
workflow.trigger.segment
|
|
262
|
+
workflow.trigger.segment,
|
|
263
|
+
version ?? null
|
|
255
264
|
]);
|
|
256
265
|
}
|
|
257
266
|
async isSegmentMember(segment, userId) {
|
|
@@ -317,9 +326,19 @@ var PostgresJourneyStore = class {
|
|
|
317
326
|
entry.userId
|
|
318
327
|
])).length > 0 ? "reclaimed" : null;
|
|
319
328
|
}
|
|
329
|
+
/**
|
|
330
|
+
* Only an entry this call claimed records a start, so a row already there is a previous
|
|
331
|
+
* attempt's — a failed entry reclaimed under the same instance id (an event replayed with its
|
|
332
|
+
* ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.
|
|
333
|
+
*/
|
|
320
334
|
async recordStart(tx, entry, execution) {
|
|
321
335
|
await tx.query(`INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)
|
|
322
|
-
VALUES ($1, $2, $3, $4, $5, $6, ${TS("$7")}, 0)
|
|
336
|
+
VALUES ($1, $2, $3, $4, $5, $6, ${TS("$7")}, 0)
|
|
337
|
+
ON CONFLICT (instance_id) DO UPDATE SET
|
|
338
|
+
name = EXCLUDED.name, target = EXCLUDED.target, input = EXCLUDED.input,
|
|
339
|
+
created_at = EXCLUDED.created_at, generation = 0, submitted_at = NULL, arn = NULL,
|
|
340
|
+
unresolved_at = NULL, callback_id = NULL, deadline_at = NULL, checked_at = NULL,
|
|
341
|
+
stopped_at = NULL`, [
|
|
323
342
|
entry.instanceId,
|
|
324
343
|
entry.workflow,
|
|
325
344
|
entry.userId,
|
|
@@ -365,7 +384,8 @@ const TIME_COLUMNS = [
|
|
|
365
384
|
"submitted_at",
|
|
366
385
|
"unresolved_at",
|
|
367
386
|
"deadline_at",
|
|
368
|
-
"checked_at"
|
|
387
|
+
"checked_at",
|
|
388
|
+
"stopped_at"
|
|
369
389
|
];
|
|
370
390
|
/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */
|
|
371
391
|
function executionColumns(alias = "") {
|
|
@@ -389,7 +409,8 @@ function toRecord(row) {
|
|
|
389
409
|
callbackId: optional(row.callback_id),
|
|
390
410
|
generation: Number(row.generation),
|
|
391
411
|
deadlineAt: ms(row.deadline_at),
|
|
392
|
-
checkedAt: ms(row.checked_at)
|
|
412
|
+
checkedAt: ms(row.checked_at),
|
|
413
|
+
stoppedAt: ms(row.stopped_at)
|
|
393
414
|
};
|
|
394
415
|
}
|
|
395
416
|
/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */
|
|
@@ -463,6 +484,9 @@ var PostgresExecutions = class {
|
|
|
463
484
|
AND (x.checked_at IS NULL OR x.checked_at < ${TS("$1")})
|
|
464
485
|
ORDER BY x.checked_at NULLS FIRST LIMIT $2`, [checkedBefore, limit])).map(toRecord);
|
|
465
486
|
}
|
|
487
|
+
async markStopped(instanceId, at) {
|
|
488
|
+
await this.sql.query(`UPDATE ${this.table} SET stopped_at = COALESCE(stopped_at, ${TS("$2")}) WHERE instance_id = $1`, [instanceId, at]);
|
|
489
|
+
}
|
|
466
490
|
async markChecked(instanceId, at) {
|
|
467
491
|
await this.sql.query(`UPDATE ${this.table} SET checked_at = ${TS("$2")} WHERE instance_id = $1`, [instanceId, at]);
|
|
468
492
|
}
|