@shware/workflow 3.3.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +230 -40
- package/dist/apns.cjs +113 -26
- package/dist/apns.cjs.map +1 -1
- package/dist/apns.d.cts +52 -6
- package/dist/apns.d.cts.map +1 -1
- package/dist/apns.d.mts +52 -6
- package/dist/apns.d.mts.map +1 -1
- package/dist/apns.mjs +111 -27
- package/dist/apns.mjs.map +1 -1
- package/dist/aws/engine-step.cjs +5 -5
- package/dist/aws/engine-step.cjs.map +1 -1
- package/dist/aws/engine-step.d.cts +8 -2
- package/dist/aws/engine-step.d.cts.map +1 -1
- package/dist/aws/engine-step.d.mts +8 -2
- package/dist/aws/engine-step.d.mts.map +1 -1
- package/dist/aws/engine-step.mjs +5 -5
- package/dist/aws/engine-step.mjs.map +1 -1
- package/dist/aws/index.cjs +50 -6
- package/dist/aws/index.cjs.map +1 -1
- package/dist/aws/index.d.cts +4 -3
- package/dist/aws/index.d.cts.map +1 -1
- package/dist/aws/index.d.mts +4 -3
- package/dist/aws/index.d.mts.map +1 -1
- package/dist/aws/index.mjs +49 -7
- package/dist/aws/index.mjs.map +1 -1
- package/dist/aws/instances.cjs +29 -6
- package/dist/aws/instances.cjs.map +1 -1
- package/dist/aws/instances.d.cts +11 -1
- package/dist/aws/instances.d.cts.map +1 -1
- package/dist/aws/instances.d.mts +11 -1
- package/dist/aws/instances.d.mts.map +1 -1
- package/dist/aws/instances.mjs +27 -4
- package/dist/aws/instances.mjs.map +1 -1
- package/dist/client.cjs +4 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.cts.map +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +4 -1
- package/dist/client.mjs.map +1 -1
- package/dist/cloudflare/bindings.cjs +28 -25
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +15 -129
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +15 -129
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs +28 -23
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/d1-env.cjs +6 -6
- package/dist/cloudflare/d1-env.cjs.map +1 -1
- package/dist/cloudflare/d1-env.d.cts +5 -5
- package/dist/cloudflare/d1-env.d.mts +5 -5
- package/dist/cloudflare/d1-env.mjs +6 -6
- package/dist/cloudflare/d1-env.mjs.map +1 -1
- package/dist/cloudflare/index.cjs +29 -18
- package/dist/cloudflare/index.d.cts +8 -4
- package/dist/cloudflare/index.d.mts +8 -4
- package/dist/cloudflare/index.mjs +9 -5
- package/dist/cloudflare/runner.cjs +29 -14
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts +9 -2
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts +9 -2
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +28 -13
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/cloudflare/schema.sql +27 -6
- package/dist/cloudflare/worker.cjs +19 -9
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts +2 -2
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts +2 -2
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +19 -9
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/config.cjs +21 -5
- package/dist/config.cjs.map +1 -1
- package/dist/config.mjs +21 -5
- package/dist/config.mjs.map +1 -1
- package/dist/dsl/action.cjs +3 -6
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +12 -11
- package/dist/dsl/action.d.cts.map +1 -1
- package/dist/dsl/action.d.mts +12 -11
- package/dist/dsl/action.d.mts.map +1 -1
- package/dist/dsl/action.mjs +3 -6
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs +35 -31
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts.map +1 -1
- package/dist/dsl/bundle.d.mts.map +1 -1
- package/dist/dsl/bundle.mjs +35 -31
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/condition.cjs +13 -1
- package/dist/dsl/condition.cjs.map +1 -1
- package/dist/dsl/condition.d.cts +9 -1
- package/dist/dsl/condition.d.cts.map +1 -1
- package/dist/dsl/condition.d.mts +9 -1
- package/dist/dsl/condition.d.mts.map +1 -1
- package/dist/dsl/condition.mjs +13 -2
- package/dist/dsl/condition.mjs.map +1 -1
- package/dist/dsl/flow.cjs +33 -11
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +9 -1
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +9 -1
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs +34 -13
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/workflow.cjs +2 -3
- package/dist/dsl/workflow.cjs.map +1 -1
- package/dist/dsl/workflow.d.cts.map +1 -1
- package/dist/dsl/workflow.d.mts.map +1 -1
- package/dist/dsl/workflow.mjs +3 -4
- package/dist/dsl/workflow.mjs.map +1 -1
- package/dist/engine/actions.cjs +1 -8
- package/dist/engine/actions.cjs.map +1 -1
- package/dist/engine/actions.d.cts +1 -12
- package/dist/engine/actions.d.cts.map +1 -1
- package/dist/engine/actions.d.mts +1 -12
- package/dist/engine/actions.d.mts.map +1 -1
- package/dist/engine/actions.mjs +1 -8
- package/dist/engine/actions.mjs.map +1 -1
- package/dist/engine/condition.cjs +25 -5
- package/dist/engine/condition.cjs.map +1 -1
- package/dist/engine/condition.d.cts +12 -3
- package/dist/engine/condition.d.cts.map +1 -1
- package/dist/engine/condition.d.mts +12 -3
- package/dist/engine/condition.d.mts.map +1 -1
- package/dist/engine/condition.mjs +25 -6
- package/dist/engine/condition.mjs.map +1 -1
- package/dist/engine/index.cjs +3 -0
- package/dist/engine/index.d.cts +5 -5
- package/dist/engine/index.d.mts +5 -5
- package/dist/engine/index.mjs +4 -4
- package/dist/engine/interpreter.cjs +27 -20
- package/dist/engine/interpreter.cjs.map +1 -1
- package/dist/engine/interpreter.d.cts.map +1 -1
- package/dist/engine/interpreter.d.mts.map +1 -1
- package/dist/engine/interpreter.mjs +27 -20
- package/dist/engine/interpreter.mjs.map +1 -1
- package/dist/engine/ports.d.cts +15 -6
- package/dist/engine/ports.d.cts.map +1 -1
- package/dist/engine/ports.d.mts +15 -6
- package/dist/engine/ports.d.mts.map +1 -1
- package/dist/engine/retry.cjs +13 -0
- package/dist/engine/retry.cjs.map +1 -1
- package/dist/engine/retry.d.cts +12 -0
- package/dist/engine/retry.d.cts.map +1 -1
- package/dist/engine/retry.d.mts +12 -0
- package/dist/engine/retry.d.mts.map +1 -1
- package/dist/engine/retry.mjs +13 -1
- package/dist/engine/retry.mjs.map +1 -1
- package/dist/engine/time-scale.cjs +90 -15
- package/dist/engine/time-scale.cjs.map +1 -1
- package/dist/engine/time-scale.d.cts +9 -6
- package/dist/engine/time-scale.d.cts.map +1 -1
- package/dist/engine/time-scale.d.mts +9 -6
- package/dist/engine/time-scale.d.mts.map +1 -1
- package/dist/engine/time-scale.mjs +90 -16
- package/dist/engine/time-scale.mjs.map +1 -1
- package/dist/fcm.cjs +111 -38
- package/dist/fcm.cjs.map +1 -1
- package/dist/fcm.d.cts +45 -5
- package/dist/fcm.d.cts.map +1 -1
- package/dist/fcm.d.mts +45 -5
- package/dist/fcm.d.mts.map +1 -1
- package/dist/fcm.mjs +110 -39
- package/dist/fcm.mjs.map +1 -1
- package/dist/hash.cjs +6 -6
- package/dist/hash.cjs.map +1 -1
- package/dist/hash.mjs +6 -6
- package/dist/hash.mjs.map +1 -1
- package/dist/host/auth.cjs +49 -0
- package/dist/host/auth.cjs.map +1 -0
- package/dist/host/auth.d.cts +35 -0
- package/dist/host/auth.d.cts.map +1 -0
- package/dist/host/auth.d.mts +35 -0
- package/dist/host/auth.d.mts.map +1 -0
- package/dist/host/auth.mjs +46 -0
- package/dist/host/auth.mjs.map +1 -0
- package/dist/host/channels.cjs +118 -40
- package/dist/host/channels.cjs.map +1 -1
- package/dist/host/channels.d.cts +27 -1
- package/dist/host/channels.d.cts.map +1 -1
- package/dist/host/channels.d.mts +27 -1
- package/dist/host/channels.d.mts.map +1 -1
- package/dist/host/channels.mjs +121 -44
- package/dist/host/channels.mjs.map +1 -1
- package/dist/host/execute.cjs +14 -2
- package/dist/host/execute.cjs.map +1 -1
- package/dist/host/execute.d.cts +4 -4
- package/dist/host/execute.d.cts.map +1 -1
- package/dist/host/execute.d.mts +4 -4
- package/dist/host/execute.d.mts.map +1 -1
- package/dist/host/execute.mjs +13 -1
- package/dist/host/execute.mjs.map +1 -1
- package/dist/host/fresh-read.cjs +30 -0
- package/dist/host/fresh-read.cjs.map +1 -0
- package/dist/host/fresh-read.d.cts +18 -0
- package/dist/host/fresh-read.d.cts.map +1 -0
- package/dist/host/fresh-read.d.mts +18 -0
- package/dist/host/fresh-read.d.mts.map +1 -0
- package/dist/host/fresh-read.mjs +29 -0
- package/dist/host/fresh-read.mjs.map +1 -0
- package/dist/host/http.cjs +340 -0
- package/dist/host/http.cjs.map +1 -0
- package/dist/host/http.d.cts +58 -0
- package/dist/host/http.d.cts.map +1 -0
- package/dist/host/http.d.mts +58 -0
- package/dist/host/http.d.mts.map +1 -0
- package/dist/host/http.mjs +336 -0
- package/dist/host/http.mjs.map +1 -0
- package/dist/host/{router.cjs → ingest.cjs} +147 -175
- package/dist/host/ingest.cjs.map +1 -0
- package/dist/host/{router.d.cts → ingest.d.cts} +48 -30
- package/dist/host/ingest.d.cts.map +1 -0
- package/dist/host/{router.d.mts → ingest.d.mts} +48 -30
- package/dist/host/ingest.d.mts.map +1 -0
- package/dist/host/{router.mjs → ingest.mjs} +144 -173
- package/dist/host/ingest.mjs.map +1 -0
- package/dist/host/journey-host.cjs +66 -93
- package/dist/host/journey-host.cjs.map +1 -1
- package/dist/host/journey-host.d.cts +31 -26
- package/dist/host/journey-host.d.cts.map +1 -1
- package/dist/host/journey-host.d.mts +31 -26
- package/dist/host/journey-host.d.mts.map +1 -1
- package/dist/host/journey-host.mjs +66 -93
- package/dist/host/journey-host.mjs.map +1 -1
- package/dist/host/platform.cjs +21 -0
- package/dist/host/platform.cjs.map +1 -0
- package/dist/host/platform.d.cts +126 -0
- package/dist/host/platform.d.cts.map +1 -0
- package/dist/host/platform.d.mts +126 -0
- package/dist/host/platform.d.mts.map +1 -0
- package/dist/host/platform.mjs +19 -0
- package/dist/host/platform.mjs.map +1 -0
- package/dist/host/senders.cjs +18 -9
- package/dist/host/senders.cjs.map +1 -1
- package/dist/host/senders.d.cts +9 -4
- package/dist/host/senders.d.cts.map +1 -1
- package/dist/host/senders.d.mts +9 -4
- package/dist/host/senders.d.mts.map +1 -1
- package/dist/host/senders.mjs +18 -9
- package/dist/host/senders.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/ir.cjs +5 -7
- package/dist/ir.cjs.map +1 -1
- package/dist/ir.d.cts +3 -12
- package/dist/ir.d.cts.map +1 -1
- package/dist/ir.d.mts +3 -12
- package/dist/ir.d.mts.map +1 -1
- package/dist/ir.mjs +5 -7
- package/dist/ir.mjs.map +1 -1
- package/dist/plan.cjs +27 -33
- package/dist/plan.cjs.map +1 -1
- package/dist/plan.d.cts +1 -1
- package/dist/plan.d.cts.map +1 -1
- package/dist/plan.d.mts +1 -1
- package/dist/plan.d.mts.map +1 -1
- package/dist/plan.mjs +27 -33
- package/dist/plan.mjs.map +1 -1
- package/dist/reporting/tracking.cjs +14 -4
- package/dist/reporting/tracking.cjs.map +1 -1
- package/dist/reporting/tracking.d.cts +10 -10
- package/dist/reporting/tracking.d.cts.map +1 -1
- package/dist/reporting/tracking.d.mts +10 -10
- package/dist/reporting/tracking.d.mts.map +1 -1
- package/dist/reporting/tracking.mjs +14 -4
- package/dist/reporting/tracking.mjs.map +1 -1
- package/dist/store/d1.cjs +88 -29
- package/dist/store/d1.cjs.map +1 -1
- package/dist/store/d1.d.cts +29 -11
- package/dist/store/d1.d.cts.map +1 -1
- package/dist/store/d1.d.mts +29 -11
- package/dist/store/d1.d.mts.map +1 -1
- package/dist/store/d1.mjs +88 -29
- package/dist/store/d1.mjs.map +1 -1
- package/dist/store/erasure.cjs +22 -0
- package/dist/store/erasure.cjs.map +1 -0
- package/dist/store/erasure.d.cts +18 -0
- package/dist/store/erasure.d.cts.map +1 -0
- package/dist/store/erasure.d.mts +18 -0
- package/dist/store/erasure.d.mts.map +1 -0
- package/dist/store/erasure.mjs +21 -0
- package/dist/store/erasure.mjs.map +1 -0
- package/dist/store/index.cjs +2 -0
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +67 -13
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +67 -13
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs +2 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres-reporting.cjs +125 -62
- package/dist/store/postgres-reporting.cjs.map +1 -1
- package/dist/store/postgres-reporting.d.cts +30 -2
- package/dist/store/postgres-reporting.d.cts.map +1 -1
- package/dist/store/postgres-reporting.d.mts +30 -2
- package/dist/store/postgres-reporting.d.mts.map +1 -1
- package/dist/store/postgres-reporting.mjs +125 -62
- package/dist/store/postgres-reporting.mjs.map +1 -1
- package/dist/store/postgres.cjs +179 -60
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +44 -7
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +44 -7
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +179 -60
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +7 -5
- 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 +7 -5
- package/dist/store/tables.mjs.map +1 -1
- package/dist/store/user-lock.cjs +43 -0
- package/dist/store/user-lock.cjs.map +1 -0
- package/dist/store/user-lock.d.cts +32 -0
- package/dist/store/user-lock.d.cts.map +1 -0
- package/dist/store/user-lock.d.mts +32 -0
- package/dist/store/user-lock.d.mts.map +1 -0
- package/dist/store/user-lock.mjs +40 -0
- package/dist/store/user-lock.mjs.map +1 -0
- package/dist/transports/cloudflare-email.cjs +1 -1
- package/dist/transports/cloudflare-email.mjs +1 -1
- package/dist/transports/ses.cjs +47 -6
- package/dist/transports/ses.cjs.map +1 -1
- package/dist/transports/ses.d.cts +9 -1
- package/dist/transports/ses.d.cts.map +1 -1
- package/dist/transports/ses.d.mts +9 -1
- package/dist/transports/ses.d.mts.map +1 -1
- package/dist/transports/ses.mjs +47 -7
- package/dist/transports/ses.mjs.map +1 -1
- package/dist/webpush.cjs +133 -47
- package/dist/webpush.cjs.map +1 -1
- package/dist/webpush.d.cts +49 -8
- package/dist/webpush.d.cts.map +1 -1
- package/dist/webpush.d.mts +49 -8
- package/dist/webpush.d.mts.map +1 -1
- package/dist/webpush.mjs +130 -47
- package/dist/webpush.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cloudflare/schema.sql +27 -6
- package/dist/host/router.cjs.map +0 -1
- package/dist/host/router.d.cts.map +0 -1
- package/dist/host/router.d.mts.map +0 -1
- package/dist/host/router.mjs.map +0 -1
|
@@ -1,20 +1,35 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
3
2
|
const require_hash = require("../hash.cjs");
|
|
4
3
|
const require_ir = require("../ir.cjs");
|
|
5
|
-
const
|
|
4
|
+
const require_store_erasure = require("../store/erasure.cjs");
|
|
6
5
|
const require_engine_bucket = require("../engine/bucket.cjs");
|
|
7
6
|
const require_engine_condition = require("../engine/condition.cjs");
|
|
8
7
|
const require_store_facts = require("../store/facts.cjs");
|
|
9
|
-
const require_cloudflare_bindings = require("../cloudflare/bindings.cjs");
|
|
10
8
|
const require_cloudflare_d1_env = require("../cloudflare/d1-env.cjs");
|
|
11
|
-
const require_reporting_tracking = require("../reporting/tracking.cjs");
|
|
12
9
|
const require_store_index = require("../store/index.cjs");
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
const require_host_platform = require("./platform.cjs");
|
|
11
|
+
//#region src/host/ingest.ts
|
|
12
|
+
/**
|
|
13
|
+
* Ingest: what the host does with what comes in, HTTP aside (that is `http.ts`). An incoming
|
|
14
|
+
* event does four things: it is stored, it wakes waiting instances, it is matched against event
|
|
15
|
+
* triggers, and it re-evaluates segment-trigger membership. An identify merges a profile, which
|
|
16
|
+
* wakes the waits on the properties it patched and re-evaluates segment triggers too. Plus
|
|
17
|
+
* devices, erasure, the segment sweep and bundle deploys.
|
|
18
|
+
*
|
|
19
|
+
* Storage goes through a JourneyStore; the `store` argument defaults to the D1 store built from
|
|
20
|
+
* the env's binding, so a Worker that only has that calls these functions as they are.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The fast answer for a user with an erasure tombstone (being erased, or erased for good): every
|
|
24
|
+
* ingest-side entry point starts here and does no work for them. The gate itself is the store's
|
|
25
|
+
* conditional write, which throws the same error when the tombstone lands after this check.
|
|
26
|
+
*/
|
|
27
|
+
async function refuseIfErased(store, userId) {
|
|
28
|
+
if (await store.erasureState(userId) !== "none") throw new require_store_erasure.UserErasedError(userId);
|
|
29
|
+
}
|
|
16
30
|
async function ingestEvent(env, input, store = require_cloudflare_d1_env.d1Store(env)) {
|
|
17
31
|
if (input.event.startsWith("$")) throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);
|
|
32
|
+
await refuseIfErased(store, input.userId);
|
|
18
33
|
const ts = input.ts ?? Date.now();
|
|
19
34
|
const payload = input.payload ?? {};
|
|
20
35
|
const id = input.id ?? crypto.randomUUID();
|
|
@@ -25,7 +40,7 @@ async function ingestEvent(env, input, store = require_cloudflare_d1_env.d1Store
|
|
|
25
40
|
ts,
|
|
26
41
|
payload
|
|
27
42
|
});
|
|
28
|
-
const woke = await wakeSubscribers(env, store, input.userId, input.event);
|
|
43
|
+
const woke = await wakeSubscribers(env, store, input.userId, [input.event]);
|
|
29
44
|
const started = await startTriggeredJourneys(env, store, {
|
|
30
45
|
...input,
|
|
31
46
|
payload
|
|
@@ -38,20 +53,27 @@ async function ingestEvent(env, input, store = require_cloudflare_d1_env.d1Store
|
|
|
38
53
|
started
|
|
39
54
|
};
|
|
40
55
|
}
|
|
41
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Wake every instance of the user waiting on any of `events`, once each: an instance subscribed
|
|
58
|
+
* to several of them (a wait on two profile properties, patched together) gets one wake-up, and
|
|
59
|
+
* the payload names the first event it matched.
|
|
60
|
+
*/
|
|
61
|
+
async function wakeSubscribers(env, store, userId, events) {
|
|
62
|
+
const handles = /* @__PURE__ */ new Map();
|
|
63
|
+
for (const event of events) for (const handle of await store.findWakeHandles(userId, event)) if (!handles.has(handle)) handles.set(handle, event);
|
|
42
64
|
let woke = 0;
|
|
43
|
-
for (const handle of
|
|
65
|
+
for (const [handle, event] of handles) {
|
|
44
66
|
let instance;
|
|
45
67
|
try {
|
|
46
68
|
instance = await env.JOURNEY.get(handle);
|
|
47
69
|
} catch (error) {
|
|
48
|
-
if (
|
|
70
|
+
if (error instanceof require_host_platform.InstanceNotFoundError) await store.unsubscribe(handle);
|
|
49
71
|
else console.warn(`[workflow] looking up ${handle} to wake it failed`, error);
|
|
50
72
|
continue;
|
|
51
73
|
}
|
|
52
74
|
try {
|
|
53
75
|
await instance.sendEvent({
|
|
54
|
-
type:
|
|
76
|
+
type: require_host_platform.WAKE_EVENT_TYPE,
|
|
55
77
|
payload: { event }
|
|
56
78
|
});
|
|
57
79
|
woke++;
|
|
@@ -137,30 +159,45 @@ async function refreshSegments(env, store, userId, ts, routes, segments = [], de
|
|
|
137
159
|
if (failures.length > 0) throw failures[0];
|
|
138
160
|
return started;
|
|
139
161
|
}
|
|
162
|
+
/** How many users one sweep page evaluates: a unit of resumable work (AWS checkpoints each). */
|
|
163
|
+
const SWEEP_PAGE_SIZE = 500;
|
|
140
164
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
* It walks users one by one: fine for thousands, a large audience wants SQL-side evaluation.
|
|
165
|
+
* What the sweep does before it looks at any user: the runtime's own upkeep (AWS: unconfirmed
|
|
166
|
+
* starts, executions that ended unseen) and the erasures left unfinished (an instance would not
|
|
167
|
+
* stop). A failure of either is logged, never fatal: the pages still run. Users whose erasure is
|
|
168
|
+
* still pending afterwards are skipped by every page (`sweepSegmentsPaged`).
|
|
146
169
|
*/
|
|
147
|
-
async function
|
|
170
|
+
async function sweepMaintenance(env, store) {
|
|
148
171
|
try {
|
|
149
172
|
await env.JOURNEY.maintain?.();
|
|
150
173
|
} catch (error) {
|
|
151
174
|
console.error("[workflow] runtime maintenance failed", error);
|
|
152
175
|
}
|
|
153
|
-
const erasing = /* @__PURE__ */ new Set();
|
|
154
176
|
for (const userId of await store.pendingErasures()) try {
|
|
155
|
-
|
|
156
|
-
if (!erased) erasing.add(userId);
|
|
177
|
+
await eraseUser(env, userId, store, Date.now());
|
|
157
178
|
} catch (error) {
|
|
158
|
-
erasing.add(userId);
|
|
159
179
|
console.error(`[workflow] erasure of ${userId} failed`, error);
|
|
160
180
|
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* One page of the sweep: the users after `after` (ascending, at most `limit`), every deployed
|
|
184
|
+
* segment evaluated for each. The pages are what makes the sweep resumable — a host whose run
|
|
185
|
+
* can be cut short (a Lambda timeout) checkpoints each one and replays the checkpointed pages
|
|
186
|
+
* instead of starting over; `sweepSegments` is the plain loop over them.
|
|
187
|
+
*/
|
|
188
|
+
async function sweepSegmentsPaged(env, store, page) {
|
|
189
|
+
const now = page.now ?? Date.now();
|
|
190
|
+
const limit = page.limit ?? 500;
|
|
161
191
|
const segments = (await store.listSegments()).map((segment) => segment.id);
|
|
162
192
|
const routes = await store.listSegmentTriggers();
|
|
163
|
-
const
|
|
193
|
+
const erasing = new Set(await store.pendingErasures());
|
|
194
|
+
const listed = await store.listUserIds({
|
|
195
|
+
after: page.after,
|
|
196
|
+
limit
|
|
197
|
+
});
|
|
198
|
+
const lastUserId = listed.at(-1);
|
|
199
|
+
if (page.after !== void 0 && lastUserId === page.after) throw new Error(`listUserIds did not advance past ${page.after}: the store ignores 'after'`);
|
|
200
|
+
const users = listed.filter((userId) => !erasing.has(userId));
|
|
164
201
|
const started = [];
|
|
165
202
|
const definitions = /* @__PURE__ */ new Map();
|
|
166
203
|
for (const userId of users) try {
|
|
@@ -168,10 +205,41 @@ async function sweepSegments(env, store, now = Date.now()) {
|
|
|
168
205
|
} catch (error) {
|
|
169
206
|
console.error(`[workflow] segment refresh for ${userId} failed`, error);
|
|
170
207
|
}
|
|
171
|
-
const sizes = await store.reporting?.snapshotSegments(now) ?? [];
|
|
172
208
|
return {
|
|
173
209
|
users: users.length,
|
|
174
210
|
started,
|
|
211
|
+
lastUserId,
|
|
212
|
+
more: listed.length >= limit
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a
|
|
217
|
+
* journey's conditions run on, so a member is exactly who a journey would see in it. Membership
|
|
218
|
+
* follows (joiners keep the time they joined, leavers are removed), segment triggers start the
|
|
219
|
+
* journeys of whoever entered by the clock alone, and the store records each segment's size.
|
|
220
|
+
* It walks users page by page (`sweepSegmentsPaged`): fine for thousands, a large audience wants
|
|
221
|
+
* SQL-side evaluation.
|
|
222
|
+
*/
|
|
223
|
+
async function sweepSegments(env, store, now = Date.now()) {
|
|
224
|
+
await sweepMaintenance(env, store);
|
|
225
|
+
let users = 0;
|
|
226
|
+
const started = [];
|
|
227
|
+
let after;
|
|
228
|
+
for (;;) {
|
|
229
|
+
const page = await sweepSegmentsPaged(env, store, {
|
|
230
|
+
after,
|
|
231
|
+
limit: 500,
|
|
232
|
+
now
|
|
233
|
+
});
|
|
234
|
+
users += page.users;
|
|
235
|
+
started.push(...page.started);
|
|
236
|
+
if (!page.more || page.lastUserId === void 0) break;
|
|
237
|
+
after = page.lastUserId;
|
|
238
|
+
}
|
|
239
|
+
const sizes = await store.reporting?.snapshotSegments(now) ?? [];
|
|
240
|
+
return {
|
|
241
|
+
users,
|
|
242
|
+
started,
|
|
175
243
|
sizes
|
|
176
244
|
};
|
|
177
245
|
}
|
|
@@ -225,7 +293,7 @@ async function startJourney(env, store, workflow, hash, userId, ts, trigger, ver
|
|
|
225
293
|
}
|
|
226
294
|
const utf8 = new TextEncoder();
|
|
227
295
|
/**
|
|
228
|
-
* Instance id: addressable (the
|
|
296
|
+
* Instance id: addressable (the host gets it directly to wake it), ≤100
|
|
229
297
|
* chars, legal charset. The murmur3 fingerprint keeps ids distinct when the
|
|
230
298
|
* sanitized/truncated userId alone would collide.
|
|
231
299
|
*/
|
|
@@ -240,11 +308,12 @@ function buildInstanceId(workflow, hash, userId, ts) {
|
|
|
240
308
|
* two identifies landing together cannot lose each other's fields.
|
|
241
309
|
*/
|
|
242
310
|
async function identifyUser(env, userId, props, store = require_cloudflare_d1_env.d1Store(env)) {
|
|
311
|
+
await refuseIfErased(store, userId);
|
|
243
312
|
const ts = Date.now();
|
|
244
313
|
return {
|
|
245
314
|
ok: true,
|
|
246
315
|
props: await store.mergeProfile(userId, props),
|
|
247
|
-
woke: await wakeSubscribers(env, store, userId, require_engine_condition.
|
|
316
|
+
woke: await wakeSubscribers(env, store, userId, Object.keys(props).map(require_engine_condition.profileUpdatedEvent)),
|
|
248
317
|
started: await refreshSegmentTriggers(env, store, userId, ts)
|
|
249
318
|
};
|
|
250
319
|
}
|
|
@@ -254,22 +323,19 @@ async function identifyUser(env, userId, props, store = require_cloudflare_d1_en
|
|
|
254
323
|
* `waitUntil`), for the new owner and the previous one.
|
|
255
324
|
*/
|
|
256
325
|
async function registerDevice(env, device, store = require_cloudflare_d1_env.d1Store(env)) {
|
|
326
|
+
await refuseIfErased(store, device.userId);
|
|
257
327
|
const previous = await store.removeDevice(device.token);
|
|
258
328
|
await store.upsertDevice({
|
|
259
329
|
...device,
|
|
260
330
|
ts: device.ts ?? Date.now()
|
|
261
331
|
});
|
|
262
|
-
let woke = await wakeSubscribers(env, store, device.userId, require_engine_condition.DEVICES_UPDATED_EVENT);
|
|
263
|
-
if (previous !== void 0 && previous !== device.userId) woke += await wakeSubscribers(env, store, previous, require_engine_condition.DEVICES_UPDATED_EVENT);
|
|
332
|
+
let woke = await wakeSubscribers(env, store, device.userId, [require_engine_condition.DEVICES_UPDATED_EVENT]);
|
|
333
|
+
if (previous !== void 0 && previous !== device.userId) woke += await wakeSubscribers(env, store, previous, [require_engine_condition.DEVICES_UPDATED_EVENT]);
|
|
264
334
|
return {
|
|
265
335
|
ok: true,
|
|
266
336
|
woke
|
|
267
337
|
};
|
|
268
338
|
}
|
|
269
|
-
/**
|
|
270
|
-
* A deleted account: everything the engine keeps about the user is erased and the journeys still
|
|
271
|
-
* running for them are terminated, so nothing more is sent. Idempotent.
|
|
272
|
-
*/
|
|
273
339
|
/** Workflow instance states that will never run another step. */
|
|
274
340
|
const STOPPED_STATUSES = /* @__PURE__ */ new Set([
|
|
275
341
|
"complete",
|
|
@@ -277,16 +343,21 @@ const STOPPED_STATUSES = /* @__PURE__ */ new Set([
|
|
|
277
343
|
"terminated"
|
|
278
344
|
]);
|
|
279
345
|
/**
|
|
280
|
-
* Stop one instance for good; true once it is known not to run again
|
|
281
|
-
*
|
|
282
|
-
*
|
|
346
|
+
* Stop one admitted instance for good; true once it is known not to run again: terminated, or
|
|
347
|
+
* already in a terminal state (terminate refuses those). Any other failure is not taken for
|
|
348
|
+
* "already gone": it answers false, and the erasure waits for a retry.
|
|
349
|
+
*
|
|
350
|
+
* An admitted instance the platform no longer knows counts as stopped too — but only an
|
|
351
|
+
* admitted one. Admission is the runner's first act, so an admitted instance did reach the
|
|
352
|
+
* runtime: not found now means it finished and was evicted. An entry that is not admitted is
|
|
353
|
+
* never passed here: for it, not found may just as well mean its `create` is still in flight.
|
|
283
354
|
*/
|
|
284
355
|
async function stopInstance(env, instanceId) {
|
|
285
356
|
let instance;
|
|
286
357
|
try {
|
|
287
358
|
instance = await env.JOURNEY.get(instanceId);
|
|
288
359
|
} catch (error) {
|
|
289
|
-
if (
|
|
360
|
+
if (error instanceof require_host_platform.InstanceNotFoundError) return true;
|
|
290
361
|
console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);
|
|
291
362
|
return false;
|
|
292
363
|
}
|
|
@@ -302,34 +373,56 @@ async function stopInstance(env, instanceId) {
|
|
|
302
373
|
}
|
|
303
374
|
}
|
|
304
375
|
/**
|
|
305
|
-
* Carry out a recorded erasure: stop every running instance of the user, and only once all
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
376
|
+
* Carry out a recorded erasure: stop every running instance of the user, and only once all are
|
|
377
|
+
* known not to run erase their data. The tombstone is already committed, so no new entry,
|
|
378
|
+
* event, profile or device of theirs lands meanwhile.
|
|
379
|
+
*
|
|
380
|
+
* An entry's runner admits itself before its first effect (`admitInstance`, mutually exclusive
|
|
381
|
+
* with the tombstone's commit), which splits the running instances in two:
|
|
382
|
+
*
|
|
383
|
+
* - not admitted: nothing of it has run, and nothing will — a `create` still in flight, or a
|
|
384
|
+
* runner invoked later, meets the tombstone at admission and exits. No stop is needed, and
|
|
385
|
+
* none would be reliable: the platform may not know the instance yet.
|
|
386
|
+
* - admitted: it did reach the runtime and must be stopped (`stopInstance`), or it would write
|
|
387
|
+
* rows back after the erase. One that will not stop leaves the erasure pending.
|
|
388
|
+
*
|
|
389
|
+
* Erasing nothing until then keeps the entries that name the instances still to stop, so a
|
|
390
|
+
* retry can finish the job. The tombstone outlives the erase (`erased_at`), which is what makes
|
|
391
|
+
* a repeat idempotent and a late write harmless. There is no straggler to come back for: every
|
|
392
|
+
* write about a user runs in the user's locked transaction, the same lock the tombstone takes,
|
|
393
|
+
* so a write either committed before the tombstone — and `forgetUser` deletes it here — or
|
|
394
|
+
* waited for the lock and is refused by the tombstone it then sees.
|
|
309
395
|
*/
|
|
310
|
-
async function eraseUser(env, userId, store) {
|
|
396
|
+
async function eraseUser(env, userId, store, now) {
|
|
311
397
|
const pending = [];
|
|
312
|
-
for (const instanceId of await store.runningInstances(userId))
|
|
398
|
+
for (const { instanceId, admitted } of await store.runningInstances(userId)) {
|
|
399
|
+
if (!admitted) continue;
|
|
400
|
+
if (!await stopInstance(env, instanceId)) pending.push(instanceId);
|
|
401
|
+
}
|
|
313
402
|
if (pending.length > 0) return {
|
|
314
403
|
erased: false,
|
|
315
404
|
pending
|
|
316
405
|
};
|
|
317
|
-
await store.forgetUser(userId);
|
|
406
|
+
await store.forgetUser(userId, now);
|
|
318
407
|
return {
|
|
319
408
|
erased: true,
|
|
320
409
|
pending
|
|
321
410
|
};
|
|
322
411
|
}
|
|
323
412
|
/**
|
|
324
|
-
* Forget a user (a deleted account): the
|
|
325
|
-
*
|
|
326
|
-
*
|
|
413
|
+
* Forget a user (a deleted account): the tombstone is committed first, then the erasure carried
|
|
414
|
+
* out. `erased: true` means every admitted runner of theirs was confirmed stopped, the entries
|
|
415
|
+
* never admitted can never run, and the data is deleted — for good, with no time window and no
|
|
416
|
+
* second pass: the tombstone commits under the user's lock, which every write about the user
|
|
417
|
+
* also takes, so nothing of theirs can land after it. An admitted instance that will not stop
|
|
418
|
+
* leaves it pending — nothing erased yet — and the scheduled sweep retries it; `erased: false`
|
|
419
|
+
* says so. A user already erased answers `erased: true` again, with nothing to do.
|
|
327
420
|
*/
|
|
328
421
|
async function forgetUser(env, userId, store = require_cloudflare_d1_env.d1Store(env), now = Date.now()) {
|
|
329
422
|
await store.requestErasure(userId, now);
|
|
330
423
|
return {
|
|
331
424
|
ok: true,
|
|
332
|
-
...await eraseUser(env, userId, store)
|
|
425
|
+
...await eraseUser(env, userId, store, now)
|
|
333
426
|
};
|
|
334
427
|
}
|
|
335
428
|
/**
|
|
@@ -341,7 +434,7 @@ async function unbindDevice(env, token, store = require_cloudflare_d1_env.d1Stor
|
|
|
341
434
|
const owner = await store.unbindDevice(token);
|
|
342
435
|
return {
|
|
343
436
|
ok: true,
|
|
344
|
-
woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, require_engine_condition.DEVICES_UPDATED_EVENT)
|
|
437
|
+
woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, [require_engine_condition.DEVICES_UPDATED_EVENT])
|
|
345
438
|
};
|
|
346
439
|
}
|
|
347
440
|
/** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */
|
|
@@ -349,7 +442,7 @@ async function removeDevice(env, token, store = require_cloudflare_d1_env.d1Stor
|
|
|
349
442
|
const owner = await store.removeDevice(token);
|
|
350
443
|
return {
|
|
351
444
|
ok: true,
|
|
352
|
-
woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, require_engine_condition.DEVICES_UPDATED_EVENT)
|
|
445
|
+
woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, [require_engine_condition.DEVICES_UPDATED_EVENT])
|
|
353
446
|
};
|
|
354
447
|
}
|
|
355
448
|
/** A versioned deploy on a store that cannot tell which version is live (D1). */
|
|
@@ -413,142 +506,21 @@ async function deployBundle(env, bundle, store = require_cloudflare_d1_env.d1Sto
|
|
|
413
506
|
applied
|
|
414
507
|
};
|
|
415
508
|
}
|
|
416
|
-
/**
|
|
417
|
-
* Request bodies are untrusted JSON. They are read as unknown fields and
|
|
418
|
-
* checked, never cast into the shape they are supposed to have: a cast only
|
|
419
|
-
* silences the compiler, and what arrives here reaches SQL parameters.
|
|
420
|
-
*/
|
|
421
|
-
async function readBody(request) {
|
|
422
|
-
const body = await request.json();
|
|
423
|
-
return isPlainObject(body) ? body : {};
|
|
424
|
-
}
|
|
425
|
-
function isPlainObject(value) {
|
|
426
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
427
|
-
}
|
|
428
|
-
function isNonEmptyString(value) {
|
|
429
|
-
return typeof value === "string" && value.length > 0;
|
|
430
|
-
}
|
|
431
|
-
async function handleRequest(request, env, store = require_cloudflare_d1_env.d1Store(env), validation = {}) {
|
|
432
|
-
const url = new URL(request.url);
|
|
433
|
-
const json = (body, status = 200) => new Response(JSON.stringify(body), {
|
|
434
|
-
status,
|
|
435
|
-
headers: { "content-type": "application/json" }
|
|
436
|
-
});
|
|
437
|
-
const { contract } = validation;
|
|
438
|
-
const enforce = validation.mode !== "report";
|
|
439
|
-
/** The contract's verdict: the value to use, or the response refusing the request. */
|
|
440
|
-
const checked = (result, original, what) => {
|
|
441
|
-
if (result.ok) return { value: result.data };
|
|
442
|
-
const issues = result.issues.map((i) => `${i.path || "(root)"}: ${i.message}`);
|
|
443
|
-
if (!enforce) {
|
|
444
|
-
console.warn(`[workflow router] contract would refuse ${what}: ${issues.join("; ")}`);
|
|
445
|
-
return { value: original };
|
|
446
|
-
}
|
|
447
|
-
return { refused: json({
|
|
448
|
-
error: `${what} refused by the contract`,
|
|
449
|
-
issues: result.issues
|
|
450
|
-
}, 400) };
|
|
451
|
-
};
|
|
452
|
-
if (request.method === "GET" && url.pathname === "/health") return json({ ok: true });
|
|
453
|
-
if (env.API_TOKEN !== void 0) {
|
|
454
|
-
if (request.headers.get("authorization") !== `Bearer ${env.API_TOKEN}`) return json({ error: "unauthorized" }, 401);
|
|
455
|
-
}
|
|
456
|
-
try {
|
|
457
|
-
if (request.method === "POST" && url.pathname === "/events") {
|
|
458
|
-
const { id, userId, event, payload, ts } = await readBody(request);
|
|
459
|
-
if (!isNonEmptyString(userId) || !isNonEmptyString(event)) return json({ error: "userId and event required" }, 400);
|
|
460
|
-
if (event.startsWith("$")) return json({ error: "event names starting with $ are reserved" }, 400);
|
|
461
|
-
if (id !== void 0 && !isNonEmptyString(id)) return json({ error: "id must be a non-empty string" }, 400);
|
|
462
|
-
if (ts !== void 0 && typeof ts !== "number") return json({ error: "ts must be a number" }, 400);
|
|
463
|
-
if (payload !== void 0 && !isPlainObject(payload)) return json({ error: "payload must be an object" }, 400);
|
|
464
|
-
let accepted = payload;
|
|
465
|
-
if (contract !== void 0) {
|
|
466
|
-
const verdict = checked(require_contract.checkEvent(contract, event, payload ?? {}), accepted ?? {}, `event '${event}'${typeof id === "string" ? ` (${id})` : ""}`);
|
|
467
|
-
if ("refused" in verdict) return verdict.refused;
|
|
468
|
-
accepted = verdict.value;
|
|
469
|
-
}
|
|
470
|
-
return json(await ingestEvent(env, {
|
|
471
|
-
id,
|
|
472
|
-
userId,
|
|
473
|
-
event,
|
|
474
|
-
payload: accepted,
|
|
475
|
-
ts
|
|
476
|
-
}, store));
|
|
477
|
-
}
|
|
478
|
-
if (request.method === "POST" && url.pathname === "/identify") {
|
|
479
|
-
const { userId, props } = await readBody(request);
|
|
480
|
-
if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
|
|
481
|
-
if (!isPlainObject(props)) return json({ error: "props must be an object" }, 400);
|
|
482
|
-
let patch = props;
|
|
483
|
-
if (contract !== void 0) {
|
|
484
|
-
const verdict = checked(contract.parseProfilePatch(props), patch, "identify");
|
|
485
|
-
if ("refused" in verdict) return verdict.refused;
|
|
486
|
-
patch = verdict.value;
|
|
487
|
-
}
|
|
488
|
-
return json(await identifyUser(env, userId, patch, store));
|
|
489
|
-
}
|
|
490
|
-
if (request.method === "POST" && url.pathname === "/devices") {
|
|
491
|
-
const { userId, token, platform, ts } = await readBody(request);
|
|
492
|
-
if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
|
|
493
|
-
if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
|
|
494
|
-
if (platform !== "ios" && platform !== "android" && platform !== "web") return json({ error: "platform must be 'ios', 'android' or 'web'" }, 400);
|
|
495
|
-
if (ts !== void 0 && typeof ts !== "number") return json({ error: "ts must be a number" }, 400);
|
|
496
|
-
return json(await registerDevice(env, {
|
|
497
|
-
userId,
|
|
498
|
-
token,
|
|
499
|
-
platform,
|
|
500
|
-
...ts === void 0 ? {} : { ts }
|
|
501
|
-
}, store));
|
|
502
|
-
}
|
|
503
|
-
if (request.method === "POST" && url.pathname === "/messages/opened") {
|
|
504
|
-
const { userId, messageId } = await readBody(request);
|
|
505
|
-
if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
|
|
506
|
-
if (!isNonEmptyString(messageId)) return json({ error: "messageId required" }, 400);
|
|
507
|
-
return json({
|
|
508
|
-
ok: true,
|
|
509
|
-
recorded: store.reporting !== void 0 && await require_reporting_tracking.recordPushOpen(store.reporting, userId, messageId)
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
if (request.method === "POST" && url.pathname === "/users/forget") {
|
|
513
|
-
const { userId } = await readBody(request);
|
|
514
|
-
if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
|
|
515
|
-
return json(await forgetUser(env, userId, store));
|
|
516
|
-
}
|
|
517
|
-
if (request.method === "POST" && url.pathname === "/devices/unbind") {
|
|
518
|
-
const { token } = await readBody(request);
|
|
519
|
-
if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
|
|
520
|
-
return json(await unbindDevice(env, token, store));
|
|
521
|
-
}
|
|
522
|
-
if (request.method === "POST" && url.pathname === "/devices/remove") {
|
|
523
|
-
const { token } = await readBody(request);
|
|
524
|
-
if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
|
|
525
|
-
return json(await removeDevice(env, token, store));
|
|
526
|
-
}
|
|
527
|
-
if (request.method === "POST" && url.pathname === "/deploy") return json(await deployBundle(env, await request.json(), store));
|
|
528
|
-
return json({ error: "not found" }, 404);
|
|
529
|
-
} catch (error) {
|
|
530
|
-
if (error instanceof zod_mini.core.$ZodError) return json({ error: `invalid payload: ${error.message}` }, 400);
|
|
531
|
-
if (error instanceof BundleIntegrityError) return json({ error: error.message }, 400);
|
|
532
|
-
if (error instanceof require_store_index.SchemaMismatchError) return json({
|
|
533
|
-
error: error.message,
|
|
534
|
-
problems: error.problems
|
|
535
|
-
}, 503);
|
|
536
|
-
console.error("[workflow router]", error);
|
|
537
|
-
return json({ error: "internal error" }, 500);
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
509
|
//#endregion
|
|
541
510
|
exports.BundleIntegrityError = BundleIntegrityError;
|
|
511
|
+
exports.SWEEP_PAGE_SIZE = SWEEP_PAGE_SIZE;
|
|
542
512
|
exports.UnversionedStoreError = UnversionedStoreError;
|
|
543
513
|
exports.deployBundle = deployBundle;
|
|
544
514
|
exports.forgetUser = forgetUser;
|
|
545
|
-
exports.handleRequest = handleRequest;
|
|
546
515
|
exports.identifyUser = identifyUser;
|
|
547
516
|
exports.ingestEvent = ingestEvent;
|
|
548
517
|
exports.refreshSegmentTriggers = refreshSegmentTriggers;
|
|
549
518
|
exports.registerDevice = registerDevice;
|
|
550
519
|
exports.removeDevice = removeDevice;
|
|
520
|
+
exports.sweepMaintenance = sweepMaintenance;
|
|
551
521
|
exports.sweepSegments = sweepSegments;
|
|
522
|
+
exports.sweepSegmentsPaged = sweepSegmentsPaged;
|
|
552
523
|
exports.unbindDevice = unbindDevice;
|
|
524
|
+
exports.wakeSubscribers = wakeSubscribers;
|
|
553
525
|
|
|
554
|
-
//# sourceMappingURL=
|
|
526
|
+
//# sourceMappingURL=ingest.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ingest.cjs","names":["UserErasedError","d1Store","InstanceNotFoundError","WAKE_EVENT_TYPE","matchesWhere","JourneyFactSource","evaluateCondition","murmur3","profileUpdatedEvent","DEVICES_UPDATED_EVENT","semanticHash","BundleIR","SchemaMismatchError"],"sources":["../../src/host/ingest.ts"],"sourcesContent":["import { d1Store } from '../cloudflare/d1-env';\nimport { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n profileUpdatedEvent,\n} from '../engine/condition';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type BundleVersion,\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n UserErasedError,\n} from '../store/index';\nimport {\n InstanceNotFoundError,\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './platform';\n\n/**\n * Ingest: what the host does with what comes in, HTTP aside (that is `http.ts`). An incoming\n * event does four things: it is stored, it wakes waiting instances, it is matched against event\n * triggers, and it re-evaluates segment-trigger membership. An identify merges a profile, which\n * wakes the waits on the properties it patched and re-evaluates segment triggers too. Plus\n * devices, erasure, the segment sweep and bundle deploys.\n *\n * Storage goes through a JourneyStore; the `store` argument defaults to the D1 store built from\n * the env's binding, so a Worker that only has that calls these functions as they are.\n */\n\n/**\n * The fast answer for a user with an erasure tombstone (being erased, or erased for good): every\n * ingest-side entry point starts here and does no work for them. The gate itself is the store's\n * conditional write, which throws the same error when the tombstone lands after this check.\n */\nasync function refuseIfErased(store: JourneyStore, userId: string): Promise<void> {\n if ((await store.erasureState(userId)) !== 'none') throw new UserErasedError(userId);\n}\n\nexport interface IngestInput {\n userId: string;\n event: string;\n payload?: Record<string, unknown>;\n ts?: number;\n /**\n * This occurrence's identity, and with it the idempotency of sending it.\n *\n * Only the sender can know whether two deliveries describe one occurrence or\n * two, so the engine does not decide: an id it has already stored makes the\n * second delivery a no-op. That matters because ingest is reachable from two\n * retrying callers — an HTTP client retrying a 500, and the interpreter's\n * send_event step being retried after it already committed its row — and a\n * second copy of an event silently changes every count- and window-based\n * condition that reads the log.\n *\n * Callers that retry should send an id they can reproduce. Omitting it gets\n * a fresh one, which records the event as its own occurrence.\n */\n id?: string;\n}\n\nexport interface IngestResult {\n /** The occurrence's identity: the caller's `id`, or the one minted for it. */\n id: string;\n /** False when that id was already in the log: nothing was written this time. */\n stored: boolean;\n woke: number;\n started: string[];\n}\n\nexport async function ingestEvent(\n env: JourneyEnv,\n input: IngestInput,\n store: JourneyStore = d1Store(env)\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n // Also reached from a running instance's send_event: an erased user's instances are stopped\n // before the erase, so one that still gets here is refused like any other writer\n await refuseIfErased(store, input.userId);\n const ts = input.ts ?? Date.now();\n const payload = input.payload ?? {};\n // No id means the sender is not claiming this is a repeat of anything, which\n // a fresh one states truthfully — unlike a key derived from the contents,\n // which would silently collapse two identical events a second apart.\n const id = input.id ?? crypto.randomUUID();\n\n const stored = await store.insertEvent({\n id,\n userId: input.userId,\n event: input.event,\n ts,\n payload,\n });\n\n /*\n * The rest runs even for a duplicate. A retry arrives precisely because the\n * first attempt did not finish — it committed the row and then failed — so\n * returning early would strand the journeys the retry exists to start. Both\n * halves are independently idempotent: waking an instance that already moved\n * on is a no-op, and the entry ledger refuses a second entry.\n */\n const woke = await wakeSubscribers(env, store, input.userId, [input.event]);\n const started = await startTriggeredJourneys(env, store, { ...input, payload }, ts);\n started.push(...(await refreshSegmentTriggers(env, store, input.userId, ts)));\n return { id, stored, woke, started };\n}\n\n/**\n * Wake every instance of the user waiting on any of `events`, once each: an instance subscribed\n * to several of them (a wait on two profile properties, patched together) gets one wake-up, and\n * the payload names the first event it matched.\n */\nexport async function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n events: readonly string[]\n): Promise<number> {\n const handles = new Map<string, string>(); // handle → the event that matched it first\n for (const event of events) {\n for (const handle of await store.findWakeHandles(userId, event)) {\n if (!handles.has(handle)) handles.set(handle, event);\n }\n }\n let woke = 0;\n for (const [handle, event] of handles) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch (error) {\n // Unknown instance (errored out without cleanup): drop the dangling subscription. Any\n // other failure (a database blip) keeps it: deleting would silence the wait for good\n if (error instanceof InstanceNotFoundError) await store.unsubscribe(handle);\n else console.warn(`[workflow] looking up ${handle} to wake it failed`, error);\n continue;\n }\n try {\n await instance.sendEvent({ type: WAKE_EVENT_TYPE, payload: { event } });\n woke++;\n } catch {\n // Transient send failure (or an instance finishing right now): keep the\n // subscription — a later event retries it, and the wait's own timeout\n // bounds the damage. Deleting here would silence all future wake-ups.\n }\n }\n return woke;\n}\n\nasync function startTriggeredJourneys(\n env: JourneyEnv,\n store: JourneyStore,\n input: IngestInput & { payload: Record<string, unknown> },\n ts: number\n): Promise<string[]> {\n const started: string[] = [];\n for (const route of await store.findTriggers(input.event)) {\n // where: the payload gate — evaluated against the incoming event first\n if (route.where !== null && !matchesWhere(input.payload, route.where)) continue;\n\n // filter: the profile gate\n if (route.filter !== null) {\n const facts = new JourneyFactSource(store, input.userId);\n if (!(await evaluateCondition(route.filter, facts, ts))) continue;\n }\n\n const instanceId = await startJourney(\n env,\n store,\n route.workflow,\n route.hash,\n input.userId,\n ts,\n {\n event: input.event,\n payload: input.payload,\n },\n route.version\n );\n if (instanceId !== null) started.push(instanceId);\n }\n return started;\n}\n\n/**\n * Segment-entry triggers, maintained lazily: on each ingest/identify for a\n * user, re-evaluate every trigger-routed segment for that user and act on the\n * membership transition (enter → start journeys, leave → drop membership so a\n * later re-entry is observable). Purely time-driven drift (an inactivity\n * segment turning true by clock alone) has no event to ride on: the scheduled\n * sweep catches it (`sweepSegments`).\n */\nexport async function refreshSegmentTriggers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number\n): Promise<string[]> {\n return refreshSegments(env, store, userId, ts, await store.listSegmentTriggers());\n}\n\n/**\n * Re-evaluate segments for one user — the routed ones only, or with `segments` every one named —\n * and act on each membership transition: entering records the membership and starts the\n * segment's routed workflows, leaving drops it. A segment trigger therefore starts journeys for\n * users who enter after it is deployed; a user already a member is not entered again.\n */\nasync function refreshSegments(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number,\n routes: readonly SegmentTriggerRoute[],\n segments: readonly string[] = [],\n // A sweep loads each definition once for all its users, not once per user\n definitions = new Map<string, ConditionIR | undefined>()\n): Promise<string[]> {\n const bySegment = new Map<string, { workflow: string; hash: string; version?: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({\n workflow: route.workflow,\n hash: route.hash,\n ...(route.version === undefined ? {} : { version: route.version }),\n });\n bySegment.set(route.segment, list);\n }\n if (bySegment.size === 0) return [];\n\n const facts = new JourneyFactSource(store, userId);\n const started: string[] = [];\n const failures: unknown[] = [];\n for (const [segmentId, segmentRoutes] of bySegment) {\n if (!definitions.has(segmentId)) {\n definitions.set(segmentId, await store.getSegmentCondition(segmentId));\n }\n const definition = definitions.get(segmentId);\n if (definition === undefined) continue; // route without a definition: broken deploy, skip\n\n const matches = await evaluateCondition(definition, facts, ts);\n const member = await store.isSegmentMember(segmentId, userId);\n\n if (matches && !member) {\n // Entry transition: the membership and the starts it owes, recorded together\n await store.addSegmentMember(\n segmentId,\n userId,\n ts,\n segmentRoutes.map((route) => route.workflow)\n );\n } else if (!matches && member) {\n await store.removeSegmentMember(segmentId, userId);\n continue;\n }\n if (!matches) continue;\n\n // Every start the entry still owes — a fresh entry's, or one an earlier evaluation failed on.\n // Each is crossed off once its instance exists, so one workflow failing neither blocks the\n // others nor gets lost: the next evaluation (the sweep, the user's next event) retries it.\n const pending = new Set(await store.pendingSegmentStarts(segmentId, userId));\n for (const route of segmentRoutes) {\n if (!pending.has(route.workflow)) continue;\n try {\n const instanceId = await startJourney(\n env,\n store,\n route.workflow,\n route.hash,\n userId,\n ts,\n { event: '$segment_entry', payload: { segment: segmentId } },\n route.version\n );\n if (instanceId !== null) started.push(instanceId);\n await store.completeSegmentStart(segmentId, userId, route.workflow);\n } catch (error) {\n failures.push(error);\n }\n }\n }\n // Surface a failure to the caller (an ingest answers 500) once every start had its chance\n if (failures.length > 0) throw failures[0];\n return started;\n}\n\nexport interface SweepResult {\n users: number;\n /** Journeys the segments' entries started. */\n started: string[];\n /** Each deployed segment's size after the sweep (empty when the store keeps no reporting). */\n sizes: { segment: string; size: number }[];\n}\n\n/** How many users one sweep page evaluates: a unit of resumable work (AWS checkpoints each). */\nexport const SWEEP_PAGE_SIZE = 500;\n\n/**\n * What the sweep does before it looks at any user: the runtime's own upkeep (AWS: unconfirmed\n * starts, executions that ended unseen) and the erasures left unfinished (an instance would not\n * stop). A failure of either is logged, never fatal: the pages still run. Users whose erasure is\n * still pending afterwards are skipped by every page (`sweepSegmentsPaged`).\n */\nexport async function sweepMaintenance(env: JourneyEnv, store: JourneyStore): Promise<void> {\n try {\n await env.JOURNEY.maintain?.();\n } catch (error) {\n console.error('[workflow] runtime maintenance failed', error);\n }\n // Erasures left pending (an admitted instance would not stop, or is still draining): retried\n // until every one of them is confirmed stopped and the data is gone\n for (const userId of await store.pendingErasures()) {\n try {\n await eraseUser(env, userId, store, Date.now());\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n}\n\nexport interface SweepPage {\n /** Users evaluated on this page (those being erased are listed but skipped). */\n users: number;\n /** Journeys the segments' entries started on this page. */\n started: string[];\n /** The last user id listed, to resume past (`after`); undefined when the page was empty. */\n lastUserId?: string | undefined;\n /** Whether the page was full, so another may follow. */\n more: boolean;\n}\n\n/**\n * One page of the sweep: the users after `after` (ascending, at most `limit`), every deployed\n * segment evaluated for each. The pages are what makes the sweep resumable — a host whose run\n * can be cut short (a Lambda timeout) checkpoints each one and replays the checkpointed pages\n * instead of starting over; `sweepSegments` is the plain loop over them.\n */\nexport async function sweepSegmentsPaged(\n env: JourneyEnv,\n store: JourneyStore,\n page: { after?: string | undefined; limit?: number | undefined; now?: number | undefined }\n): Promise<SweepPage> {\n const now = page.now ?? Date.now();\n const limit = page.limit ?? SWEEP_PAGE_SIZE;\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n // Read per page, not once up front: an erasure requested since the last page is honored too\n const erasing = new Set(await store.pendingErasures());\n const listed = await store.listUserIds({ after: page.after, limit });\n const lastUserId = listed.at(-1);\n // A store that ignores `after` would hand back the same page forever: refuse to loop on it.\n // Equality only — the order is the store's collation, which JavaScript's `<` does not know\n if (page.after !== undefined && lastUserId === page.after) {\n throw new Error(`listUserIds did not advance past ${page.after}: the store ignores 'after'`);\n }\n const users = listed.filter((userId) => !erasing.has(userId));\n const started: string[] = [];\n const definitions = new Map<string, ConditionIR | undefined>();\n for (const userId of users) {\n try {\n started.push(\n ...(await refreshSegments(env, store, userId, now, routes, segments, definitions))\n );\n } catch (error) {\n // One user's failed start is kept for the next sweep; it must not stop everyone else's\n console.error(`[workflow] segment refresh for ${userId} failed`, error);\n }\n }\n return { users: users.length, started, lastUserId, more: listed.length >= limit };\n}\n\n/**\n * The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a\n * journey's conditions run on, so a member is exactly who a journey would see in it. Membership\n * follows (joiners keep the time they joined, leavers are removed), segment triggers start the\n * journeys of whoever entered by the clock alone, and the store records each segment's size.\n * It walks users page by page (`sweepSegmentsPaged`): fine for thousands, a large audience wants\n * SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n await sweepMaintenance(env, store);\n let users = 0;\n const started: string[] = [];\n let after: string | undefined;\n for (;;) {\n const page = await sweepSegmentsPaged(env, store, { after, limit: SWEEP_PAGE_SIZE, now });\n users += page.users;\n started.push(...page.started);\n if (!page.more || page.lastUserId === undefined) break;\n after = page.lastUserId;\n }\n const sizes = (await store.reporting?.snapshotSegments(now)) ?? [];\n return { users, started, sizes };\n}\n\n/**\n * Create one journey instance behind the entry ledger. Returns null when the\n * once-policy blocks the entry (the store's attempt is atomic, so concurrent\n * ingests cannot double-enter). A pair whose previous instance is recorded as\n * 'failed' is reclaimed rather than barred forever over one outage.\n */\nasync function startJourney(\n env: JourneyEnv,\n store: JourneyStore,\n workflow: string,\n hash: string,\n userId: string,\n ts: number,\n trigger: { event: string; payload: Record<string, unknown> },\n /** The code version whose bundle routed this start, read with the hash (see TriggerRoute). */\n version?: string\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n const execution = await env.JOURNEY.plan?.({ id: instanceId, params, ts, version });\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts, execution });\n if (outcome === null) {\n // Already entered and still alive — unless its start never got through: this retry is the\n // first chance to finish it\n await env.JOURNEY.resume?.({ workflow, userId });\n return null;\n }\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n // A recorded start stays: the runtime may have taken it, and a retry with the same name\n // and payload finds that execution instead of starting a second one\n if (execution !== undefined) throw error;\n if (outcome === 'reclaimed') {\n // Put the corpse back rather than deleting it: the entry is still a\n // failure, and dropping the row would erase that from the ledger.\n await store.setEntryStatus(instanceId, 'failed');\n } else {\n // Roll the ledger back so a retried ingest can enter — otherwise the\n // once-policy would permanently record an entry that never ran.\n await store.removeEntry(instanceId);\n }\n throw error;\n }\n return instanceId;\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * Instance id: addressable (the host gets it directly to wake it), ≤100\n * chars, legal charset. The murmur3 fingerprint keeps ids distinct when the\n * sanitized/truncated userId alone would collide.\n */\nfunction buildInstanceId(workflow: string, hash: string, userId: string, ts: number): string {\n const uid = userId.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 24);\n const fingerprint = murmur3(utf8.encode(userId)).toString(36);\n return `${workflow.slice(0, 32)}-${hash.slice(0, 8)}-${uid}-${fingerprint}-${ts.toString(36)}`;\n}\n\n/* --------------------------------- identify --------------------------------- */\n\nexport interface IdentifyResult {\n ok: true;\n props: ProfileProps;\n woke: number;\n started: string[];\n}\n\n/**\n * Merge-patch profile properties (a null removes one), then wake property waits\n * and re-evaluate segment triggers. The merge is one statement in the store, so\n * two identifies landing together cannot lose each other's fields.\n */\nexport async function identifyUser(\n env: JourneyEnv,\n userId: string,\n props: ProfileProps,\n store: JourneyStore = d1Store(env)\n): Promise<IdentifyResult> {\n await refuseIfErased(store, userId);\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // A property wait subscribes to its own property's channel (see relevantEvents): only the\n // waits on what this patch touched wake up\n const woke = await wakeSubscribers(\n env,\n store,\n userId,\n Object.keys(props).map(profileUpdatedEvent)\n );\n // A profile change can move the user into (or out of) a trigger-routed segment\n const started = await refreshSegmentTriggers(env, store, userId, ts);\n return { ok: true, props: merged, woke, started };\n}\n\nexport interface DeviceRegistration {\n userId: string;\n token: string;\n platform: string;\n ts?: number;\n}\n\n/**\n * A push token registered for the user (or moved to them from another account: a token belongs\n * to one user at a time). Wakes the waits that read devices (`reachable('push')` inside\n * `waitUntil`), for the new owner and the previous one.\n */\nexport async function registerDevice(\n env: JourneyEnv,\n device: DeviceRegistration,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n await refuseIfErased(store, device.userId);\n const previous = await store.removeDevice(device.token);\n await store.upsertDevice({ ...device, ts: device.ts ?? Date.now() });\n let woke = await wakeSubscribers(env, store, device.userId, [DEVICES_UPDATED_EVENT]);\n if (previous !== undefined && previous !== device.userId) {\n woke += await wakeSubscribers(env, store, previous, [DEVICES_UPDATED_EVENT]);\n }\n return { ok: true, woke };\n}\n\n/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one admitted instance for good; true once it is known not to run again: terminated, or\n * already in a terminal state (terminate refuses those). Any other failure is not taken for\n * \"already gone\": it answers false, and the erasure waits for a retry.\n *\n * An admitted instance the platform no longer knows counts as stopped too — but only an\n * admitted one. Admission is the runner's first act, so an admitted instance did reach the\n * runtime: not found now means it finished and was evicted. An entry that is not admitted is\n * never passed here: for it, not found may just as well mean its `create` is still in flight.\n */\nasync function stopInstance(env: JourneyEnv, instanceId: string): Promise<boolean> {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(instanceId);\n } catch (error) {\n if (error instanceof InstanceNotFoundError) return true;\n console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);\n return false;\n }\n if (instance.terminate === undefined) return false;\n try {\n await instance.terminate();\n return true;\n } catch (error) {\n const status = await instance.status?.().catch(() => undefined);\n if (status !== undefined && STOPPED_STATUSES.has(status.status)) return true;\n console.warn(`[workflow] terminating ${instanceId} failed`, error);\n return false;\n }\n}\n\n/**\n * Carry out a recorded erasure: stop every running instance of the user, and only once all are\n * known not to run erase their data. The tombstone is already committed, so no new entry,\n * event, profile or device of theirs lands meanwhile.\n *\n * An entry's runner admits itself before its first effect (`admitInstance`, mutually exclusive\n * with the tombstone's commit), which splits the running instances in two:\n *\n * - not admitted: nothing of it has run, and nothing will — a `create` still in flight, or a\n * runner invoked later, meets the tombstone at admission and exits. No stop is needed, and\n * none would be reliable: the platform may not know the instance yet.\n * - admitted: it did reach the runtime and must be stopped (`stopInstance`), or it would write\n * rows back after the erase. One that will not stop leaves the erasure pending.\n *\n * Erasing nothing until then keeps the entries that name the instances still to stop, so a\n * retry can finish the job. The tombstone outlives the erase (`erased_at`), which is what makes\n * a repeat idempotent and a late write harmless. There is no straggler to come back for: every\n * write about a user runs in the user's locked transaction, the same lock the tombstone takes,\n * so a write either committed before the tombstone — and `forgetUser` deletes it here — or\n * waited for the lock and is refused by the tombstone it then sees.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore,\n now: number\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const { instanceId, admitted } of await store.runningInstances(userId)) {\n if (!admitted) continue;\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId, now);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the tombstone is committed first, then the erasure carried\n * out. `erased: true` means every admitted runner of theirs was confirmed stopped, the entries\n * never admitted can never run, and the data is deleted — for good, with no time window and no\n * second pass: the tombstone commits under the user's lock, which every write about the user\n * also takes, so nothing of theirs can land after it. An admitted instance that will not stop\n * leaves it pending — nothing erased yet — and the scheduled sweep retries it; `erased: false`\n * says so. A user already erased answers `erased: true` again, with nothing to do.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore = d1Store(env),\n now = Date.now()\n): Promise<{ ok: true; erased: boolean; pending: string[] }> {\n await store.requestErasure(userId, now);\n return { ok: true, ...(await eraseUser(env, userId, store, now)) };\n}\n\n/**\n * The user signed out on the device: the token stays registered, bound to nobody, so the next\n * sign-in only has to bind it again. Wakes the former owner's device waits (`reachable('push')`\n * may no longer hold).\n */\nexport async function unbindDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.unbindDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, [DEVICES_UPDATED_EVENT]);\n return { ok: true, woke };\n}\n\n/** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */\nexport async function removeDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.removeDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, [DEVICES_UPDATED_EVENT]);\n return { ok: true, woke };\n}\n\n/* ---------------------------------- deploy ---------------------------------- */\n\nexport interface DeployResult {\n workflows: string[];\n /**\n * Workflows whose trigger type has no runtime routing yet — they deploy (the\n * IR is stored and versioned) but will never start until the routing lands.\n * Currently: date (TODO — needs cron + Queues, instance creation is\n * rate-limited and a date trigger fans out to the whole audience at once)\n * and webhook (TODO — needs endpoint allocation).\n */\n unrouted: { workflow: string; trigger: TriggerIR['type'] }[];\n /**\n * Whether the routes now point at this bundle: always for a forced deploy, false for a\n * versioned one when a version as new or newer is already live (nothing was swapped).\n */\n applied: boolean;\n}\n\n/** A versioned deploy on a store that cannot tell which version is live (D1). */\nexport class UnversionedStoreError extends Error {\n override readonly name = 'UnversionedStoreError';\n constructor() {\n super('this store does not record which version is live: deploy with POST /bundle/deploy');\n }\n}\n\n/** A bundle whose declared hashes do not describe its contents — rejected before anything is written. */\nexport class BundleIntegrityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BundleIntegrityError';\n }\n}\n\n/**\n * Recompute every declared contentHash and refuse the bundle if one disagrees.\n *\n * The contentHash is the address an in-flight journey reads its IR from, so\n * a hash that does not describe its own content is a way to change what a\n * pinned instance executes: submit an edited flow under the old hash and the\n * next replay picks it up. The compiler always computes the hash it ships, so\n * a mismatch means a hand-rolled payload or a stale client — neither should be\n * able to overwrite a version that journeys are running.\n *\n * Each hash is recomputed exactly the way its compiler produced it: a workflow\n * hashes its whole IR (contentHash strips itself), a segment hashes only its\n * condition. Mirroring them is load-bearing — recomputing a segment over the\n * whole record would reject every honest deploy.\n */\nfunction verifyBundleHashes(parsed: BundleIR): void {\n const mismatched: string[] = [];\n for (const workflow of parsed.workflows) {\n if (semanticHash(workflow) !== workflow.contentHash) {\n mismatched.push(`workflow '${workflow.id}'`);\n }\n }\n for (const segment of parsed.segments) {\n if (semanticHash(segment.condition) !== segment.contentHash) {\n mismatched.push(`segment '${segment.id}'`);\n }\n }\n if (mismatched.length > 0) {\n throw new BundleIntegrityError(\n `contentHash does not match content for ${mismatched.join(', ')} — recompile the bundle instead of editing it by hand`\n );\n }\n}\n\n/**\n * Bundle deploy, terraform-apply style: workflow bodies first (content-addressed, so a failed\n * deploy leaves only harmless orphans), then the routing swap. With a `version` the swap happens\n * only over an older live version (`replaceRoutesIfNewer`) — how journeyWorker applies the bundle\n * compiled into it; without one it is forced, whatever is live.\n */\nexport async function deployBundle(\n env: JourneyEnv,\n bundle: unknown,\n store: JourneyStore = d1Store(env),\n version?: BundleVersion\n): Promise<DeployResult> {\n if (version !== undefined && store.replaceRoutesIfNewer === undefined) {\n throw new UnversionedStoreError();\n }\n const parsed = BundleIR.parse(bundle);\n // Before any write: a bad hash must not reach the store, where it would address content it does not describe\n verifyBundleHashes(parsed);\n // Nor a bundle the database cannot hold: the host migrates, the engine only checks\n const problems = (await store.checkSchema?.()) ?? [];\n if (problems.length > 0) throw new SchemaMismatchError(problems);\n\n for (const workflow of parsed.workflows) await store.putWorkflowIR(workflow);\n let applied = true;\n if (version === undefined) await store.replaceRoutes(parsed);\n else applied = (await store.replaceRoutesIfNewer?.(parsed, version)) ?? false;\n\n const unrouted = parsed.workflows\n .filter((workflow) => workflow.trigger.type === 'date' || workflow.trigger.type === 'webhook')\n .map((workflow) => ({ workflow: workflow.id, trigger: workflow.trigger.type }));\n\n return {\n workflows: parsed.workflows.map((w) => `${w.id}@${w.contentHash.slice(0, 8)}`),\n unrouted,\n applied,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,eAAe,eAAe,OAAqB,QAA+B;CAChF,IAAK,MAAM,MAAM,aAAa,MAAM,MAAO,QAAQ,MAAM,IAAIA,sBAAAA,gBAAgB,MAAM;AACrF;AAiCA,eAAsB,YACpB,KACA,OACA,QAAsBC,0BAAAA,QAAQ,GAAG,GACV;CACvB,IAAI,MAAM,MAAM,WAAW,GAAG,GAC5B,MAAM,IAAI,MAAM,eAAe,MAAM,MAAM,uCAAuC;CAIpF,MAAM,eAAe,OAAO,MAAM,MAAM;CACxC,MAAM,KAAK,MAAM,MAAM,KAAK,IAAI;CAChC,MAAM,UAAU,MAAM,WAAW,CAAC;CAIlC,MAAM,KAAK,MAAM,MAAM,OAAO,WAAW;CAEzC,MAAM,SAAS,MAAM,MAAM,YAAY;EACrC;EACA,QAAQ,MAAM;EACd,OAAO,MAAM;EACb;EACA;CACF,CAAC;CASD,MAAM,OAAO,MAAM,gBAAgB,KAAK,OAAO,MAAM,QAAQ,CAAC,M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