@shware/workflow 2.0.0 → 2.0.1
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/dist/config.cjs +2 -2
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +2 -2
- package/dist/config.mjs.map +1 -1
- package/dist/contract.cjs.map +1 -1
- package/dist/contract.d.cts +1 -1
- package/dist/contract.d.cts.map +1 -1
- package/dist/contract.d.mts +1 -1
- package/dist/contract.d.mts.map +1 -1
- package/dist/contract.mjs.map +1 -1
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +2 -2
- package/dist/dsl/action.d.cts.map +1 -1
- package/dist/dsl/action.d.mts +2 -2
- package/dist/dsl/action.d.mts.map +1 -1
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts +1 -1
- package/dist/dsl/bundle.d.mts +1 -1
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +1 -1
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +1 -1
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/refs.cjs.map +1 -1
- package/dist/dsl/refs.d.cts +5 -4
- package/dist/dsl/refs.d.cts.map +1 -1
- package/dist/dsl/refs.d.mts +5 -4
- package/dist/dsl/refs.d.mts.map +1 -1
- package/dist/dsl/refs.mjs.map +1 -1
- package/dist/dsl/template.cjs.map +1 -1
- package/dist/dsl/template.d.cts +2 -2
- package/dist/dsl/template.d.cts.map +1 -1
- package/dist/dsl/template.d.mts +2 -2
- package/dist/dsl/template.d.mts.map +1 -1
- package/dist/dsl/template.mjs.map +1 -1
- 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.map +1 -1
- package/dist/reporting/tracking.cjs +5 -1
- package/dist/reporting/tracking.cjs.map +1 -1
- package/dist/reporting/tracking.d.cts.map +1 -1
- package/dist/reporting/tracking.d.mts.map +1 -1
- package/dist/reporting/tracking.mjs +5 -1
- package/dist/reporting/tracking.mjs.map +1 -1
- package/dist/store/postgres-reporting.cjs +5 -5
- package/dist/store/postgres-reporting.cjs.map +1 -1
- package/dist/store/postgres-reporting.mjs +5 -5
- package/dist/store/postgres-reporting.mjs.map +1 -1
- package/dist/templates.cjs.map +1 -1
- package/dist/templates.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interpreter.mjs","names":[],"sources":["../../src/engine/interpreter.ts"],"sourcesContent":["import type { NodeIR, PropValueIR, ScalarIR, WorkflowIR } from '../ir';\nimport { hashToBucket } from './bucket';\nimport { evaluateCondition, relevantEvents } from './condition';\nimport type { FactSource, JourneyContext, JourneyOutcome, OutboundMessage } from './ports';\nimport { RECIPIENT_PROPERTY } from './recipient';\nimport { nextWindowStart } from './time-window';\n\n/**\n * IR interpreter: the execution core for one user's journey instance.\n *\n * Pure logic — it imports nothing platform-specific; every external effect\n * arrives through the JourneyContext ports, and durable semantics\n * (checkpoint/replay) are the EngineStep adapter's job.\n *\n * Step naming: an IR node id *is* the step name (derived from the structural\n * path, so it is deterministic and unique). When one node needs several steps,\n * a suffix is appended (`${id}:guard`, `${id}:check:${n}`).\n *\n * Guard semantics: goal / exitWhen are checked at journey entry and after\n * every suspension point (delay / random_delay / time_window / wait_until) —\n * the moments where wall-clock time passed and the user's state may have\n * moved. Between two synchronous nodes no meaningful time passes, so checking\n * there would only burn step budget (each checkpoint costs a state write).\n */\n\n/**\n * Cap on wait_until re-evaluations: beyond it we treat the wait as timed out,\n * so a wake-up storm cannot exhaust the platform's step budget. Each loop\n * iteration costs a handful of steps, so 64 checks stay well inside the\n * platform step budgets while absorbing far more wake churn than 16 did.\n */\nconst MAX_WAIT_CHECKS = 64;\n\n/** The user property holding an IANA timezone id, read when a time_window says tz: 'user'. Same convention-table status as RECIPIENT_PROPERTY. */\nconst TIMEZONE_PROPERTY = 'timezone';\n\ntype FlowSignal =\n | { kind: 'fall_through' }\n | { kind: 'exit'; reason?: string }\n | { kind: 'goal' }\n | { kind: 'exit_when' };\n\nconst FALL_THROUGH: FlowSignal = { kind: 'fall_through' };\n\n/**\n * Whether and when the instance converted — a fact of its own, apart from how it ends: with\n * `exitOnMatch: false` a conversion lets the flow go on, and the instance still ends `completed`\n * (or `exited`, `exit_when`) carrying it. Set only from checkpointed step results, so a replay\n * rebuilds the same state.\n */\ninterface GoalState {\n convertedAt?: number;\n}\n\nconst goalStates = new WeakMap<JourneyContext, GoalState>();\n\nfunction goalState(ctx: JourneyContext): GoalState {\n let state = goalStates.get(ctx);\n if (state === undefined) {\n state = {};\n goalStates.set(ctx, state);\n }\n return state;\n}\n\n/** When the goal's attribution window closes, measured from entry; none without `within`. */\nfunction goalDeadline(ir: WorkflowIR, ctx: JourneyContext): number | undefined {\n return ir.goal?.within === undefined ? undefined : ctx.enteredAtMs + ir.goal.within.ms;\n}\n\n/**\n * Whether the goal holds for events inside its window: after entry, and not after the window\n * closed — an instance resumed past the deadline must not count a purchase made after it. The\n * conversion time is when the check saw it, capped at the deadline.\n */\nasync function goalReached(\n ir: WorkflowIR,\n ctx: JourneyContext,\n now: number\n): Promise<{ at: number } | null> {\n const goal = ir.goal;\n if (goal === undefined) return null;\n const deadline = goalDeadline(ir, ctx);\n const met = await evaluateCondition(goal.condition, ctx.facts, now, {\n anchorMs: ctx.enteredAtMs,\n ...(deadline === undefined ? {} : { untilMs: deadline }),\n });\n return met ? { at: deadline === undefined ? now : Math.min(now, deadline) } : null;\n}\n\nexport async function runJourney(ir: WorkflowIR, ctx: JourneyContext): Promise<JourneyOutcome> {\n await started(ir, ctx);\n const entry = await checkGuards('entry', ir, ctx);\n let signal = entry ?? (await runFlow(ir.flow, ir, ctx));\n // The flow is done but the conversion window is not: keep watching it (see awaitTail)\n if (signal.kind === 'fall_through') signal = (await awaitTail(ir, ctx)) ?? FALL_THROUGH;\n const { convertedAt } = goalState(ctx);\n const converted = convertedAt === undefined ? {} : { convertedAt };\n switch (signal.kind) {\n case 'fall_through':\n return { status: 'completed', ...converted };\n case 'exit':\n return signal.reason !== undefined\n ? { status: 'exited', reason: signal.reason, ...converted }\n : { status: 'exited', ...converted };\n case 'goal':\n return { status: 'goal', ...converted };\n case 'exit_when':\n return { status: 'exit_when', ...converted };\n }\n}\n\nasync function runFlow(nodes: NodeIR[], ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal> {\n for (const node of nodes) {\n await reached(node, ir, ctx);\n const signal = await runNode(node, ir, ctx);\n if (signal.kind !== 'fall_through') return signal;\n }\n return FALL_THROUGH;\n}\n\n/**\n * Tell the observer the instance entered — before the entry guards, which can end it before the\n * first node: an instance is counted from its entry, not from its first node.\n */\nasync function started(ir: WorkflowIR, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n if (observer?.started === undefined) return;\n await ctx.step.do('entry:started', async () => {\n await observer.started?.({\n workflow: ir.id,\n instanceId: ctx.instanceId,\n userId: ctx.userId,\n at: ctx.enteredAtMs,\n });\n });\n}\n\n/**\n * Tell the observer the instance is at `node`. A step of its own, so a replay does not report\n * the nodes it passes on the way back again, and the arrival time stays the first one.\n */\nasync function reached(node: NodeIR, ir: WorkflowIR, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n if (observer?.nodeReached === undefined) return;\n await ctx.step.do(`${node.id}:reached`, async () => {\n await observer.nodeReached?.({\n workflow: ir.id,\n instanceId: ctx.instanceId,\n userId: ctx.userId,\n nodeId: node.id,\n at: Date.now(),\n });\n });\n}\n\n/**\n * One copy out through the host's sender, with the observer on both sides: it may attach\n * tracking before, and hears how the transport took the copy after. A send that throws is\n * not reported — the step retries it, and reports when it settles. A report that fails after\n * the send is logged, never thrown: the step would retry and the transport — a webhook, a web\n * push, with no idempotency key of its own — would deliver the copy again.\n */\nasync function deliver(message: OutboundMessage, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n const tracking = await observer?.messagePrepared?.(message);\n const copy = tracking === undefined ? message : { ...message, tracking };\n const result = await ctx.messages.send(copy);\n try {\n await observer?.messageSent?.(copy, result ?? { delivered: true });\n } catch (error) {\n console.error(`[workflow] reporting ${copy.idempotencyKey} as sent failed`, error);\n }\n}\n\n/**\n * Goal / exitWhen guards (see the header for when they run).\n *\n * The goal condition is anchored at workflow entry: a `performed` inside it\n * only counts events after the user entered, so pre-existing history cannot\n * register as a conversion. exitWhen is deliberately unanchored — \"user\n * unsubscribed\" should exit no matter when it happened.\n */\nasync function checkGuards(\n stepId: string,\n ir: WorkflowIR,\n ctx: JourneyContext\n): Promise<FlowSignal | null> {\n const goal = ir.goal;\n const exitWhen = ir.exitWhen;\n if (goal === undefined && exitWhen === undefined) return null;\n\n const state = goalState(ctx);\n const result = await ctx.step.do(`${stepId}:guard`, async () => {\n const now = Date.now();\n // Already converted (exitOnMatch: false): the conversion stands, no need to look again\n const goalHit =\n goal !== undefined && state.convertedAt === undefined\n ? await goalReached(ir, ctx, now)\n : null;\n const exitMet = exitWhen !== undefined && (await evaluateCondition(exitWhen, ctx.facts, now));\n return { goalAt: goalHit?.at ?? null, exitMet };\n });\n\n // A checkpoint from before conversions carried a time held `goalMet` instead: met at entry's anchor\n const legacy = result as { goalMet?: boolean };\n const goalAt =\n typeof result.goalAt === 'number'\n ? result.goalAt\n : legacy.goalMet === true\n ? ctx.enteredAtMs\n : null;\n if (goalAt !== null) {\n state.convertedAt ??= goalAt;\n if (goal?.exitOnMatch ?? true) return { kind: 'goal' };\n }\n if (result.exitMet) return { kind: 'exit_when' };\n return null;\n}\n\n/**\n * The host's template check, with the instance and node added to the message:\n * a refused message must point at the journey that produced it. The error\n * keeps its class (and `name`), so adapters can stop retrying it.\n */\nfunction validate(\n node: Extract<NodeIR, { type: 'message' }>,\n props: Record<string, ScalarIR | undefined>,\n ctx: JourneyContext\n): Record<string, ScalarIR | undefined> {\n if (ctx.validator === undefined) return props;\n try {\n return ctx.validator.validate({ channel: node.channel, template: node.template, props });\n } catch (error) {\n if (error instanceof Error) {\n error.message = `[${ctx.instanceId} ${node.id}] ${error.message}`;\n }\n throw error;\n }\n}\n\n/**\n * A push goes to devices, not to a profile address: one copy per device the\n * host's directory lists (or only the most recent, `devices: 'latest'`). Each\n * copy's idempotency key carries its token, so a retried step that already\n * reached some devices re-sends to the rest and the senders drop the repeats —\n * keyed by token rather than position, because the list can change between\n * attempts. A user with no device is skipped, not failed: being unreachable is\n * a state of the user, and `reachable('push')` is how a journey branches on it.\n */\n/**\n * A push: one step settles what goes out and to which devices, then each device gets a step of\n * its own — a failure on one device retries that device alone, and the copies already delivered\n * are not sent again (APNs and FCM carry the idempotency key but do not de-duplicate on it).\n */\nasync function sendPush(\n node: Extract<NodeIR, { type: 'message' }>,\n ir: WorkflowIR,\n ctx: JourneyContext\n): Promise<void> {\n const plan = await ctx.step.do(`${node.id}:send`, async () => {\n const props = validate(node, await resolveValues(node.props, ctx.facts), ctx);\n if (await ctx.facts.isSuppressed?.(node.channel)) return null;\n const listed = await ctx.facts.listDevices();\n const devices = node.devices === 'latest' ? listed.slice(0, 1) : listed;\n return { props, devices };\n });\n // null: the channel is opted out. Undefined: a checkpoint from before per-device steps, whose\n // single step already sent to every device.\n if (plan === null || plan === undefined) return;\n if (plan.devices.length === 0) {\n console.log(`[journey] push ${node.template} skipped: no device for user ${ctx.userId}`);\n return;\n }\n for (const [index, device] of plan.devices.entries()) {\n await ctx.step.do(`${node.id}:send:${index}`, async () => {\n await deliver(\n {\n workflow: ir.id,\n instanceId: ctx.instanceId,\n nodeId: node.id,\n channel: 'push',\n template: node.template,\n props: plan.props,\n userId: ctx.userId,\n recipient: device.token,\n device,\n idempotencyKey: `${ctx.instanceId}:${node.id}:${device.token}`,\n },\n ctx\n );\n });\n }\n}\n\nasync function runNode(node: NodeIR, ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal> {\n switch (node.type) {\n case 'message': {\n if (node.channel === 'push') {\n await sendPush(node, ir, ctx);\n return FALL_THROUGH;\n }\n await ctx.step.do(`${node.id}:send`, async () => {\n const props = validate(node, await resolveValues(node.props, ctx.facts), ctx);\n // An opted-out channel (an email unsubscribe) is skipped, like a push with no device\n if (await ctx.facts.isSuppressed?.(node.channel)) return;\n const recipientPath = RECIPIENT_PROPERTY[node.channel];\n const recipient =\n recipientPath === undefined ? undefined : await ctx.facts.getProperty(recipientPath);\n await deliver(\n {\n workflow: ir.id,\n instanceId: ctx.instanceId,\n nodeId: node.id,\n channel: node.channel,\n template: node.template,\n props,\n userId: ctx.userId,\n recipient: recipient === undefined ? undefined : String(recipient),\n idempotencyKey: `${ctx.instanceId}:${node.id}`,\n },\n ctx\n );\n });\n return FALL_THROUGH;\n }\n\n case 'delay': {\n await ctx.step.sleep(node.id, node.duration.ms);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'random_delay': {\n // The random value is drawn and persisted inside the step, so replay does not re-roll it\n const ms = await ctx.step.do(`${node.id}:roll`, async () => {\n const span = node.max.ms - node.min.ms;\n return node.min.ms + Math.floor(Math.random() * Math.max(span, 0));\n });\n await ctx.step.sleep(`${node.id}:sleep`, ms);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'time_window': {\n const target = await ctx.step.do(`${node.id}:target`, async () => {\n const tz =\n node.tz === 'user'\n ? String((await ctx.facts.getProperty(TIMEZONE_PROPERTY)) ?? 'UTC')\n : node.tz;\n return nextWindowStart(Date.now(), node.days, node.between, tz);\n });\n if (target === null) return FALL_THROUGH; // already inside the window: no suspension, no guard\n await ctx.step.sleepUntil(`${node.id}:sleep`, target);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'wait_until': {\n const met = await waitUntil(node, ctx);\n // Time passed while waiting — guard before acting on the outcome (goal wins over the wait result)\n const guard = await checkGuards(node.id, ir, ctx);\n if (guard) return guard;\n if (met) return FALL_THROUGH;\n const onTimeout = node.onTimeout;\n if (onTimeout === 'continue') return FALL_THROUGH;\n if (onTimeout === 'exit') return { kind: 'exit', reason: `${node.id}:timeout` };\n return runFlow(onTimeout, ir, ctx);\n }\n\n case 'branch': {\n const matched = await ctx.step.do(`${node.id}:eval`, async () => {\n const now = Date.now();\n for (const [i, branchCase] of node.cases.entries()) {\n if (await evaluateCondition(branchCase.condition, ctx.facts, now)) {\n return i;\n }\n }\n return -1; // no match → default arm, or simply continue\n });\n const flow = matched >= 0 ? node.cases[matched]?.flow : node.otherwise;\n if (flow === undefined) return FALL_THROUGH;\n const signal = await runFlow(flow, ir, ctx);\n // Structural rejoin: once an arm falls through, execution resumes after the branch\n return signal;\n }\n\n case 'filter': {\n const pass = await ctx.step.do(`${node.id}:eval`, async () =>\n evaluateCondition(node.condition, ctx.facts, Date.now())\n );\n return pass ? FALL_THROUGH : { kind: 'exit', reason: node.reason ?? `${node.id}:filtered` };\n }\n\n case 'cohort': {\n // Deterministic bucketing, so replay needs no checkpoint. The explicit\n // experiment key (when set) keeps the assignment stable across workflow\n // versions; the structural id fallback is fine for one-off splits.\n const bucket = hashToBucket(`${ctx.userId}:${node.key ?? node.id}`);\n // Integer basis points on both sides (the DSL guarantees weights sit on\n // the 0.01% grid), so no float ever meets the comparison.\n let cumulative = 0;\n for (const arm of node.arms) {\n cumulative += Math.round(arm.weight * 100);\n if (bucket < cumulative) return runFlow(arm.flow, ir, ctx);\n }\n return FALL_THROUGH;\n }\n\n case 'exit':\n return node.reason !== undefined ? { kind: 'exit', reason: node.reason } : { kind: 'exit' };\n\n case 'send_event': {\n await ctx.step.do(`${node.id}:emit`, async () => {\n const payload = await resolveValues(node.payload, ctx.facts);\n try {\n await ctx.events.emit(node.event, payload, `${ctx.instanceId}:${node.id}`);\n } catch (error) {\n // A refused event must point at the journey that emitted it\n if (error instanceof Error)\n error.message = `[${ctx.instanceId} ${node.id}] ${error.message}`;\n throw error;\n }\n });\n return FALL_THROUGH;\n }\n\n case 'action': {\n // Custom code runs inside step.do: retried on throw, checkpointed on success\n const invoker = ctx.actions;\n if (invoker === undefined) {\n throw new Error(\n `action '${node.action}': this runtime has no ActionInvoker configured — register the action on the adapter (see engine/actions.ts)`\n );\n }\n await ctx.step.do(`${node.id}:run`, async () => {\n const args = await resolveValues(node.args, ctx.facts);\n await invoker.invoke({\n action: node.action,\n codeHash: node.codeHash,\n args,\n userId: ctx.userId,\n idempotencyKey: `${ctx.instanceId}:${node.id}`,\n });\n });\n return FALL_THROUGH;\n }\n }\n}\n\nasync function waitUntil(\n node: Extract<NodeIR, { type: 'wait_until' }>,\n ctx: JourneyContext\n): Promise<boolean> {\n const deadline = await ctx.step.do(\n `${node.id}:deadline`,\n async () => Date.now() + node.timeout.ms\n );\n const events = await ctx.step.do(`${node.id}:events`, async () =>\n relevantEvents(node.condition, ctx.facts)\n );\n // Anchor at the moment the wait began (deadline is checkpointed, so this is\n // replay-stable): `performed` inside the condition only counts events that\n // happen during the wait — pre-existing history must not satisfy it.\n const anchorMs = deadline - node.timeout.ms;\n const met = await waitLoop(node.id, ctx, deadline, events, async (now) =>\n (await evaluateCondition(node.condition, ctx.facts, now, { anchorMs })) ? true : null\n );\n await ctx.step.unsubscribe(`${node.id}:unsubscribe`);\n return met === true;\n}\n\n/**\n * The conversion window outlives the flow: a journey whose steps are done while its goal's\n * `within` is still open keeps watching until the window closes — the purchase that follows the\n * last offer email is that email's conversion, and ending the instance at the email would report\n * it as a plain completion. `exitWhen` still applies while it waits. Nothing to wait for without\n * a window, or once the instance has converted.\n */\nasync function awaitTail(ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal | null> {\n const deadline = goalDeadline(ir, ctx);\n const goal = ir.goal;\n if (goal === undefined || deadline === undefined) return null;\n const state = goalState(ctx);\n if (state.convertedAt !== undefined) return null;\n const open = await ctx.step.do('goal:open', async () => deadline > Date.now());\n if (!open) return null;\n const exitWhen = ir.exitWhen;\n const events = await ctx.step.do('goal:events', async () => [\n ...new Set([\n ...(await relevantEvents(goal.condition, ctx.facts)),\n ...(exitWhen === undefined ? [] : await relevantEvents(exitWhen, ctx.facts)),\n ]),\n ]);\n const hit = await waitLoop('goal', ctx, deadline, events, async (now) => {\n const reached = await goalReached(ir, ctx, now);\n if (reached !== null) return { kind: 'goal' as const, at: reached.at };\n if (exitWhen !== undefined && (await evaluateCondition(exitWhen, ctx.facts, now))) {\n return { kind: 'exit_when' as const, at: now };\n }\n return null;\n });\n await ctx.step.unsubscribe('goal:unsubscribe');\n if (hit === null) return null;\n // A checkpoint from before the tail watched exitWhen recorded a plain `true`: the goal\n if ((hit as unknown) === true || hit.kind === 'goal') {\n state.convertedAt ??= (hit as { at?: number }).at ?? deadline;\n return { kind: 'goal' };\n }\n return { kind: 'exit_when' };\n}\n\n/**\n * Wait until `check` finds something or the deadline passes: subscribe, check, sleep until a\n * relevant event wakes the instance or time runs out. `check` runs inside a step, so its result\n * must be serializable; null means \"not yet\".\n */\nasync function waitLoop<R>(\n id: string,\n ctx: JourneyContext,\n deadline: number,\n events: string[],\n check: (now: number) => Promise<R | null>\n): Promise<R | null> {\n for (let attempt = 0; attempt < MAX_WAIT_CHECKS; attempt++) {\n // Subscribe before the check, every attempt: one subscribe arms at least\n // one wake-up (AWS callbacks are consumed on delivery, so each attempt\n // needs a fresh arm; Cloudflare rows make the repeat call idempotent), and\n // arming first closes the race where the event lands between the check and\n // the registration.\n await ctx.step.subscribe(`${id}:subscribe:${attempt}`, events);\n\n const met = await ctx.step.do(`${id}:check:${attempt}`, async () => check(Date.now()));\n // `false` is a checkpoint from before checks answered null for \"not yet\"\n if (met !== null && (met as unknown) !== false) return met;\n\n // Checkpointed: replay re-runs this control flow with wall-clock time far\n // ahead of the original run, so the branch must come from a persisted value.\n const remaining = await ctx.step.do(\n `${id}:remaining:${attempt}`,\n async () => deadline - Date.now()\n );\n // The condition was checked just above — expiring here needs no extra final check\n if (remaining <= 0) return null;\n\n const wake = await ctx.step.waitForWake(`${id}:wait:${attempt}`, remaining);\n if (wake === 'timeout') {\n // Final check after timeout: in a tight race the event may land exactly as the timer fires\n const final = await ctx.step.do(`${id}:final`, async () => check(Date.now()));\n return (final as unknown) === false ? null : final;\n }\n // Woken → back to the top of the loop to re-evaluate (at-least-once wake-up semantics)\n }\n return null; // check budget exhausted → treated as timed out (see MAX_WAIT_CHECKS)\n}\n\nasync function resolveValues(\n values: Record<string, PropValueIR>,\n facts: FactSource\n): Promise<Record<string, ScalarIR | undefined>> {\n const resolved: Record<string, ScalarIR | undefined> = {};\n for (const [key, value] of Object.entries(values)) {\n resolved[key] = typeof value === 'object' ? await facts.getProperty(value.path) : value;\n }\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,kBAAkB;;AAGxB,MAAM,oBAAoB;AAQ1B,MAAM,eAA2B,EAAE,MAAM,eAAe;AAYxD,MAAM,6BAAa,IAAI,QAAmC;AAE1D,SAAS,UAAU,KAAgC;CACjD,IAAI,QAAQ,WAAW,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,CAAC;EACT,WAAW,IAAI,KAAK,KAAK;CAC3B;CACA,OAAO;AACT;;AAGA,SAAS,aAAa,IAAgB,KAAyC;CAC7E,OAAO,GAAG,MAAM,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,cAAc,GAAG,KAAK,OAAO;AACtF;;;;;;AAOA,eAAe,YACb,IACA,KACA,KACgC;CAChC,MAAM,OAAO,GAAG;CAChB,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,MAAM,WAAW,aAAa,IAAI,GAAG;CAKrC,OAAO,MAJW,kBAAkB,KAAK,WAAW,IAAI,OAAO,KAAK;EAClE,UAAU,IAAI;EACd,GAAI,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,SA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Y,GAAG,GAAG,QAAQ,WAAW,SAAS,MAC7D,WAAW;GAEtB,MAAM,QAAQ,MAAM,IAAI,KAAK,GAAG,GAAG,GAAG,SAAS,YAAY,MAAM,KAAK,IAAI,CAAC,CAAC;GAC5E,OAAQ,UAAsB,QAAQ,OAAO;EAC/C;CAEF;CACA,OAAO;AACT;AAEA,eAAe,cACb,QACA,OAC+C;CAC/C,MAAM,WAAiD,CAAC;CACxD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,SAAS,OAAO,OAAO,UAAU,WAAW,MAAM,MAAM,YAAY,MAAM,IAAI,IAAI;CAEpF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"interpreter.mjs","names":[],"sources":["../../src/engine/interpreter.ts"],"sourcesContent":["import type { NodeIR, PropValueIR, ScalarIR, WorkflowIR } from '../ir';\nimport { hashToBucket } from './bucket';\nimport { evaluateCondition, relevantEvents } from './condition';\nimport type {\n FactSource,\n JourneyContext,\n JourneyOutcome,\n OutboundMessage,\n PushDevice,\n} from './ports';\nimport { RECIPIENT_PROPERTY } from './recipient';\nimport { nextWindowStart } from './time-window';\n\n/**\n * IR interpreter: the execution core for one user's journey instance.\n *\n * Pure logic — it imports nothing platform-specific; every external effect\n * arrives through the JourneyContext ports, and durable semantics\n * (checkpoint/replay) are the EngineStep adapter's job.\n *\n * Step naming: an IR node id *is* the step name (derived from the structural\n * path, so it is deterministic and unique). When one node needs several steps,\n * a suffix is appended (`${id}:guard`, `${id}:check:${n}`).\n *\n * Guard semantics: goal / exitWhen are checked at journey entry and after\n * every suspension point (delay / random_delay / time_window / wait_until) —\n * the moments where wall-clock time passed and the user's state may have\n * moved. Between two synchronous nodes no meaningful time passes, so checking\n * there would only burn step budget (each checkpoint costs a state write).\n */\n\n/**\n * Cap on wait_until re-evaluations: beyond it we treat the wait as timed out,\n * so a wake-up storm cannot exhaust the platform's step budget. Each loop\n * iteration costs a handful of steps, so 64 checks stay well inside the\n * platform step budgets while absorbing far more wake churn than 16 did.\n */\nconst MAX_WAIT_CHECKS = 64;\n\n/** The user property holding an IANA timezone id, read when a time_window says tz: 'user'. Same convention-table status as RECIPIENT_PROPERTY. */\nconst TIMEZONE_PROPERTY = 'timezone';\n\ntype FlowSignal =\n | { kind: 'fall_through' }\n | { kind: 'exit'; reason?: string }\n | { kind: 'goal' }\n | { kind: 'exit_when' };\n\nconst FALL_THROUGH: FlowSignal = { kind: 'fall_through' };\n\n/**\n * Whether and when the instance converted — a fact of its own, apart from how it ends: with\n * `exitOnMatch: false` a conversion lets the flow go on, and the instance still ends `completed`\n * (or `exited`, `exit_when`) carrying it. Set only from checkpointed step results, so a replay\n * rebuilds the same state.\n */\ninterface GoalState {\n convertedAt?: number;\n}\n\nconst goalStates = new WeakMap<JourneyContext, GoalState>();\n\nfunction goalState(ctx: JourneyContext): GoalState {\n let state = goalStates.get(ctx);\n if (state === undefined) {\n state = {};\n goalStates.set(ctx, state);\n }\n return state;\n}\n\n/** When the goal's attribution window closes, measured from entry; none without `within`. */\nfunction goalDeadline(ir: WorkflowIR, ctx: JourneyContext): number | undefined {\n return ir.goal?.within === undefined ? undefined : ctx.enteredAtMs + ir.goal.within.ms;\n}\n\n/**\n * Whether the goal holds for events inside its window: after entry, and not after the window\n * closed — an instance resumed past the deadline must not count a purchase made after it. The\n * conversion time is when the check saw it, capped at the deadline.\n */\nasync function goalReached(\n ir: WorkflowIR,\n ctx: JourneyContext,\n now: number\n): Promise<{ at: number } | null> {\n const goal = ir.goal;\n if (goal === undefined) return null;\n const deadline = goalDeadline(ir, ctx);\n const met = await evaluateCondition(goal.condition, ctx.facts, now, {\n anchorMs: ctx.enteredAtMs,\n ...(deadline === undefined ? {} : { untilMs: deadline }),\n });\n return met ? { at: deadline === undefined ? now : Math.min(now, deadline) } : null;\n}\n\nexport async function runJourney(ir: WorkflowIR, ctx: JourneyContext): Promise<JourneyOutcome> {\n await started(ir, ctx);\n const entry = await checkGuards('entry', ir, ctx);\n let signal = entry ?? (await runFlow(ir.flow, ir, ctx));\n // The flow is done but the conversion window is not: keep watching it (see awaitTail)\n if (signal.kind === 'fall_through') signal = (await awaitTail(ir, ctx)) ?? FALL_THROUGH;\n const { convertedAt } = goalState(ctx);\n const converted = convertedAt === undefined ? {} : { convertedAt };\n switch (signal.kind) {\n case 'fall_through':\n return { status: 'completed', ...converted };\n case 'exit':\n return signal.reason !== undefined\n ? { status: 'exited', reason: signal.reason, ...converted }\n : { status: 'exited', ...converted };\n case 'goal':\n return { status: 'goal', ...converted };\n case 'exit_when':\n return { status: 'exit_when', ...converted };\n }\n}\n\nasync function runFlow(nodes: NodeIR[], ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal> {\n for (const node of nodes) {\n await reached(node, ir, ctx);\n const signal = await runNode(node, ir, ctx);\n if (signal.kind !== 'fall_through') return signal;\n }\n return FALL_THROUGH;\n}\n\n/**\n * Tell the observer the instance entered — before the entry guards, which can end it before the\n * first node: an instance is counted from its entry, not from its first node.\n */\nasync function started(ir: WorkflowIR, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n if (observer?.started === undefined) return;\n await ctx.step.do('entry:started', async () => {\n await observer.started?.({\n workflow: ir.id,\n instanceId: ctx.instanceId,\n userId: ctx.userId,\n at: ctx.enteredAtMs,\n });\n });\n}\n\n/**\n * Tell the observer the instance is at `node`. A step of its own, so a replay does not report\n * the nodes it passes on the way back again, and the arrival time stays the first one.\n */\nasync function reached(node: NodeIR, ir: WorkflowIR, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n if (observer?.nodeReached === undefined) return;\n await ctx.step.do(`${node.id}:reached`, async () => {\n await observer.nodeReached?.({\n workflow: ir.id,\n instanceId: ctx.instanceId,\n userId: ctx.userId,\n nodeId: node.id,\n at: Date.now(),\n });\n });\n}\n\n/**\n * One copy out through the host's sender, with the observer on both sides: it may attach\n * tracking before, and hears how the transport took the copy after. A send that throws is\n * not reported — the step retries it, and reports when it settles. A report that fails after\n * the send is logged, never thrown: the step would retry and the transport — a webhook, a web\n * push, with no idempotency key of its own — would deliver the copy again.\n */\nasync function deliver(message: OutboundMessage, ctx: JourneyContext): Promise<void> {\n const observer = ctx.observer;\n const tracking = await observer?.messagePrepared?.(message);\n const copy = tracking === undefined ? message : { ...message, tracking };\n const result = await ctx.messages.send(copy);\n try {\n await observer?.messageSent?.(copy, result ?? { delivered: true });\n } catch (error) {\n console.error(`[workflow] reporting ${copy.idempotencyKey} as sent failed`, error);\n }\n}\n\n/**\n * Goal / exitWhen guards (see the header for when they run).\n *\n * The goal condition is anchored at workflow entry: a `performed` inside it\n * only counts events after the user entered, so pre-existing history cannot\n * register as a conversion. exitWhen is deliberately unanchored — \"user\n * unsubscribed\" should exit no matter when it happened.\n */\nasync function checkGuards(\n stepId: string,\n ir: WorkflowIR,\n ctx: JourneyContext\n): Promise<FlowSignal | null> {\n const goal = ir.goal;\n const exitWhen = ir.exitWhen;\n if (goal === undefined && exitWhen === undefined) return null;\n\n const state = goalState(ctx);\n const result = await ctx.step.do(`${stepId}:guard`, async () => {\n const now = Date.now();\n // Already converted (exitOnMatch: false): the conversion stands, no need to look again\n const goalHit =\n goal !== undefined && state.convertedAt === undefined\n ? await goalReached(ir, ctx, now)\n : null;\n const exitMet = exitWhen !== undefined && (await evaluateCondition(exitWhen, ctx.facts, now));\n return { goalAt: goalHit?.at ?? null, exitMet };\n });\n\n // A checkpoint from before conversions carried a time held `goalMet` instead: met at entry's anchor\n const legacy = result as { goalMet?: boolean };\n const goalAt =\n typeof result.goalAt === 'number'\n ? result.goalAt\n : legacy.goalMet === true\n ? ctx.enteredAtMs\n : null;\n if (goalAt !== null) {\n state.convertedAt ??= goalAt;\n if (goal?.exitOnMatch ?? true) return { kind: 'goal' };\n }\n if (result.exitMet) return { kind: 'exit_when' };\n return null;\n}\n\n/**\n * The host's template check, with the instance and node added to the message:\n * a refused message must point at the journey that produced it. The error\n * keeps its class (and `name`), so adapters can stop retrying it.\n */\nfunction validate(\n node: Extract<NodeIR, { type: 'message' }>,\n props: Record<string, ScalarIR | undefined>,\n ctx: JourneyContext\n): Record<string, ScalarIR | undefined> {\n if (ctx.validator === undefined) return props;\n try {\n return ctx.validator.validate({ channel: node.channel, template: node.template, props });\n } catch (error) {\n if (error instanceof Error) {\n error.message = `[${ctx.instanceId} ${node.id}] ${error.message}`;\n }\n throw error;\n }\n}\n\ntype PushPlan = { props: Record<string, ScalarIR | undefined>; devices: PushDevice[] };\n\n/**\n * A push goes to devices, not to a profile address: one copy per device the\n * host's directory lists (or only the most recent, `devices: 'latest'`). Each\n * copy's idempotency key carries its token, so a retried step that already\n * reached some devices re-sends to the rest and the senders drop the repeats —\n * keyed by token rather than position, because the list can change between\n * attempts. A user with no device is skipped, not failed: being unreachable is\n * a state of the user, and `reachable('push')` is how a journey branches on it.\n */\n/**\n * A push: one step settles what goes out and to which devices, then each device gets a step of\n * its own — a failure on one device retries that device alone, and the copies already delivered\n * are not sent again (APNs and FCM carry the idempotency key but do not de-duplicate on it).\n */\nasync function sendPush(\n node: Extract<NodeIR, { type: 'message' }>,\n ir: WorkflowIR,\n ctx: JourneyContext\n): Promise<void> {\n const plan = await ctx.step.do<PushPlan | null | undefined>(`${node.id}:send`, async () => {\n const props = validate(node, await resolveValues(node.props, ctx.facts), ctx);\n if (await ctx.facts.isSuppressed?.(node.channel)) return null;\n const listed = await ctx.facts.listDevices();\n const devices = node.devices === 'latest' ? listed.slice(0, 1) : listed;\n return { props, devices };\n });\n // null: the channel is opted out. Undefined: a checkpoint from before per-device steps, whose\n // single step already sent to every device.\n if (plan === null || plan === undefined) return;\n if (plan.devices.length === 0) {\n console.log(`[journey] push ${node.template} skipped: no device for user ${ctx.userId}`);\n return;\n }\n for (const [index, device] of plan.devices.entries()) {\n await ctx.step.do(`${node.id}:send:${index}`, async () => {\n await deliver(\n {\n workflow: ir.id,\n instanceId: ctx.instanceId,\n nodeId: node.id,\n channel: 'push',\n template: node.template,\n props: plan.props,\n userId: ctx.userId,\n recipient: device.token,\n device,\n idempotencyKey: `${ctx.instanceId}:${node.id}:${device.token}`,\n },\n ctx\n );\n });\n }\n}\n\nasync function runNode(node: NodeIR, ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal> {\n switch (node.type) {\n case 'message': {\n if (node.channel === 'push') {\n await sendPush(node, ir, ctx);\n return FALL_THROUGH;\n }\n await ctx.step.do(`${node.id}:send`, async () => {\n const props = validate(node, await resolveValues(node.props, ctx.facts), ctx);\n // An opted-out channel (an email unsubscribe) is skipped, like a push with no device\n if (await ctx.facts.isSuppressed?.(node.channel)) return;\n const recipientPath = RECIPIENT_PROPERTY[node.channel];\n const recipient =\n recipientPath === undefined ? undefined : await ctx.facts.getProperty(recipientPath);\n await deliver(\n {\n workflow: ir.id,\n instanceId: ctx.instanceId,\n nodeId: node.id,\n channel: node.channel,\n template: node.template,\n props,\n userId: ctx.userId,\n recipient: recipient === undefined ? undefined : String(recipient),\n idempotencyKey: `${ctx.instanceId}:${node.id}`,\n },\n ctx\n );\n });\n return FALL_THROUGH;\n }\n\n case 'delay': {\n await ctx.step.sleep(node.id, node.duration.ms);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'random_delay': {\n // The random value is drawn and persisted inside the step, so replay does not re-roll it\n const ms = await ctx.step.do(`${node.id}:roll`, async () => {\n const span = node.max.ms - node.min.ms;\n return node.min.ms + Math.floor(Math.random() * Math.max(span, 0));\n });\n await ctx.step.sleep(`${node.id}:sleep`, ms);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'time_window': {\n const target = await ctx.step.do(`${node.id}:target`, async () => {\n const tz =\n node.tz === 'user'\n ? String((await ctx.facts.getProperty(TIMEZONE_PROPERTY)) ?? 'UTC')\n : node.tz;\n return nextWindowStart(Date.now(), node.days, node.between, tz);\n });\n if (target === null) return FALL_THROUGH; // already inside the window: no suspension, no guard\n await ctx.step.sleepUntil(`${node.id}:sleep`, target);\n return (await checkGuards(node.id, ir, ctx)) ?? FALL_THROUGH;\n }\n\n case 'wait_until': {\n const met = await waitUntil(node, ctx);\n // Time passed while waiting — guard before acting on the outcome (goal wins over the wait result)\n const guard = await checkGuards(node.id, ir, ctx);\n if (guard) return guard;\n if (met) return FALL_THROUGH;\n const onTimeout = node.onTimeout;\n if (onTimeout === 'continue') return FALL_THROUGH;\n if (onTimeout === 'exit') return { kind: 'exit', reason: `${node.id}:timeout` };\n return runFlow(onTimeout, ir, ctx);\n }\n\n case 'branch': {\n const matched = await ctx.step.do(`${node.id}:eval`, async () => {\n const now = Date.now();\n for (const [i, branchCase] of node.cases.entries()) {\n if (await evaluateCondition(branchCase.condition, ctx.facts, now)) {\n return i;\n }\n }\n return -1; // no match → default arm, or simply continue\n });\n const flow = matched >= 0 ? node.cases[matched]?.flow : node.otherwise;\n if (flow === undefined) return FALL_THROUGH;\n const signal = await runFlow(flow, ir, ctx);\n // Structural rejoin: once an arm falls through, execution resumes after the branch\n return signal;\n }\n\n case 'filter': {\n const pass = await ctx.step.do(`${node.id}:eval`, async () =>\n evaluateCondition(node.condition, ctx.facts, Date.now())\n );\n return pass ? FALL_THROUGH : { kind: 'exit', reason: node.reason ?? `${node.id}:filtered` };\n }\n\n case 'cohort': {\n // Deterministic bucketing, so replay needs no checkpoint. The explicit\n // experiment key (when set) keeps the assignment stable across workflow\n // versions; the structural id fallback is fine for one-off splits.\n const bucket = hashToBucket(`${ctx.userId}:${node.key ?? node.id}`);\n // Integer basis points on both sides (the DSL guarantees weights sit on\n // the 0.01% grid), so no float ever meets the comparison.\n let cumulative = 0;\n for (const arm of node.arms) {\n cumulative += Math.round(arm.weight * 100);\n if (bucket < cumulative) return runFlow(arm.flow, ir, ctx);\n }\n return FALL_THROUGH;\n }\n\n case 'exit':\n return node.reason !== undefined ? { kind: 'exit', reason: node.reason } : { kind: 'exit' };\n\n case 'send_event': {\n await ctx.step.do(`${node.id}:emit`, async () => {\n const payload = await resolveValues(node.payload, ctx.facts);\n try {\n await ctx.events.emit(node.event, payload, `${ctx.instanceId}:${node.id}`);\n } catch (error) {\n // A refused event must point at the journey that emitted it\n if (error instanceof Error)\n error.message = `[${ctx.instanceId} ${node.id}] ${error.message}`;\n throw error;\n }\n });\n return FALL_THROUGH;\n }\n\n case 'action': {\n // Custom code runs inside step.do: retried on throw, checkpointed on success\n const invoker = ctx.actions;\n if (invoker === undefined) {\n throw new Error(\n `action '${node.action}': this runtime has no ActionInvoker configured — register the action on the adapter (see engine/actions.ts)`\n );\n }\n await ctx.step.do(`${node.id}:run`, async () => {\n const args = await resolveValues(node.args, ctx.facts);\n await invoker.invoke({\n action: node.action,\n codeHash: node.codeHash,\n args,\n userId: ctx.userId,\n idempotencyKey: `${ctx.instanceId}:${node.id}`,\n });\n });\n return FALL_THROUGH;\n }\n }\n}\n\nasync function waitUntil(\n node: Extract<NodeIR, { type: 'wait_until' }>,\n ctx: JourneyContext\n): Promise<boolean> {\n const deadline = await ctx.step.do(\n `${node.id}:deadline`,\n async () => Date.now() + node.timeout.ms\n );\n const events = await ctx.step.do(`${node.id}:events`, async () =>\n relevantEvents(node.condition, ctx.facts)\n );\n // Anchor at the moment the wait began (deadline is checkpointed, so this is\n // replay-stable): `performed` inside the condition only counts events that\n // happen during the wait — pre-existing history must not satisfy it.\n const anchorMs = deadline - node.timeout.ms;\n const met = await waitLoop(node.id, ctx, deadline, events, async (now) =>\n (await evaluateCondition(node.condition, ctx.facts, now, { anchorMs })) ? true : null\n );\n await ctx.step.unsubscribe(`${node.id}:unsubscribe`);\n return met === true;\n}\n\n/**\n * The conversion window outlives the flow: a journey whose steps are done while its goal's\n * `within` is still open keeps watching until the window closes — the purchase that follows the\n * last offer email is that email's conversion, and ending the instance at the email would report\n * it as a plain completion. `exitWhen` still applies while it waits. Nothing to wait for without\n * a window, or once the instance has converted.\n */\nasync function awaitTail(ir: WorkflowIR, ctx: JourneyContext): Promise<FlowSignal | null> {\n const deadline = goalDeadline(ir, ctx);\n const goal = ir.goal;\n if (goal === undefined || deadline === undefined) return null;\n const state = goalState(ctx);\n if (state.convertedAt !== undefined) return null;\n const open = await ctx.step.do('goal:open', async () => deadline > Date.now());\n if (!open) return null;\n const exitWhen = ir.exitWhen;\n const events = await ctx.step.do('goal:events', async () => [\n ...new Set([\n ...(await relevantEvents(goal.condition, ctx.facts)),\n ...(exitWhen === undefined ? [] : await relevantEvents(exitWhen, ctx.facts)),\n ]),\n ]);\n const hit = await waitLoop('goal', ctx, deadline, events, async (now) => {\n const reached = await goalReached(ir, ctx, now);\n if (reached !== null) return { kind: 'goal' as const, at: reached.at };\n if (exitWhen !== undefined && (await evaluateCondition(exitWhen, ctx.facts, now))) {\n return { kind: 'exit_when' as const, at: now };\n }\n return null;\n });\n await ctx.step.unsubscribe('goal:unsubscribe');\n if (hit === null) return null;\n // A checkpoint from before the tail watched exitWhen recorded a plain `true`: the goal\n if ((hit as unknown) === true || hit.kind === 'goal') {\n state.convertedAt ??= (hit as { at?: number }).at ?? deadline;\n return { kind: 'goal' };\n }\n return { kind: 'exit_when' };\n}\n\n/**\n * Wait until `check` finds something or the deadline passes: subscribe, check, sleep until a\n * relevant event wakes the instance or time runs out. `check` runs inside a step, so its result\n * must be serializable; null means \"not yet\".\n */\nasync function waitLoop<R>(\n id: string,\n ctx: JourneyContext,\n deadline: number,\n events: string[],\n check: (now: number) => Promise<R | null>\n): Promise<R | null> {\n for (let attempt = 0; attempt < MAX_WAIT_CHECKS; attempt++) {\n // Subscribe before the check, every attempt: one subscribe arms at least\n // one wake-up (AWS callbacks are consumed on delivery, so each attempt\n // needs a fresh arm; Cloudflare rows make the repeat call idempotent), and\n // arming first closes the race where the event lands between the check and\n // the registration.\n await ctx.step.subscribe(`${id}:subscribe:${attempt}`, events);\n\n const met = await ctx.step.do(`${id}:check:${attempt}`, async () => check(Date.now()));\n // `false` is a checkpoint from before checks answered null for \"not yet\"\n if (met !== null && (met as unknown) !== false) return met;\n\n // Checkpointed: replay re-runs this control flow with wall-clock time far\n // ahead of the original run, so the branch must come from a persisted value.\n const remaining = await ctx.step.do(\n `${id}:remaining:${attempt}`,\n async () => deadline - Date.now()\n );\n // The condition was checked just above — expiring here needs no extra final check\n if (remaining <= 0) return null;\n\n const wake = await ctx.step.waitForWake(`${id}:wait:${attempt}`, remaining);\n if (wake === 'timeout') {\n // Final check after timeout: in a tight race the event may land exactly as the timer fires\n const final = await ctx.step.do(`${id}:final`, async () => check(Date.now()));\n return (final as unknown) === false ? null : final;\n }\n // Woken → back to the top of the loop to re-evaluate (at-least-once wake-up semantics)\n }\n return null; // check budget exhausted → treated as timed out (see MAX_WAIT_CHECKS)\n}\n\nasync function resolveValues(\n values: Record<string, PropValueIR>,\n facts: FactSource\n): Promise<Record<string, ScalarIR | undefined>> {\n const resolved: Record<string, ScalarIR | undefined> = {};\n for (const [key, value] of Object.entries(values)) {\n resolved[key] = typeof value === 'object' ? await facts.getProperty(value.path) : value;\n }\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,kBAAkB;;AAGxB,MAAM,oBAAoB;AAQ1B,MAAM,eAA2B,EAAE,MAAM,eAAe;AAYxD,MAAM,6BAAa,IAAI,QAAmC;AAE1D,SAAS,UAAU,KAAgC;CACjD,IAAI,QAAQ,WAAW,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,CAAC;EACT,WAAW,IAAI,KAAK,KAAK;CAC3B;CACA,OAAO;AACT;;AAGA,SAAS,aAAa,IAAgB,KAAyC;CAC7E,OAAO,GAAG,MAAM,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,cAAc,GAAG,KAAK,OAAO;AACtF;;;;;;AAOA,eAAe,YACb,IACA,KACA,KACgC;CAChC,MAAM,OAAO,GAAG;CAChB,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,MAAM,WAAW,aAAa,IAAI,GAAG;CAKrC,OAAO,MAJW,kBAAkB,KAAK,WAAW,IAAI,OAAO,KAAK;EAClE,UAAU,IAAI;E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a,GAAG,OAAO;EAG3B,IAAI,MADe,IAAI,KAAK,YAAY,GAAG,GAAG,QAAQ,WAAW,SAAS,MAC7D,WAAW;GAEtB,MAAM,QAAQ,MAAM,IAAI,KAAK,GAAG,GAAG,GAAG,SAAS,YAAY,MAAM,KAAK,IAAI,CAAC,CAAC;GAC5E,OAAQ,UAAsB,QAAQ,OAAO;EAC/C;CAEF;CACA,OAAO;AACT;AAEA,eAAe,cACb,QACA,OAC+C;CAC/C,MAAM,WAAiD,CAAC;CACxD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,SAAS,OAAO,OAAO,UAAU,WAAW,MAAM,MAAM,YAAY,MAAM,IAAI,IAAI;CAEpF,OAAO;AACT"}
|
|
@@ -16,7 +16,11 @@ function requester(request) {
|
|
|
16
16
|
}
|
|
17
17
|
/** A `/t/...` request's response, or undefined when the path is not a tracking route. */
|
|
18
18
|
async function handleTracking(request, reporting, options = {}) {
|
|
19
|
-
const
|
|
19
|
+
const path = new URL(request.url).pathname.split("/");
|
|
20
|
+
const root = path.at(1);
|
|
21
|
+
const kind = path.at(2);
|
|
22
|
+
const id = path.at(3);
|
|
23
|
+
const position = path.at(4);
|
|
20
24
|
if (root !== "t" || id === void 0 || !UUID.test(id)) return void 0;
|
|
21
25
|
const who = requester(request);
|
|
22
26
|
const read = who.method === "GET" || who.method === "HEAD";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracking.cjs","names":["isUnsubscribeLink","classifyOpen","BURST_WINDOW_MS","classifyClick"],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import { isUnsubscribeLink } from '../email';\nimport type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/l/<message>/<position> a link: records the click, redirects to the recorded URL\n * GET /t/u/<message>/<position> the unsubscribe link: records the click, asks to confirm\n * POST /t/u/<message> the unsubscribe confirmation\n * GET /t/c/<message>/<position> a link of an email sent before links carried their purpose\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. An\n * email's unsubscribe link is a tracked link too, and which link it is was fixed when the email was\n * sent (its route): following it shows a confirmation page, and only the confirmation — a POST,\n * which no link scanner sends — counts. Changing a template's or the config's unsubscribe URL, or\n * removing the template, changes nothing for emails already sent.\n *\n * Emails sent before that carry `/t/c/` links, which say nothing of their purpose: one is the\n * unsubscribe link when its recorded URL is `legacyUnsubscribeUrl` (the global unsubscribe URL\n * those emails were all sent with), as it was then.\n */\n\nexport interface TrackingOptions {\n /**\n * The unsubscribe URL emails sent with `/t/c/` links carried (the config's `email.unsubscribeUrl`\n * by default): following such a link to it asks for confirmation instead of redirecting.\n */\n legacyUnsubscribeUrl?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `email.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const [, root, kind, id, position] = url.pathname.split('/');\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if ((kind === 'l' || kind === 'u' || kind === 'c') && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n const unsubscribe =\n kind === 'u' || (kind === 'c' && isUnsubscribeLink(target, options.legacyUnsubscribeUrl));\n if (unsubscribe) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;;;AA8CA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,GAAG,MAAM,MAAM,IAAI,YAAY,IADrB,IAAI,QAAQ,GACW,CAAC,CAAC,SAAS,MAAM,GAAG;CAC3D,IAAI,SAAS,OAAO,OAAO,KAAA,KAAa,CAAC,KAAK,KAAK,EAAE,GAAG,OAAO,KAAA;CAC/D,MAAM,MAAM,UAAU,OAAO;CAC7B,MAAM,OAAO,IAAI,WAAW,SAAS,IAAI,WAAW;CACpD,IAAI,SAA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,MAAM,gCAAe,IAAI,IAAI,CAAC,UAAU,GAAG,KAAK,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC,CAAC,EAAA,CAAE;EACxF,MAAM,UAAUC,2BAAAA,cACd;GAAE,GAAG;GAAK,kBAAkB,KAAK,KAAK;GAAa;GAAc,WAAW,KAAK;EAAU,GAC3F,EAAE,SAAS,QAAQ,QAAQ,CAC7B;EACA,OAAO;GACL,YAAY;IAAE;IAAI,GAAG;IAAS,GAAG,QAAQ,GAAG;GAAE;GAC9C,UAAU,QAAQ,WAAW,gBAAgB,QAAQ,WAAW;EAClE;CACF,CAAC,EAAA,EACgB;AACnB;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,KAAK,QAAQ,aAAa,MAAM,KAAK,EAAE,WAAW,CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
|
1
|
+
{"version":3,"file":"tracking.cjs","names":["isUnsubscribeLink","classifyOpen","BURST_WINDOW_MS","classifyClick"],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import { isUnsubscribeLink } from '../email';\nimport type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/l/<message>/<position> a link: records the click, redirects to the recorded URL\n * GET /t/u/<message>/<position> the unsubscribe link: records the click, asks to confirm\n * POST /t/u/<message> the unsubscribe confirmation\n * GET /t/c/<message>/<position> a link of an email sent before links carried their purpose\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. An\n * email's unsubscribe link is a tracked link too, and which link it is was fixed when the email was\n * sent (its route): following it shows a confirmation page, and only the confirmation — a POST,\n * which no link scanner sends — counts. Changing a template's or the config's unsubscribe URL, or\n * removing the template, changes nothing for emails already sent.\n *\n * Emails sent before that carry `/t/c/` links, which say nothing of their purpose: one is the\n * unsubscribe link when its recorded URL is `legacyUnsubscribeUrl` (the global unsubscribe URL\n * those emails were all sent with), as it was then.\n */\n\nexport interface TrackingOptions {\n /**\n * The unsubscribe URL emails sent with `/t/c/` links carried (the config's `email.unsubscribeUrl`\n * by default): following such a link to it asks for confirmation instead of redirecting.\n */\n legacyUnsubscribeUrl?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `email.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const path = url.pathname.split('/');\n const root = path.at(1);\n const kind = path.at(2);\n const id = path.at(3);\n const position = path.at(4);\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if ((kind === 'l' || kind === 'u' || kind === 'c') && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n const unsubscribe =\n kind === 'u' || (kind === 'c' && isUnsubscribeLink(target, options.legacyUnsubscribeUrl));\n if (unsubscribe) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;;;AA8CA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,OAAO,IADG,IAAI,QAAQ,GACb,CAAC,CAAC,SAAS,MAAM,GAAG;CACnC,MAAM,OAAO,KAAK,GAAG,CAAC;CACtB,MAAM,OAAO,KAAK,GAAG,CAAC;CACtB,MAAM,KAAK,KAAK,GAAG,CAAC;CACpB,MAAM,WAAW,KAAK,GAAG,CAAC;CAC1B,IAAI,SAAS,OAAO,OAAO,KAAA,KAAa,CAAC,KAAK,KAAK,EAAE,GAAG,OAAO,KAAA;CAC/D,MAAM,MAAM,UAAU,OAAO;CAC7B,MAAM,OAAO,IAAI,WAAW,SAAS,IAA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AAA,kBAAkB,SAAS;EACxF,MAAM,gCAAe,IAAI,IAAI,CAAC,UAAU,GAAG,KAAK,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC,CAAC,EAAA,CAAE;EACxF,MAAM,UAAUC,2BAAAA,cACd;GAAE,GAAG;GAAK,kBAAkB,KAAK,KAAK;GAAa;GAAc,WAAW,KAAK;EAAU,GAC3F,EAAE,SAAS,QAAQ,QAAQ,CAC7B;EACA,OAAO;GACL,YAAY;IAAE;IAAI,GAAG;IAAS,GAAG,QAAQ,GAAG;GAAE;GAC9C,UAAU,QAAQ,WAAW,gBAAgB,QAAQ,WAAW;EAClE;CACF,CAAC,EAAA,EACgB;AACnB;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,KAAK,QAAQ,aAAa,MAAM,KAAK,EAAE,WAAW,CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracking.d.cts","names":[],"sources":["../../src/reporting/tracking.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BiB;;;;;EAKf;;EAEA;;EAEA;;EAEA,eACM;IAAQ;IAAmB;IAAgB;QAAiB;;;wBAgC9C,eACpB,SAAS,SACT,WAAW,kBACX,UAAS,kBACR,QAAQ;;;;;;
|
|
1
|
+
{"version":3,"file":"tracking.d.cts","names":[],"sources":["../../src/reporting/tracking.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BiB;;;;;EAKf;;EAEA;;EAEA;;EAEA,eACM;IAAQ;IAAmB;IAAgB;QAAiB;;;wBAgC9C,eACpB,SAAS,SACT,WAAW,kBACX,UAAS,kBACR,QAAQ;;;;;;wBAuEW,eACpB,WAAW,kBACX,gBACA,mBACA,cACC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracking.d.mts","names":[],"sources":["../../src/reporting/tracking.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BiB;;;;;EAKf;;EAEA;;EAEA;;EAEA,eACM;IAAQ;IAAmB;IAAgB;QAAiB;;;wBAgC9C,eACpB,SAAS,SACT,WAAW,kBACX,UAAS,kBACR,QAAQ;;;;;;
|
|
1
|
+
{"version":3,"file":"tracking.d.mts","names":[],"sources":["../../src/reporting/tracking.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BiB;;;;;EAKf;;EAEA;;EAEA;;EAEA,eACM;IAAQ;IAAmB;IAAgB;QAAiB;;;wBAgC9C,eACpB,SAAS,SACT,WAAW,kBACX,UAAS,kBACR,QAAQ;;;;;;wBAuEW,eACpB,WAAW,kBACX,gBACA,mBACA,cACC"}
|
|
@@ -15,7 +15,11 @@ function requester(request) {
|
|
|
15
15
|
}
|
|
16
16
|
/** A `/t/...` request's response, or undefined when the path is not a tracking route. */
|
|
17
17
|
async function handleTracking(request, reporting, options = {}) {
|
|
18
|
-
const
|
|
18
|
+
const path = new URL(request.url).pathname.split("/");
|
|
19
|
+
const root = path.at(1);
|
|
20
|
+
const kind = path.at(2);
|
|
21
|
+
const id = path.at(3);
|
|
22
|
+
const position = path.at(4);
|
|
19
23
|
if (root !== "t" || id === void 0 || !UUID.test(id)) return void 0;
|
|
20
24
|
const who = requester(request);
|
|
21
25
|
const read = who.method === "GET" || who.method === "HEAD";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracking.mjs","names":[],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import { isUnsubscribeLink } from '../email';\nimport type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/l/<message>/<position> a link: records the click, redirects to the recorded URL\n * GET /t/u/<message>/<position> the unsubscribe link: records the click, asks to confirm\n * POST /t/u/<message> the unsubscribe confirmation\n * GET /t/c/<message>/<position> a link of an email sent before links carried their purpose\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. An\n * email's unsubscribe link is a tracked link too, and which link it is was fixed when the email was\n * sent (its route): following it shows a confirmation page, and only the confirmation — a POST,\n * which no link scanner sends — counts. Changing a template's or the config's unsubscribe URL, or\n * removing the template, changes nothing for emails already sent.\n *\n * Emails sent before that carry `/t/c/` links, which say nothing of their purpose: one is the\n * unsubscribe link when its recorded URL is `legacyUnsubscribeUrl` (the global unsubscribe URL\n * those emails were all sent with), as it was then.\n */\n\nexport interface TrackingOptions {\n /**\n * The unsubscribe URL emails sent with `/t/c/` links carried (the config's `email.unsubscribeUrl`\n * by default): following such a link to it asks for confirmation instead of redirecting.\n */\n legacyUnsubscribeUrl?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `email.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const [, root, kind, id, position] = url.pathname.split('/');\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if ((kind === 'l' || kind === 'u' || kind === 'c') && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n const unsubscribe =\n kind === 'u' || (kind === 'c' && isUnsubscribeLink(target, options.legacyUnsubscribeUrl));\n if (unsubscribe) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;;AA8CA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,GAAG,MAAM,MAAM,IAAI,YAAY,IADrB,IAAI,QAAQ,GACW,CAAC,CAAC,SAAS,MAAM,GAAG;CAC3D,IAAI,SAAS,OAAO,OAAO,KAA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,GAAG,OAAO,KAAA;CACxD,MAAM,KAAK,KAAK,IAAI;CAYpB,QAAO,MAXgB,UAAU,YAAY,IAAI,UAAU,IAAI,kBAAkB,SAAS;EACxF,MAAM,gCAAe,IAAI,IAAI,CAAC,UAAU,GAAG,KAAK,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC,CAAC,EAAA,CAAE;EACxF,MAAM,UAAU,cACd;GAAE,GAAG;GAAK,kBAAkB,KAAK,KAAK;GAAa;GAAc,WAAW,KAAK;EAAU,GAC3F,EAAE,SAAS,QAAQ,QAAQ,CAC7B;EACA,OAAO;GACL,YAAY;IAAE;IAAI,GAAG;IAAS,GAAG,QAAQ,GAAG;GAAE;GAC9C,UAAU,QAAQ,WAAW,gBAAgB,QAAQ,WAAW;EAClE;CACF,CAAC,EAAA,EACgB;AACnB;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,KAAK,QAAQ,aAAa,MAAM,KAAK,EAAE,WAAW,CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
|
1
|
+
{"version":3,"file":"tracking.mjs","names":[],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import { isUnsubscribeLink } from '../email';\nimport type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/l/<message>/<position> a link: records the click, redirects to the recorded URL\n * GET /t/u/<message>/<position> the unsubscribe link: records the click, asks to confirm\n * POST /t/u/<message> the unsubscribe confirmation\n * GET /t/c/<message>/<position> a link of an email sent before links carried their purpose\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. An\n * email's unsubscribe link is a tracked link too, and which link it is was fixed when the email was\n * sent (its route): following it shows a confirmation page, and only the confirmation — a POST,\n * which no link scanner sends — counts. Changing a template's or the config's unsubscribe URL, or\n * removing the template, changes nothing for emails already sent.\n *\n * Emails sent before that carry `/t/c/` links, which say nothing of their purpose: one is the\n * unsubscribe link when its recorded URL is `legacyUnsubscribeUrl` (the global unsubscribe URL\n * those emails were all sent with), as it was then.\n */\n\nexport interface TrackingOptions {\n /**\n * The unsubscribe URL emails sent with `/t/c/` links carried (the config's `email.unsubscribeUrl`\n * by default): following such a link to it asks for confirmation instead of redirecting.\n */\n legacyUnsubscribeUrl?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `email.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const path = url.pathname.split('/');\n const root = path.at(1);\n const kind = path.at(2);\n const id = path.at(3);\n const position = path.at(4);\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if ((kind === 'l' || kind === 'u' || kind === 'c') && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n const unsubscribe =\n kind === 'u' || (kind === 'c' && isUnsubscribeLink(target, options.legacyUnsubscribeUrl));\n if (unsubscribe) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;;AA8CA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,OAAO,IADG,IAAI,QAAQ,GACb,CAAC,CAAC,SAAS,MAAM,GAAG;CACnC,MAAM,OAAO,KAAK,GAAG,CAAC;CACtB,MAAM,OAAO,KAAK,GAAG,CAAC;CACtB,MAAM,KAAK,KAAK,GAAG,CAAC;CACpB,MAAM,WAAW,KAAK,GAAG,CAAC;CAC1B,IAAI,SAAS,OAAO,OAAO,KAAA,KAAa,CAAC,KAAK,KAAK,EAAE,GAAG,OAAO,KAAA;CAC/D,M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AO,MAXgB,UAAU,YAAY,IAAI,UAAU,IAAI,kBAAkB,SAAS;EACxF,MAAM,gCAAe,IAAI,IAAI,CAAC,UAAU,GAAG,KAAK,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC,CAAC,EAAA,CAAE;EACxF,MAAM,UAAU,cACd;GAAE,GAAG;GAAK,kBAAkB,KAAK,KAAK;GAAa;GAAc,WAAW,KAAK;EAAU,GAC3F,EAAE,SAAS,QAAQ,QAAQ,CAC7B;EACA,OAAO;GACL,YAAY;IAAE;IAAI,GAAG;IAAS,GAAG,QAAQ,GAAG;GAAE;GAC9C,UAAU,QAAQ,WAAW,gBAAgB,QAAQ,WAAW;EAClE;CACF,CAAC,EAAA,EACgB;AACnB;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,KAAK,QAAQ,aAAa,MAAM,KAAK,EAAE,WAAW,CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
|
@@ -70,7 +70,7 @@ var PostgresReporting = class {
|
|
|
70
70
|
message.channel,
|
|
71
71
|
message.userId,
|
|
72
72
|
message.sentAt
|
|
73
|
-
]))
|
|
73
|
+
])).at(0)?.id;
|
|
74
74
|
if (id === void 0) throw new Error(`message ${message.idempotencyKey} was not recorded`);
|
|
75
75
|
return id;
|
|
76
76
|
}
|
|
@@ -86,7 +86,7 @@ var PostgresReporting = class {
|
|
|
86
86
|
async recordOpen(messageId, judge) {
|
|
87
87
|
return this.sql.transaction(async (tx) => {
|
|
88
88
|
const row = (await tx.query(`SELECT user_id, ${MS("coalesce(delivered_at, sent_at)")} AS delivered_at
|
|
89
|
-
FROM ${this.t.message} WHERE id = $1`, [messageId]))
|
|
89
|
+
FROM ${this.t.message} WHERE id = $1`, [messageId])).at(0);
|
|
90
90
|
if (row === void 0) return false;
|
|
91
91
|
const open = judge({
|
|
92
92
|
userId: row.user_id,
|
|
@@ -120,11 +120,11 @@ var PostgresReporting = class {
|
|
|
120
120
|
async recordClick(messageId, position, at, windowMs, judge) {
|
|
121
121
|
return this.sql.transaction(async (tx) => {
|
|
122
122
|
const message = (await tx.query(`SELECT ${MS("coalesce(delivered_at, sent_at)")} AS delivered_at
|
|
123
|
-
FROM ${this.t.message} WHERE id = $1 FOR UPDATE`, [messageId]))
|
|
123
|
+
FROM ${this.t.message} WHERE id = $1 FOR UPDATE`, [messageId])).at(0);
|
|
124
124
|
if (message === void 0) return void 0;
|
|
125
125
|
const link = (await tx.query(`SELECT l.url,
|
|
126
126
|
(SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count
|
|
127
|
-
FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`, [messageId, position]))
|
|
127
|
+
FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`, [messageId, position])).at(0);
|
|
128
128
|
if (link === void 0) return void 0;
|
|
129
129
|
const since = at - windowMs;
|
|
130
130
|
const recent = await tx.query(`SELECT position, ${MS("clicked_at")} AS at FROM ${this.t.messageClick}
|
|
@@ -185,7 +185,7 @@ var PostgresReporting = class {
|
|
|
185
185
|
async recordUnsubscribe(messageId, at) {
|
|
186
186
|
return this.sql.transaction(async (tx) => {
|
|
187
187
|
const userId = (await tx.query(`UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS("$2")})
|
|
188
|
-
WHERE id = $1 AND channel = 'email' RETURNING user_id`, [messageId, at]))
|
|
188
|
+
WHERE id = $1 AND channel = 'email' RETURNING user_id`, [messageId, at])).at(0)?.user_id;
|
|
189
189
|
if (userId === void 0) return false;
|
|
190
190
|
await tx.query(`INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS("$2")})
|
|
191
191
|
ON CONFLICT DO NOTHING`, [userId, at]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-reporting.cjs","names":["uuidv7"],"sources":["../../src/store/postgres-reporting.ts"],"sourcesContent":["import type { ClickContext, Engagement, JourneyReporting, MessageRecord } from './index';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport type { TableKey } from './tables';\n\n/**\n * Epoch milliseconds → timestamptz, and back: numbers in and out, whatever the driver maps (a\n * driver may hand a double or a bigint count back as a string).\n */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\nconst MS = (column: string) => `(extract(epoch from ${column}) * 1000)::double precision`;\n\n/**\n * Journey reporting on the engine's Postgres schema (tables.ts: instance, message,\n * message_link, message_open, message_click, segment_member, segment_snapshot). Every timestamp\n * is written here, never defaulted, and every write is idempotent: the engine reports again when\n * a step is retried.\n */\nexport class PostgresReporting implements JourneyReporting {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly t: Record<TableKey, string>\n ) {}\n\n async instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO NOTHING`,\n [input.instanceId, input.workflow, input.userId, input.at]\n );\n }\n\n async nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, node_id, node_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, $5, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO UPDATE SET node_id = EXCLUDED.node_id, node_at = EXCLUDED.node_at`,\n [input.instanceId, input.workflow, input.userId, input.at, input.nodeId]\n );\n }\n\n async instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void> {\n // An upsert: an instance that started before its start was reported still gets its row\n await this.sql.query(\n `INSERT INTO ${this.t.instance}\n (instance_id, workflow, user_id, entered_at, status, finished_at, converted_at)\n VALUES ($1, $2, $3, ${TS('$5')}, $4, ${TS('$5')}, ${TS('$6')})\n ON CONFLICT (instance_id) DO UPDATE SET status = EXCLUDED.status,\n finished_at = EXCLUDED.finished_at, converted_at = EXCLUDED.converted_at`,\n [\n input.instanceId,\n input.workflow,\n input.userId,\n input.status,\n input.at,\n input.convertedAt ?? null,\n ]\n );\n }\n\n async recordMessage(message: MessageRecord): Promise<string> {\n // A retried step records the same copy again: the row it already wrote is the one\n const rows = await this.sql.query<{ id: string }>(\n `INSERT INTO ${this.t.message}\n (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, sent_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${TS('$9')})\n ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key\n RETURNING id`,\n [\n uuidv7(message.sentAt),\n message.idempotencyKey,\n message.workflow,\n message.instanceId,\n message.nodeId,\n message.template,\n message.channel,\n message.userId,\n message.sentAt,\n ]\n );\n const id = rows[0]?.id;\n if (id === undefined) throw new Error(`message ${message.idempotencyKey} was not recorded`);\n return id;\n }\n\n async settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void> {\n if (result.delivered) {\n await this.sql.query(\n `UPDATE ${this.t.message} SET delivered_at = coalesce(delivered_at, ${TS('$2')}) WHERE idempotency_key = $1`,\n [idempotencyKey, at]\n );\n } else {\n await this.sql.query(\n `UPDATE ${this.t.message} SET undelivered_reason = $2 WHERE idempotency_key = $1`,\n [idempotencyKey, result.reason]\n );\n }\n }\n\n async recordLinks(messageId: string, urls: readonly string[]): Promise<void> {\n if (urls.length === 0) return;\n const values = urls.map((_, i) => `($1, ${i}, $${i + 2})`).join(', ');\n await this.sql.query(\n `INSERT INTO ${this.t.messageLink} (message_id, position, url) VALUES ${values} ON CONFLICT DO NOTHING`,\n [messageId, ...urls]\n );\n }\n\n async recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean> {\n // In a transaction: read through Hyperdrive, a bare read may come from its cache, from before\n // the copy existed\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string; delivered_at: number | string }>(\n `SELECT user_id, ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1`,\n [messageId]\n );\n const row = rows[0];\n if (row === undefined) return false;\n const open = judge({ userId: row.user_id, deliveredAt: Number(row.delivered_at) });\n if (open === undefined) return true;\n await tx.query(\n `INSERT INTO ${this.t.messageOpen}\n (id, message_id, opened_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, ${TS('$3')}, $4, $5, $6, $7, $8, $9)`,\n [\n uuidv7(open.at),\n messageId,\n open.at,\n open.machine,\n open.reason,\n open.userAgent,\n open.asn,\n open.organization,\n open.country,\n ]\n );\n await tx.query(\n `UPDATE ${this.t.message} SET\n opened_at = coalesce(opened_at, ${TS('$2')}),\n human_opened_at = CASE WHEN $3 THEN human_opened_at ELSE coalesce(human_opened_at, ${TS('$2')}) END\n WHERE id = $1`,\n [messageId, open.at, open.machine]\n );\n return true;\n });\n }\n\n async 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 return this.sql.transaction(async (tx) => {\n // The copy's row is the lock: concurrent clicks on it are judged one at a time\n const messages = await tx.query<{ delivered_at: number | string }>(\n `SELECT ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1 FOR UPDATE`,\n [messageId]\n );\n const message = messages[0];\n if (message === undefined) return undefined;\n const links = await tx.query<{ url: string; link_count: number | string }>(\n `SELECT l.url,\n (SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count\n FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`,\n [messageId, position]\n );\n const link = links[0];\n if (link === undefined) return undefined;\n const since = at - windowMs;\n const recent = await tx.query<{ position: number; at: number | string }>(\n `SELECT position, ${MS('clicked_at')} AS at FROM ${this.t.messageClick}\n WHERE message_id = $1 AND clicked_at >= ${TS('$2')} ORDER BY clicked_at`,\n [messageId, since]\n );\n const { engagement: click, backdate } = judge({\n url: link.url,\n deliveredAt: Number(message.delivered_at),\n linkCount: Number(link.link_count),\n recent: recent.map((row) => ({ position: row.position, at: Number(row.at) })),\n });\n await tx.query(\n `INSERT INTO ${this.t.messageClick}\n (id, message_id, position, url, clicked_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6, $7, $8, $9, $10, $11)`,\n [\n uuidv7(click.at),\n messageId,\n position,\n link.url,\n click.at,\n click.machine,\n click.reason,\n click.userAgent,\n click.asn,\n click.organization,\n click.country,\n ]\n );\n if (backdate) {\n // A walk across the copy is found on its later clicks: the earlier ones were part of it\n await tx.query(\n `UPDATE ${this.t.messageClick} SET machine = true, reason = $4\n WHERE message_id = $1 AND NOT machine\n AND clicked_at BETWEEN ${TS('$2')} AND ${TS('$3')}`,\n [messageId, since, at, click.reason]\n );\n }\n // First opens and clicks, from the classified rows (a click implies an open)\n await tx.query(\n `UPDATE ${this.t.message} m SET\n clicked_at = coalesce(m.clicked_at, ${TS('$2')}),\n opened_at = coalesce(m.opened_at, ${TS('$2')}),\n human_clicked_at = (SELECT min(c.clicked_at) FROM ${this.t.messageClick} c\n WHERE c.message_id = m.id AND NOT c.machine),\n human_opened_at = (SELECT min(t) FROM (\n SELECT o.opened_at AS t FROM ${this.t.messageOpen} o WHERE o.message_id = m.id AND NOT o.machine\n UNION ALL\n SELECT c.clicked_at FROM ${this.t.messageClick} c WHERE c.message_id = m.id AND NOT c.machine\n ) human)\n WHERE m.id = $1`,\n [messageId, at]\n );\n return { url: link.url, engagement: click };\n });\n }\n\n async recordDeviceDelivered(messageId: string, at: number): Promise<boolean> {\n const rows = await this.sql.query<{ id: string }>(\n `UPDATE ${this.t.message} SET device_delivered_at = coalesce(device_delivered_at, ${TS('$2')})\n WHERE id = $1 RETURNING id`,\n [messageId, at]\n );\n return rows.length > 0;\n }\n\n async recordUnsubscribe(messageId: string, at: number): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string }>(\n `UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS('$2')})\n WHERE id = $1 AND channel = 'email' RETURNING user_id`,\n [messageId, at]\n );\n const userId = rows[0]?.user_id;\n if (userId === undefined) return false;\n // The opt-out itself: the engine sends this user no more email\n await tx.query(\n `INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n return true;\n });\n }\n\n async snapshotSegments(at: number): Promise<{ segment: string; size: number }[]> {\n return this.sql.transaction(async (tx) => {\n // Segments no longer deployed take their members with them\n await tx.query(\n `DELETE FROM ${this.t.segmentMember} m\n WHERE NOT EXISTS (SELECT 1 FROM ${this.t.segment} s WHERE s.id = m.segment)`\n );\n const rows = await tx.query<{ segment: string; size: number | string }>(\n `INSERT INTO ${this.t.segmentSnapshot} (segment, taken_at, size)\n SELECT s.id, ${TS('$1')}, (SELECT count(*) FROM ${this.t.segmentMember} m WHERE m.segment = s.id)\n FROM ${this.t.segment} s\n ON CONFLICT DO NOTHING\n RETURNING segment, size`,\n [at]\n );\n return rows\n .map((row) => ({ segment: row.segment, size: Number(row.size) }))\n .sort((a, b) => a.segment.localeCompare(b.segment));\n });\n }\n}\n"],"mappings":";;;;;;;AAQA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AACpD,MAAM,MAAM,WAAmB,uBAAuB,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E,OAAO,CAAC;EACtD,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"postgres-reporting.cjs","names":["uuidv7"],"sources":["../../src/store/postgres-reporting.ts"],"sourcesContent":["import type { ClickContext, Engagement, JourneyReporting, MessageRecord } from './index';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport type { TableKey } from './tables';\n\n/**\n * Epoch milliseconds → timestamptz, and back: numbers in and out, whatever the driver maps (a\n * driver may hand a double or a bigint count back as a string).\n */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\nconst MS = (column: string) => `(extract(epoch from ${column}) * 1000)::double precision`;\n\n/**\n * Journey reporting on the engine's Postgres schema (tables.ts: instance, message,\n * message_link, message_open, message_click, segment_member, segment_snapshot). Every timestamp\n * is written here, never defaulted, and every write is idempotent: the engine reports again when\n * a step is retried.\n */\nexport class PostgresReporting implements JourneyReporting {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly t: Record<TableKey, string>\n ) {}\n\n async instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO NOTHING`,\n [input.instanceId, input.workflow, input.userId, input.at]\n );\n }\n\n async nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, node_id, node_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, $5, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO UPDATE SET node_id = EXCLUDED.node_id, node_at = EXCLUDED.node_at`,\n [input.instanceId, input.workflow, input.userId, input.at, input.nodeId]\n );\n }\n\n async instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void> {\n // An upsert: an instance that started before its start was reported still gets its row\n await this.sql.query(\n `INSERT INTO ${this.t.instance}\n (instance_id, workflow, user_id, entered_at, status, finished_at, converted_at)\n VALUES ($1, $2, $3, ${TS('$5')}, $4, ${TS('$5')}, ${TS('$6')})\n ON CONFLICT (instance_id) DO UPDATE SET status = EXCLUDED.status,\n finished_at = EXCLUDED.finished_at, converted_at = EXCLUDED.converted_at`,\n [\n input.instanceId,\n input.workflow,\n input.userId,\n input.status,\n input.at,\n input.convertedAt ?? null,\n ]\n );\n }\n\n async recordMessage(message: MessageRecord): Promise<string> {\n // A retried step records the same copy again: the row it already wrote is the one\n const rows = await this.sql.query<{ id: string }>(\n `INSERT INTO ${this.t.message}\n (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, sent_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${TS('$9')})\n ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key\n RETURNING id`,\n [\n uuidv7(message.sentAt),\n message.idempotencyKey,\n message.workflow,\n message.instanceId,\n message.nodeId,\n message.template,\n message.channel,\n message.userId,\n message.sentAt,\n ]\n );\n const id = rows.at(0)?.id;\n if (id === undefined) throw new Error(`message ${message.idempotencyKey} was not recorded`);\n return id;\n }\n\n async settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void> {\n if (result.delivered) {\n await this.sql.query(\n `UPDATE ${this.t.message} SET delivered_at = coalesce(delivered_at, ${TS('$2')}) WHERE idempotency_key = $1`,\n [idempotencyKey, at]\n );\n } else {\n await this.sql.query(\n `UPDATE ${this.t.message} SET undelivered_reason = $2 WHERE idempotency_key = $1`,\n [idempotencyKey, result.reason]\n );\n }\n }\n\n async recordLinks(messageId: string, urls: readonly string[]): Promise<void> {\n if (urls.length === 0) return;\n const values = urls.map((_, i) => `($1, ${i}, $${i + 2})`).join(', ');\n await this.sql.query(\n `INSERT INTO ${this.t.messageLink} (message_id, position, url) VALUES ${values} ON CONFLICT DO NOTHING`,\n [messageId, ...urls]\n );\n }\n\n async recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean> {\n // In a transaction: read through Hyperdrive, a bare read may come from its cache, from before\n // the copy existed\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string; delivered_at: number | string }>(\n `SELECT user_id, ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1`,\n [messageId]\n );\n const row = rows.at(0);\n if (row === undefined) return false;\n const open = judge({ userId: row.user_id, deliveredAt: Number(row.delivered_at) });\n if (open === undefined) return true;\n await tx.query(\n `INSERT INTO ${this.t.messageOpen}\n (id, message_id, opened_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, ${TS('$3')}, $4, $5, $6, $7, $8, $9)`,\n [\n uuidv7(open.at),\n messageId,\n open.at,\n open.machine,\n open.reason,\n open.userAgent,\n open.asn,\n open.organization,\n open.country,\n ]\n );\n await tx.query(\n `UPDATE ${this.t.message} SET\n opened_at = coalesce(opened_at, ${TS('$2')}),\n human_opened_at = CASE WHEN $3 THEN human_opened_at ELSE coalesce(human_opened_at, ${TS('$2')}) END\n WHERE id = $1`,\n [messageId, open.at, open.machine]\n );\n return true;\n });\n }\n\n async 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 return this.sql.transaction(async (tx) => {\n // The copy's row is the lock: concurrent clicks on it are judged one at a time\n const messages = await tx.query<{ delivered_at: number | string }>(\n `SELECT ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1 FOR UPDATE`,\n [messageId]\n );\n const message = messages.at(0);\n if (message === undefined) return undefined;\n const links = await tx.query<{ url: string; link_count: number | string }>(\n `SELECT l.url,\n (SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count\n FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`,\n [messageId, position]\n );\n const link = links.at(0);\n if (link === undefined) return undefined;\n const since = at - windowMs;\n const recent = await tx.query<{ position: number; at: number | string }>(\n `SELECT position, ${MS('clicked_at')} AS at FROM ${this.t.messageClick}\n WHERE message_id = $1 AND clicked_at >= ${TS('$2')} ORDER BY clicked_at`,\n [messageId, since]\n );\n const { engagement: click, backdate } = judge({\n url: link.url,\n deliveredAt: Number(message.delivered_at),\n linkCount: Number(link.link_count),\n recent: recent.map((row) => ({ position: row.position, at: Number(row.at) })),\n });\n await tx.query(\n `INSERT INTO ${this.t.messageClick}\n (id, message_id, position, url, clicked_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6, $7, $8, $9, $10, $11)`,\n [\n uuidv7(click.at),\n messageId,\n position,\n link.url,\n click.at,\n click.machine,\n click.reason,\n click.userAgent,\n click.asn,\n click.organization,\n click.country,\n ]\n );\n if (backdate) {\n // A walk across the copy is found on its later clicks: the earlier ones were part of it\n await tx.query(\n `UPDATE ${this.t.messageClick} SET machine = true, reason = $4\n WHERE message_id = $1 AND NOT machine\n AND clicked_at BETWEEN ${TS('$2')} AND ${TS('$3')}`,\n [messageId, since, at, click.reason]\n );\n }\n // First opens and clicks, from the classified rows (a click implies an open)\n await tx.query(\n `UPDATE ${this.t.message} m SET\n clicked_at = coalesce(m.clicked_at, ${TS('$2')}),\n opened_at = coalesce(m.opened_at, ${TS('$2')}),\n human_clicked_at = (SELECT min(c.clicked_at) FROM ${this.t.messageClick} c\n WHERE c.message_id = m.id AND NOT c.machine),\n human_opened_at = (SELECT min(t) FROM (\n SELECT o.opened_at AS t FROM ${this.t.messageOpen} o WHERE o.message_id = m.id AND NOT o.machine\n UNION ALL\n SELECT c.clicked_at FROM ${this.t.messageClick} c WHERE c.message_id = m.id AND NOT c.machine\n ) human)\n WHERE m.id = $1`,\n [messageId, at]\n );\n return { url: link.url, engagement: click };\n });\n }\n\n async recordDeviceDelivered(messageId: string, at: number): Promise<boolean> {\n const rows = await this.sql.query<{ id: string }>(\n `UPDATE ${this.t.message} SET device_delivered_at = coalesce(device_delivered_at, ${TS('$2')})\n WHERE id = $1 RETURNING id`,\n [messageId, at]\n );\n return rows.length > 0;\n }\n\n async recordUnsubscribe(messageId: string, at: number): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string }>(\n `UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS('$2')})\n WHERE id = $1 AND channel = 'email' RETURNING user_id`,\n [messageId, at]\n );\n const userId = rows.at(0)?.user_id;\n if (userId === undefined) return false;\n // The opt-out itself: the engine sends this user no more email\n await tx.query(\n `INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n return true;\n });\n }\n\n async snapshotSegments(at: number): Promise<{ segment: string; size: number }[]> {\n return this.sql.transaction(async (tx) => {\n // Segments no longer deployed take their members with them\n await tx.query(\n `DELETE FROM ${this.t.segmentMember} m\n WHERE NOT EXISTS (SELECT 1 FROM ${this.t.segment} s WHERE s.id = m.segment)`\n );\n const rows = await tx.query<{ segment: string; size: number | string }>(\n `INSERT INTO ${this.t.segmentSnapshot} (segment, taken_at, size)\n SELECT s.id, ${TS('$1')}, (SELECT count(*) FROM ${this.t.segmentMember} m WHERE m.segment = s.id)\n FROM ${this.t.segment} s\n ON CONFLICT DO NOTHING\n RETURNING segment, size`,\n [at]\n );\n return rows\n .map((row) => ({ segment: row.segment, size: Number(row.size) }))\n .sort((a, b) => a.segment.localeCompare(b.segment));\n });\n }\n}\n"],"mappings":";;;;;;;AAQA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AACpD,MAAM,MAAM,WAAmB,uBAAuB,OAAO;;;;;;;AAQ7D,IAAa,oBAAb,MAA2D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AAE,QAAQ,cAAc,EAAE,OAAO,CAAC;EACtD,CAAC;CACH;AACF"}
|
|
@@ -69,7 +69,7 @@ var PostgresReporting = class {
|
|
|
69
69
|
message.channel,
|
|
70
70
|
message.userId,
|
|
71
71
|
message.sentAt
|
|
72
|
-
]))
|
|
72
|
+
])).at(0)?.id;
|
|
73
73
|
if (id === void 0) throw new Error(`message ${message.idempotencyKey} was not recorded`);
|
|
74
74
|
return id;
|
|
75
75
|
}
|
|
@@ -85,7 +85,7 @@ var PostgresReporting = class {
|
|
|
85
85
|
async recordOpen(messageId, judge) {
|
|
86
86
|
return this.sql.transaction(async (tx) => {
|
|
87
87
|
const row = (await tx.query(`SELECT user_id, ${MS("coalesce(delivered_at, sent_at)")} AS delivered_at
|
|
88
|
-
FROM ${this.t.message} WHERE id = $1`, [messageId]))
|
|
88
|
+
FROM ${this.t.message} WHERE id = $1`, [messageId])).at(0);
|
|
89
89
|
if (row === void 0) return false;
|
|
90
90
|
const open = judge({
|
|
91
91
|
userId: row.user_id,
|
|
@@ -119,11 +119,11 @@ var PostgresReporting = class {
|
|
|
119
119
|
async recordClick(messageId, position, at, windowMs, judge) {
|
|
120
120
|
return this.sql.transaction(async (tx) => {
|
|
121
121
|
const message = (await tx.query(`SELECT ${MS("coalesce(delivered_at, sent_at)")} AS delivered_at
|
|
122
|
-
FROM ${this.t.message} WHERE id = $1 FOR UPDATE`, [messageId]))
|
|
122
|
+
FROM ${this.t.message} WHERE id = $1 FOR UPDATE`, [messageId])).at(0);
|
|
123
123
|
if (message === void 0) return void 0;
|
|
124
124
|
const link = (await tx.query(`SELECT l.url,
|
|
125
125
|
(SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count
|
|
126
|
-
FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`, [messageId, position]))
|
|
126
|
+
FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`, [messageId, position])).at(0);
|
|
127
127
|
if (link === void 0) return void 0;
|
|
128
128
|
const since = at - windowMs;
|
|
129
129
|
const recent = await tx.query(`SELECT position, ${MS("clicked_at")} AS at FROM ${this.t.messageClick}
|
|
@@ -184,7 +184,7 @@ var PostgresReporting = class {
|
|
|
184
184
|
async recordUnsubscribe(messageId, at) {
|
|
185
185
|
return this.sql.transaction(async (tx) => {
|
|
186
186
|
const userId = (await tx.query(`UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS("$2")})
|
|
187
|
-
WHERE id = $1 AND channel = 'email' RETURNING user_id`, [messageId, at]))
|
|
187
|
+
WHERE id = $1 AND channel = 'email' RETURNING user_id`, [messageId, at])).at(0)?.user_id;
|
|
188
188
|
if (userId === void 0) return false;
|
|
189
189
|
await tx.query(`INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS("$2")})
|
|
190
190
|
ON CONFLICT DO NOTHING`, [userId, at]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-reporting.mjs","names":[],"sources":["../../src/store/postgres-reporting.ts"],"sourcesContent":["import type { ClickContext, Engagement, JourneyReporting, MessageRecord } from './index';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport type { TableKey } from './tables';\n\n/**\n * Epoch milliseconds → timestamptz, and back: numbers in and out, whatever the driver maps (a\n * driver may hand a double or a bigint count back as a string).\n */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\nconst MS = (column: string) => `(extract(epoch from ${column}) * 1000)::double precision`;\n\n/**\n * Journey reporting on the engine's Postgres schema (tables.ts: instance, message,\n * message_link, message_open, message_click, segment_member, segment_snapshot). Every timestamp\n * is written here, never defaulted, and every write is idempotent: the engine reports again when\n * a step is retried.\n */\nexport class PostgresReporting implements JourneyReporting {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly t: Record<TableKey, string>\n ) {}\n\n async instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO NOTHING`,\n [input.instanceId, input.workflow, input.userId, input.at]\n );\n }\n\n async nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, node_id, node_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, $5, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO UPDATE SET node_id = EXCLUDED.node_id, node_at = EXCLUDED.node_at`,\n [input.instanceId, input.workflow, input.userId, input.at, input.nodeId]\n );\n }\n\n async instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void> {\n // An upsert: an instance that started before its start was reported still gets its row\n await this.sql.query(\n `INSERT INTO ${this.t.instance}\n (instance_id, workflow, user_id, entered_at, status, finished_at, converted_at)\n VALUES ($1, $2, $3, ${TS('$5')}, $4, ${TS('$5')}, ${TS('$6')})\n ON CONFLICT (instance_id) DO UPDATE SET status = EXCLUDED.status,\n finished_at = EXCLUDED.finished_at, converted_at = EXCLUDED.converted_at`,\n [\n input.instanceId,\n input.workflow,\n input.userId,\n input.status,\n input.at,\n input.convertedAt ?? null,\n ]\n );\n }\n\n async recordMessage(message: MessageRecord): Promise<string> {\n // A retried step records the same copy again: the row it already wrote is the one\n const rows = await this.sql.query<{ id: string }>(\n `INSERT INTO ${this.t.message}\n (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, sent_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${TS('$9')})\n ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key\n RETURNING id`,\n [\n uuidv7(message.sentAt),\n message.idempotencyKey,\n message.workflow,\n message.instanceId,\n message.nodeId,\n message.template,\n message.channel,\n message.userId,\n message.sentAt,\n ]\n );\n const id = rows[0]?.id;\n if (id === undefined) throw new Error(`message ${message.idempotencyKey} was not recorded`);\n return id;\n }\n\n async settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void> {\n if (result.delivered) {\n await this.sql.query(\n `UPDATE ${this.t.message} SET delivered_at = coalesce(delivered_at, ${TS('$2')}) WHERE idempotency_key = $1`,\n [idempotencyKey, at]\n );\n } else {\n await this.sql.query(\n `UPDATE ${this.t.message} SET undelivered_reason = $2 WHERE idempotency_key = $1`,\n [idempotencyKey, result.reason]\n );\n }\n }\n\n async recordLinks(messageId: string, urls: readonly string[]): Promise<void> {\n if (urls.length === 0) return;\n const values = urls.map((_, i) => `($1, ${i}, $${i + 2})`).join(', ');\n await this.sql.query(\n `INSERT INTO ${this.t.messageLink} (message_id, position, url) VALUES ${values} ON CONFLICT DO NOTHING`,\n [messageId, ...urls]\n );\n }\n\n async recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean> {\n // In a transaction: read through Hyperdrive, a bare read may come from its cache, from before\n // the copy existed\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string; delivered_at: number | string }>(\n `SELECT user_id, ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1`,\n [messageId]\n );\n const row = rows[0];\n if (row === undefined) return false;\n const open = judge({ userId: row.user_id, deliveredAt: Number(row.delivered_at) });\n if (open === undefined) return true;\n await tx.query(\n `INSERT INTO ${this.t.messageOpen}\n (id, message_id, opened_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, ${TS('$3')}, $4, $5, $6, $7, $8, $9)`,\n [\n uuidv7(open.at),\n messageId,\n open.at,\n open.machine,\n open.reason,\n open.userAgent,\n open.asn,\n open.organization,\n open.country,\n ]\n );\n await tx.query(\n `UPDATE ${this.t.message} SET\n opened_at = coalesce(opened_at, ${TS('$2')}),\n human_opened_at = CASE WHEN $3 THEN human_opened_at ELSE coalesce(human_opened_at, ${TS('$2')}) END\n WHERE id = $1`,\n [messageId, open.at, open.machine]\n );\n return true;\n });\n }\n\n async 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 return this.sql.transaction(async (tx) => {\n // The copy's row is the lock: concurrent clicks on it are judged one at a time\n const messages = await tx.query<{ delivered_at: number | string }>(\n `SELECT ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1 FOR UPDATE`,\n [messageId]\n );\n const message = messages[0];\n if (message === undefined) return undefined;\n const links = await tx.query<{ url: string; link_count: number | string }>(\n `SELECT l.url,\n (SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count\n FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`,\n [messageId, position]\n );\n const link = links[0];\n if (link === undefined) return undefined;\n const since = at - windowMs;\n const recent = await tx.query<{ position: number; at: number | string }>(\n `SELECT position, ${MS('clicked_at')} AS at FROM ${this.t.messageClick}\n WHERE message_id = $1 AND clicked_at >= ${TS('$2')} ORDER BY clicked_at`,\n [messageId, since]\n );\n const { engagement: click, backdate } = judge({\n url: link.url,\n deliveredAt: Number(message.delivered_at),\n linkCount: Number(link.link_count),\n recent: recent.map((row) => ({ position: row.position, at: Number(row.at) })),\n });\n await tx.query(\n `INSERT INTO ${this.t.messageClick}\n (id, message_id, position, url, clicked_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6, $7, $8, $9, $10, $11)`,\n [\n uuidv7(click.at),\n messageId,\n position,\n link.url,\n click.at,\n click.machine,\n click.reason,\n click.userAgent,\n click.asn,\n click.organization,\n click.country,\n ]\n );\n if (backdate) {\n // A walk across the copy is found on its later clicks: the earlier ones were part of it\n await tx.query(\n `UPDATE ${this.t.messageClick} SET machine = true, reason = $4\n WHERE message_id = $1 AND NOT machine\n AND clicked_at BETWEEN ${TS('$2')} AND ${TS('$3')}`,\n [messageId, since, at, click.reason]\n );\n }\n // First opens and clicks, from the classified rows (a click implies an open)\n await tx.query(\n `UPDATE ${this.t.message} m SET\n clicked_at = coalesce(m.clicked_at, ${TS('$2')}),\n opened_at = coalesce(m.opened_at, ${TS('$2')}),\n human_clicked_at = (SELECT min(c.clicked_at) FROM ${this.t.messageClick} c\n WHERE c.message_id = m.id AND NOT c.machine),\n human_opened_at = (SELECT min(t) FROM (\n SELECT o.opened_at AS t FROM ${this.t.messageOpen} o WHERE o.message_id = m.id AND NOT o.machine\n UNION ALL\n SELECT c.clicked_at FROM ${this.t.messageClick} c WHERE c.message_id = m.id AND NOT c.machine\n ) human)\n WHERE m.id = $1`,\n [messageId, at]\n );\n return { url: link.url, engagement: click };\n });\n }\n\n async recordDeviceDelivered(messageId: string, at: number): Promise<boolean> {\n const rows = await this.sql.query<{ id: string }>(\n `UPDATE ${this.t.message} SET device_delivered_at = coalesce(device_delivered_at, ${TS('$2')})\n WHERE id = $1 RETURNING id`,\n [messageId, at]\n );\n return rows.length > 0;\n }\n\n async recordUnsubscribe(messageId: string, at: number): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string }>(\n `UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS('$2')})\n WHERE id = $1 AND channel = 'email' RETURNING user_id`,\n [messageId, at]\n );\n const userId = rows[0]?.user_id;\n if (userId === undefined) return false;\n // The opt-out itself: the engine sends this user no more email\n await tx.query(\n `INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n return true;\n });\n }\n\n async snapshotSegments(at: number): Promise<{ segment: string; size: number }[]> {\n return this.sql.transaction(async (tx) => {\n // Segments no longer deployed take their members with them\n await tx.query(\n `DELETE FROM ${this.t.segmentMember} m\n WHERE NOT EXISTS (SELECT 1 FROM ${this.t.segment} s WHERE s.id = m.segment)`\n );\n const rows = await tx.query<{ segment: string; size: number | string }>(\n `INSERT INTO ${this.t.segmentSnapshot} (segment, taken_at, size)\n SELECT s.id, ${TS('$1')}, (SELECT count(*) FROM ${this.t.segmentMember} m WHERE m.segment = s.id)\n FROM ${this.t.segment} s\n ON CONFLICT DO NOTHING\n RETURNING segment, size`,\n [at]\n );\n return rows\n .map((row) => ({ segment: row.segment, size: Number(row.size) }))\n .sort((a, b) => a.segment.localeCompare(b.segment));\n });\n }\n}\n"],"mappings":";;;;;;AAQA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AACpD,MAAM,MAAM,WAAmB,uBAAuB,OAAO;;;;;;;AAQ7D,IAAa,oBAAb,MAA2D;CAEtC;CACA;CAFnB,YACE,KACA,GACA;EAFiB,KAAA,MAAA;EACA,KAAA,IAAA;CAChB;CAEH,MAAM,gBAAgB,OAKJ;EAChB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;6BACR,GAAG,IAAI,EAAE;8CAEhC;GAAC,MAAM;GAAY,MAAM;GAAU,MAAM;GAAQ,MAAM;EAAE,CAC3D;CACF;CAEA,MAAM,YAAY,OAMA;EAChB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;6BACR,GAAG,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE;wGAEjD;GAAC,MAAM;GAAY,MAAM;GAAU,MAAM;GAAQ,MAAM;GAAI,MAAM;EAAM,CACzE;CACF;CAEA,MAAM,iBAAiB,OAOL;EAEhB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;;6BAER,GAAG,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE;;oFAG9D;GACE,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM,e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ACT,CAAC;CACH;CAEA,MAAM,iBAAiB,IAA0D;EAC/E,OAAO,KAAK,IAAI,YAAY,OAAO,OAAO;GAExC,MAAM,GAAG,MACP,eAAe,KAAK,EAAE,cAAc;2CACD,KAAK,EAAE,QAAQ,2BACpD;GASA,QAAO,MARY,GAAG,MACpB,eAAe,KAAK,EAAE,gBAAgB;wBACtB,GAAG,IAAI,EAAE,0BAA0B,KAAK,EAAE,cAAc;gBAChE,KAAK,EAAE,QAAQ;;mCAGvB,CAAC,EAAE,CACL,EAAA,CAEG,KAAK,SAAS;IAAE,SAAS,IAAI;IAAS,MAAM,OAAO,IAAI,IAAI;GAAE,EAAE,CAAC,CAChE,MAAM,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;EACtD,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"postgres-reporting.mjs","names":[],"sources":["../../src/store/postgres-reporting.ts"],"sourcesContent":["import type { ClickContext, Engagement, JourneyReporting, MessageRecord } from './index';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport type { TableKey } from './tables';\n\n/**\n * Epoch milliseconds → timestamptz, and back: numbers in and out, whatever the driver maps (a\n * driver may hand a double or a bigint count back as a string).\n */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\nconst MS = (column: string) => `(extract(epoch from ${column}) * 1000)::double precision`;\n\n/**\n * Journey reporting on the engine's Postgres schema (tables.ts: instance, message,\n * message_link, message_open, message_click, segment_member, segment_snapshot). Every timestamp\n * is written here, never defaulted, and every write is idempotent: the engine reports again when\n * a step is retried.\n */\nexport class PostgresReporting implements JourneyReporting {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly t: Record<TableKey, string>\n ) {}\n\n async instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO NOTHING`,\n [input.instanceId, input.workflow, input.userId, input.at]\n );\n }\n\n async nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.instance} (instance_id, workflow, user_id, entered_at, node_id, node_at, status)\n VALUES ($1, $2, $3, ${TS('$4')}, $5, ${TS('$4')}, 'running')\n ON CONFLICT (instance_id) DO UPDATE SET node_id = EXCLUDED.node_id, node_at = EXCLUDED.node_at`,\n [input.instanceId, input.workflow, input.userId, input.at, input.nodeId]\n );\n }\n\n async instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void> {\n // An upsert: an instance that started before its start was reported still gets its row\n await this.sql.query(\n `INSERT INTO ${this.t.instance}\n (instance_id, workflow, user_id, entered_at, status, finished_at, converted_at)\n VALUES ($1, $2, $3, ${TS('$5')}, $4, ${TS('$5')}, ${TS('$6')})\n ON CONFLICT (instance_id) DO UPDATE SET status = EXCLUDED.status,\n finished_at = EXCLUDED.finished_at, converted_at = EXCLUDED.converted_at`,\n [\n input.instanceId,\n input.workflow,\n input.userId,\n input.status,\n input.at,\n input.convertedAt ?? null,\n ]\n );\n }\n\n async recordMessage(message: MessageRecord): Promise<string> {\n // A retried step records the same copy again: the row it already wrote is the one\n const rows = await this.sql.query<{ id: string }>(\n `INSERT INTO ${this.t.message}\n (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, sent_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${TS('$9')})\n ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key\n RETURNING id`,\n [\n uuidv7(message.sentAt),\n message.idempotencyKey,\n message.workflow,\n message.instanceId,\n message.nodeId,\n message.template,\n message.channel,\n message.userId,\n message.sentAt,\n ]\n );\n const id = rows.at(0)?.id;\n if (id === undefined) throw new Error(`message ${message.idempotencyKey} was not recorded`);\n return id;\n }\n\n async settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void> {\n if (result.delivered) {\n await this.sql.query(\n `UPDATE ${this.t.message} SET delivered_at = coalesce(delivered_at, ${TS('$2')}) WHERE idempotency_key = $1`,\n [idempotencyKey, at]\n );\n } else {\n await this.sql.query(\n `UPDATE ${this.t.message} SET undelivered_reason = $2 WHERE idempotency_key = $1`,\n [idempotencyKey, result.reason]\n );\n }\n }\n\n async recordLinks(messageId: string, urls: readonly string[]): Promise<void> {\n if (urls.length === 0) return;\n const values = urls.map((_, i) => `($1, ${i}, $${i + 2})`).join(', ');\n await this.sql.query(\n `INSERT INTO ${this.t.messageLink} (message_id, position, url) VALUES ${values} ON CONFLICT DO NOTHING`,\n [messageId, ...urls]\n );\n }\n\n async recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean> {\n // In a transaction: read through Hyperdrive, a bare read may come from its cache, from before\n // the copy existed\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string; delivered_at: number | string }>(\n `SELECT user_id, ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1`,\n [messageId]\n );\n const row = rows.at(0);\n if (row === undefined) return false;\n const open = judge({ userId: row.user_id, deliveredAt: Number(row.delivered_at) });\n if (open === undefined) return true;\n await tx.query(\n `INSERT INTO ${this.t.messageOpen}\n (id, message_id, opened_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, ${TS('$3')}, $4, $5, $6, $7, $8, $9)`,\n [\n uuidv7(open.at),\n messageId,\n open.at,\n open.machine,\n open.reason,\n open.userAgent,\n open.asn,\n open.organization,\n open.country,\n ]\n );\n await tx.query(\n `UPDATE ${this.t.message} SET\n opened_at = coalesce(opened_at, ${TS('$2')}),\n human_opened_at = CASE WHEN $3 THEN human_opened_at ELSE coalesce(human_opened_at, ${TS('$2')}) END\n WHERE id = $1`,\n [messageId, open.at, open.machine]\n );\n return true;\n });\n }\n\n async 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 return this.sql.transaction(async (tx) => {\n // The copy's row is the lock: concurrent clicks on it are judged one at a time\n const messages = await tx.query<{ delivered_at: number | string }>(\n `SELECT ${MS('coalesce(delivered_at, sent_at)')} AS delivered_at\n FROM ${this.t.message} WHERE id = $1 FOR UPDATE`,\n [messageId]\n );\n const message = messages.at(0);\n if (message === undefined) return undefined;\n const links = await tx.query<{ url: string; link_count: number | string }>(\n `SELECT l.url,\n (SELECT count(*) FROM ${this.t.messageLink} a WHERE a.message_id = l.message_id) AS link_count\n FROM ${this.t.messageLink} l WHERE l.message_id = $1 AND l.position = $2`,\n [messageId, position]\n );\n const link = links.at(0);\n if (link === undefined) return undefined;\n const since = at - windowMs;\n const recent = await tx.query<{ position: number; at: number | string }>(\n `SELECT position, ${MS('clicked_at')} AS at FROM ${this.t.messageClick}\n WHERE message_id = $1 AND clicked_at >= ${TS('$2')} ORDER BY clicked_at`,\n [messageId, since]\n );\n const { engagement: click, backdate } = judge({\n url: link.url,\n deliveredAt: Number(message.delivered_at),\n linkCount: Number(link.link_count),\n recent: recent.map((row) => ({ position: row.position, at: Number(row.at) })),\n });\n await tx.query(\n `INSERT INTO ${this.t.messageClick}\n (id, message_id, position, url, clicked_at, machine, reason, user_agent, asn, as_organization, country)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6, $7, $8, $9, $10, $11)`,\n [\n uuidv7(click.at),\n messageId,\n position,\n link.url,\n click.at,\n click.machine,\n click.reason,\n click.userAgent,\n click.asn,\n click.organization,\n click.country,\n ]\n );\n if (backdate) {\n // A walk across the copy is found on its later clicks: the earlier ones were part of it\n await tx.query(\n `UPDATE ${this.t.messageClick} SET machine = true, reason = $4\n WHERE message_id = $1 AND NOT machine\n AND clicked_at BETWEEN ${TS('$2')} AND ${TS('$3')}`,\n [messageId, since, at, click.reason]\n );\n }\n // First opens and clicks, from the classified rows (a click implies an open)\n await tx.query(\n `UPDATE ${this.t.message} m SET\n clicked_at = coalesce(m.clicked_at, ${TS('$2')}),\n opened_at = coalesce(m.opened_at, ${TS('$2')}),\n human_clicked_at = (SELECT min(c.clicked_at) FROM ${this.t.messageClick} c\n WHERE c.message_id = m.id AND NOT c.machine),\n human_opened_at = (SELECT min(t) FROM (\n SELECT o.opened_at AS t FROM ${this.t.messageOpen} o WHERE o.message_id = m.id AND NOT o.machine\n UNION ALL\n SELECT c.clicked_at FROM ${this.t.messageClick} c WHERE c.message_id = m.id AND NOT c.machine\n ) human)\n WHERE m.id = $1`,\n [messageId, at]\n );\n return { url: link.url, engagement: click };\n });\n }\n\n async recordDeviceDelivered(messageId: string, at: number): Promise<boolean> {\n const rows = await this.sql.query<{ id: string }>(\n `UPDATE ${this.t.message} SET device_delivered_at = coalesce(device_delivered_at, ${TS('$2')})\n WHERE id = $1 RETURNING id`,\n [messageId, at]\n );\n return rows.length > 0;\n }\n\n async recordUnsubscribe(messageId: string, at: number): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n const rows = await tx.query<{ user_id: string }>(\n `UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS('$2')})\n WHERE id = $1 AND channel = 'email' RETURNING user_id`,\n [messageId, at]\n );\n const userId = rows.at(0)?.user_id;\n if (userId === undefined) return false;\n // The opt-out itself: the engine sends this user no more email\n await tx.query(\n `INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n return true;\n });\n }\n\n async snapshotSegments(at: number): Promise<{ segment: string; size: number }[]> {\n return this.sql.transaction(async (tx) => {\n // Segments no longer deployed take their members with them\n await tx.query(\n `DELETE FROM ${this.t.segmentMember} m\n WHERE NOT EXISTS (SELECT 1 FROM ${this.t.segment} s WHERE s.id = m.segment)`\n );\n const rows = await tx.query<{ segment: string; size: number | string }>(\n `INSERT INTO ${this.t.segmentSnapshot} (segment, taken_at, size)\n SELECT s.id, ${TS('$1')}, (SELECT count(*) FROM ${this.t.segmentMember} m WHERE m.segment = s.id)\n FROM ${this.t.segment} s\n ON CONFLICT DO NOTHING\n RETURNING segment, size`,\n [at]\n );\n return rows\n .map((row) => ({ segment: row.segment, size: Number(row.size) }))\n .sort((a, b) => a.segment.localeCompare(b.segment));\n });\n }\n}\n"],"mappings":";;;;;;AAQA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AACpD,MAAM,MAAM,WAAmB,uBAAuB,OAAO;;;;;;;AAQ7D,IAAa,oBAAb,MAA2D;CAEtC;CACA;CAFnB,YACE,KACA,GACA;EAFiB,KAAA,MAAA;EACA,KAAA,IAAA;CAChB;CAEH,MAAM,gBAAgB,OAKJ;EAChB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;6BACR,GAAG,IAAI,EAAE;8CAEhC;GAAC,MAAM;GAAY,MAAM;GAAU,MAAM;GAAQ,MAAM;EAAE,CAC3D;CACF;CAEA,MAAM,YAAY,OAMA;EAChB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;6BACR,GAAG,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE;wGAEjD;GAAC,MAAM;GAAY,MAAM;GAAU,MAAM;GAAQ,MAAM;GAAI,MAAM;EAAM,CACzE;CACF;CAEA,MAAM,iBAAiB,OAOL;EAEhB,MAAM,KAAK,IAAI,MACb,eAAe,KAAK,EAAE,SAAS;;6BAER,GAAG,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE;;oFAG9D;GACE,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM;GACN,MAAM,eAAe;EACvB,CACF;CACF;CAEA,MAAM,cAAc,SAAyC;EAoB3D,MAAM,MAAK,MAlBQ,KAA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