@shware/workflow 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -4
- package/dist/aws/engine-step.cjs +2 -3
- package/dist/aws/engine-step.cjs.map +1 -1
- package/dist/aws/engine-step.d.cts +10 -0
- package/dist/aws/engine-step.d.cts.map +1 -1
- package/dist/aws/engine-step.d.mts +10 -0
- package/dist/aws/engine-step.d.mts.map +1 -1
- package/dist/aws/engine-step.mjs +2 -3
- package/dist/aws/engine-step.mjs.map +1 -1
- package/dist/aws/index.cjs +14 -6
- package/dist/aws/index.cjs.map +1 -1
- package/dist/aws/index.d.cts +12 -0
- package/dist/aws/index.d.cts.map +1 -1
- package/dist/aws/index.d.mts +12 -0
- package/dist/aws/index.d.mts.map +1 -1
- package/dist/aws/index.mjs +14 -6
- package/dist/aws/index.mjs.map +1 -1
- package/dist/aws/instances.cjs +29 -9
- package/dist/aws/instances.cjs.map +1 -1
- package/dist/aws/instances.d.cts +24 -5
- package/dist/aws/instances.d.cts.map +1 -1
- package/dist/aws/instances.d.mts +24 -5
- package/dist/aws/instances.d.mts.map +1 -1
- package/dist/aws/instances.mjs +29 -9
- package/dist/aws/instances.mjs.map +1 -1
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +2 -0
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +2 -0
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/runner.cjs +4 -5
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +4 -5
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/engine/duration.cjs +34 -0
- package/dist/engine/duration.cjs.map +1 -0
- package/dist/engine/duration.d.cts +5 -0
- package/dist/engine/duration.d.cts.map +1 -0
- package/dist/engine/duration.d.mts +5 -0
- package/dist/engine/duration.d.mts.map +1 -0
- package/dist/engine/duration.mjs +33 -0
- package/dist/engine/duration.mjs.map +1 -0
- package/dist/engine/index.cjs +5 -0
- package/dist/engine/index.d.cts +3 -1
- package/dist/engine/index.d.mts +3 -1
- package/dist/engine/index.mjs +3 -1
- package/dist/engine/retry.cjs +29 -0
- package/dist/engine/retry.cjs.map +1 -0
- package/dist/engine/retry.d.cts +17 -0
- package/dist/engine/retry.d.cts.map +1 -0
- package/dist/engine/retry.d.mts +17 -0
- package/dist/engine/retry.d.mts.map +1 -0
- package/dist/engine/retry.mjs +27 -0
- package/dist/engine/retry.mjs.map +1 -0
- package/dist/host/execute.cjs +6 -7
- package/dist/host/execute.cjs.map +1 -1
- package/dist/host/execute.d.cts +0 -4
- package/dist/host/execute.d.cts.map +1 -1
- package/dist/host/execute.d.mts +0 -4
- package/dist/host/execute.d.mts.map +1 -1
- package/dist/host/execute.mjs +6 -7
- package/dist/host/execute.mjs.map +1 -1
- package/dist/host/journey-host.cjs +15 -0
- package/dist/host/journey-host.cjs.map +1 -1
- package/dist/host/journey-host.d.cts.map +1 -1
- package/dist/host/journey-host.d.mts.map +1 -1
- package/dist/host/journey-host.mjs +15 -0
- package/dist/host/journey-host.mjs.map +1 -1
- package/dist/host/router.cjs +7 -5
- package/dist/host/router.cjs.map +1 -1
- package/dist/host/router.d.cts.map +1 -1
- package/dist/host/router.d.mts.map +1 -1
- package/dist/host/router.mjs +7 -5
- package/dist/host/router.mjs.map +1 -1
- package/dist/http2-client.cjs +7 -5
- package/dist/http2-client.cjs.map +1 -1
- package/dist/http2-client.d.cts +5 -2
- package/dist/http2-client.d.cts.map +1 -1
- package/dist/http2-client.d.mts +5 -2
- package/dist/http2-client.d.mts.map +1 -1
- package/dist/http2-client.mjs +7 -5
- package/dist/http2-client.mjs.map +1 -1
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +11 -0
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +11 -0
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres.cjs +37 -13
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +6 -0
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +6 -0
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +37 -13
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +6 -3
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +6 -3
- package/dist/store/tables.mjs.map +1 -1
- package/dist/transports/cloudflare-email.cjs +4 -0
- package/dist/transports/cloudflare-email.cjs.map +1 -1
- package/dist/transports/cloudflare-email.d.cts +2 -0
- package/dist/transports/cloudflare-email.d.cts.map +1 -1
- package/dist/transports/cloudflare-email.d.mts +2 -0
- package/dist/transports/cloudflare-email.d.mts.map +1 -1
- package/dist/transports/cloudflare-email.mjs +4 -0
- package/dist/transports/cloudflare-email.mjs.map +1 -1
- package/dist/transports/ses.cjs +4 -0
- package/dist/transports/ses.cjs.map +1 -1
- package/dist/transports/ses.d.cts +2 -0
- package/dist/transports/ses.d.cts.map +1 -1
- package/dist/transports/ses.d.mts +2 -0
- package/dist/transports/ses.d.mts.map +1 -1
- package/dist/transports/ses.mjs +4 -0
- package/dist/transports/ses.mjs.map +1 -1
- package/dist/transports/sigv4.cjs +6 -1
- package/dist/transports/sigv4.cjs.map +1 -1
- package/dist/transports/sigv4.d.cts.map +1 -1
- package/dist/transports/sigv4.d.mts.map +1 -1
- package/dist/transports/sigv4.mjs +6 -1
- package/dist/transports/sigv4.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.cjs","names":["TABLES","PostgresReporting","columnName","uuidv7","ConditionIR","WorkflowIR"],"sources":["../../src/store/postgres.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport { type BundleIR, ConditionIR, WorkflowIR } from '../ir';\nimport type {\n BundleVersion,\n DeviceInput,\n EntryInput,\n EntryOutcome,\n EventInput,\n EventWindow,\n ExecutionRecord,\n ExecutionRegistry,\n ExecutionStart,\n JourneyReporting,\n JourneyStore,\n ProfileProps,\n SegmentTriggerRoute,\n TriggerRoute,\n} from './index';\nimport { PostgresReporting } from './postgres-reporting';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport { type ColumnType, DEFAULT_SCHEMA, TABLES, type TableKey, columnName } from './tables';\n\nexport { DEFAULT_SCHEMA } from './tables';\nexport { type SqlClientLike, uuidv7 } from './sql';\n\nexport interface PostgresJourneyStoreOptions {\n /**\n * The Postgres schema the engine's tables live in — `workflow` by default, the config's\n * `database.schema` under journeyWorker. A schema of its own keeps the tables apart from the\n * app's. The host creates them with its own migrations, from the drizzle file\n * `renderDrizzleSchema` generates (or the plain `renderPostgresDdl`).\n */\n schema?: string;\n}\n\n/** information_schema's udt_name per column type. */\nconst UDT: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'int4',\n boolean: 'bool',\n};\n\n/** Epoch milliseconds → timestamptz, so the tables keep the database's native type. */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\n\nfunction asJson<T>(value: unknown): T {\n return (typeof value === 'string' ? JSON.parse(value) : value) as T;\n}\n\n/**\n * Journey data plane on Postgres. Same contract as D1JourneyStore, native\n * types where Postgres has them (jsonb, timestamptz), and the concurrency\n * guarantees come from the database: ON CONFLICT for the once policy and\n * idempotent subscriptions, a transaction for the route swap, a jsonb merge\n * for /identify. The tables are declared in tables.ts.\n */\nexport class PostgresJourneyStore implements JourneyStore {\n private readonly t: Record<TableKey, string>;\n private readonly schema: string;\n readonly reporting: JourneyReporting;\n readonly executions: ExecutionRegistry;\n\n constructor(\n private readonly sql: SqlClientLike,\n options: PostgresJourneyStoreOptions = {}\n ) {\n this.schema = options.schema ?? DEFAULT_SCHEMA;\n const qualify = (name: string) => `\"${this.schema}\".\"${name}\"`;\n this.t = Object.fromEntries(\n (Object.keys(TABLES) as TableKey[]).map((key) => [key, qualify(TABLES[key].name)])\n ) as Record<TableKey, string>;\n this.reporting = new PostgresReporting(sql, this.t);\n this.executions = new PostgresExecutions(sql, this.t.execution, this.t.entry);\n }\n\n /**\n * What the live database lacks against tables.ts: missing tables, missing columns, a column\n * of another type or nullability. Read-only — the engine never migrates the host's database; a\n * deploy fails with these problems listed, and the fix is to regenerate the drizzle file and\n * run the host's migrations.\n */\n async checkSchema(): Promise<string[]> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache — a\n // deploy right after the migration must see the new columns\n const rows = await this.sql.transaction((tx) =>\n tx.query<{\n table_name: string;\n column_name: string;\n udt_name: string;\n is_nullable: string;\n }>(\n `SELECT table_name, column_name, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = $1`,\n [this.schema]\n )\n );\n const live = new Map(rows.map((row) => [`${row.table_name}.${row.column_name}`, row]));\n const tables = new Set(rows.map((row) => row.table_name));\n const problems: string[] = [];\n for (const spec of Object.values(TABLES)) {\n const where = `\"${this.schema}\".\"${spec.name}\"`;\n if (!tables.has(spec.name)) {\n problems.push(`table ${where} is missing`);\n continue;\n }\n for (const [key, column] of Object.entries(spec.columns)) {\n const name = columnName(key);\n const row = live.get(`${spec.name}.${name}`);\n if (row === undefined) problems.push(`column ${where}.\"${name}\" is missing`);\n else if (row.udt_name !== UDT[column.type])\n problems.push(\n `column ${where}.\"${name}\" is ${row.udt_name}, expected ${UDT[column.type]}`\n );\n else if ((row.is_nullable === 'YES') !== (column.nullable === true))\n problems.push(\n `column ${where}.\"${name}\" should be ${column.nullable ? 'nullable' : 'NOT NULL'}`\n );\n }\n }\n return problems;\n }\n\n async insertEvent(input: EventInput): Promise<boolean> {\n // The row key stays a UUID v7 (the house rule for every table); the\n // sender's occurrence id lives in event_id, whose unique index is what\n // makes a second delivery a no-op. ON CONFLICT DO NOTHING + RETURNING\n // reports which of the two happened without a second round trip.\n const rows = await this.sql.query(\n `INSERT INTO ${this.t.event} (id, event_id, user_id, name, ts, payload)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6::text::jsonb)\n ON CONFLICT (event_id) DO NOTHING RETURNING id`,\n [\n uuidv7(input.ts),\n input.id,\n input.userId,\n input.event,\n input.ts,\n JSON.stringify(input.payload),\n ]\n );\n return rows.length > 0;\n }\n\n /** The event rows of one user and name, within the window's bounds (both inclusive). */\n private eventWindow(userId: string, event: string, window?: EventWindow) {\n const params: unknown[] = [userId, event];\n let where = 'user_id = $1 AND name = $2';\n if (window?.sinceMs !== undefined) {\n params.push(window.sinceMs);\n where += ` AND ts >= ${TS(`$${params.length}`)}`;\n }\n if (window?.untilMs !== undefined) {\n params.push(window.untilMs);\n where += ` AND ts <= ${TS(`$${params.length}`)}`;\n }\n return { where, params };\n }\n\n async countEvents(userId: string, event: string, window?: EventWindow): Promise<number> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ c: number | string }>(\n `SELECT count(*)::int AS c FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return Number(rows.at(0)?.c ?? 0);\n }\n\n async listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ payload: unknown }>(\n `SELECT payload FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return rows.map((row) => asJson<Record<string, unknown>>(row.payload));\n }\n\n async getProfile(userId: string): Promise<ProfileProps | undefined> {\n const rows = await this.sql.query<{ props: unknown }>(\n `SELECT props FROM ${this.t.profile} WHERE user_id = $1`,\n [userId]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : asJson<ProfileProps>(row.props);\n }\n\n async mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps> {\n // RFC 7386 merge-patch in one statement: jsonb `||` overwrites key by key\n // and jsonb_strip_nulls then drops the keys the patch set to null (the\n // API's only way to unset a property). Atomic in the database, so two\n // concurrent identifies cannot lose each other's keys.\n const rows = await this.sql.query<{ props: unknown }>(\n `INSERT INTO ${this.t.profile} (user_id, props) VALUES ($1, jsonb_strip_nulls($2::text::jsonb))\n ON CONFLICT (user_id) DO UPDATE SET props = jsonb_strip_nulls(${this.t.profile}.props || $3::text::jsonb)\n RETURNING props`,\n // EXCLUDED.props would be the stripped insert value, so the update merges the raw patch again\n [userId, JSON.stringify(props), JSON.stringify(props)]\n );\n return asJson<ProfileProps>(rows.at(0)?.props ?? {});\n }\n\n async listUserIds(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.profile} UNION SELECT DISTINCT user_id FROM ${this.t.event}`\n );\n return rows.map((row) => row.user_id);\n }\n\n listDevices(userId: string): Promise<PushDevice[]> {\n return this.sql.query<PushDevice>(\n `SELECT token, platform FROM ${this.t.device} WHERE user_id = $1 ORDER BY ts DESC`,\n [userId]\n );\n }\n\n async upsertDevice(device: DeviceInput): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.device} (token, user_id, platform, ts) VALUES ($1, $2, $3, ${TS('$4')})\n ON CONFLICT (token) DO UPDATE SET user_id = EXCLUDED.user_id, platform = EXCLUDED.platform, ts = EXCLUDED.ts`,\n [device.token, device.userId, device.platform, device.ts]\n );\n }\n\n async requestErasure(userId: string, at: number): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.erasure} (user_id, requested_at) VALUES ($1, ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n }\n\n async pendingErasures(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.erasure} ORDER BY requested_at`\n );\n return rows.map((row) => row.user_id);\n }\n\n async runningInstances(userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ instance_id: string }>(\n `SELECT instance_id FROM ${this.t.entry} WHERE user_id = $1 AND status = 'running'`,\n [userId]\n );\n return rows.map((row) => row.instance_id);\n }\n\n async forgetUser(userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n // Children before the copies they belong to\n for (const child of [this.t.messageOpen, this.t.messageClick, this.t.messageLink]) {\n await tx.query(\n `DELETE FROM ${child} WHERE message_id IN (SELECT id FROM ${this.t.message} WHERE user_id = $1)`,\n [userId]\n );\n }\n for (const table of [\n this.t.message,\n this.t.instance,\n this.t.entry,\n this.t.execution,\n this.t.subscription,\n this.t.segmentStart,\n this.t.segmentMember,\n this.t.suppression,\n this.t.device,\n this.t.event,\n this.t.profile,\n // The request goes with the data it asked to erase\n this.t.erasure,\n ]) {\n await tx.query(`DELETE FROM ${table} WHERE user_id = $1`, [userId]);\n }\n });\n }\n\n async isSuppressed(userId: string, channel: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.suppression} WHERE user_id = $1 AND channel = $2`,\n [userId, channel]\n );\n return rows.length > 0;\n }\n\n async removeDevice(token: string): Promise<string | undefined> {\n const rows = await this.sql.query<{ user_id: string | null }>(\n `DELETE FROM ${this.t.device} WHERE token = $1 RETURNING user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async unbindDevice(token: string): Promise<string | undefined> {\n // The owner as it was before the update: RETURNING alone would only show the null\n const rows = await this.sql.query<{ user_id: string | null }>(\n `WITH old AS (SELECT token, user_id FROM ${this.t.device} WHERE token = $1 FOR UPDATE)\n UPDATE ${this.t.device} d SET user_id = NULL FROM old WHERE d.token = old.token\n RETURNING old.user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async listSegments(): Promise<{ id: string; condition: ConditionIR }[]> {\n const rows = await this.sql.query<{ id: string; condition: unknown }>(\n `SELECT id, condition FROM ${this.t.segment} ORDER BY id`\n );\n return rows.map((row) => ({\n id: row.id,\n condition: ConditionIR.parse(asJson(row.condition)),\n }));\n }\n\n async getSegmentCondition(id: string): Promise<ConditionIR | undefined> {\n const rows = await this.sql.query<{ condition: unknown }>(\n `SELECT condition FROM ${this.t.segment} WHERE id = $1`,\n [id]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : ConditionIR.parse(asJson(row.condition));\n }\n\n async findTriggers(event: string): Promise<TriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n where_clause: unknown;\n filter: unknown;\n }>(\n `SELECT workflow, hash, \"where\" AS where_clause, filter FROM ${this.t.trigger} WHERE event = $1`,\n [event]\n );\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n where: row.where_clause === null ? null : ConditionIR.parse(asJson(row.where_clause)),\n filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter)),\n }));\n }\n\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]> {\n return this.sql.query<SegmentTriggerRoute>(\n `SELECT workflow, hash, segment FROM ${this.t.segmentTrigger}`\n );\n }\n\n async putWorkflowIR(workflow: WorkflowIR): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)\n ON CONFLICT (content_hash) DO UPDATE SET ir = EXCLUDED.ir`,\n [workflow.contentHash, JSON.stringify(workflow)]\n );\n }\n\n async getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined> {\n const rows = await this.sql.query<{ ir: unknown }>(\n `SELECT ir FROM ${this.t.ir} WHERE content_hash = $1`,\n [contentHash]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : WorkflowIR.parse(asJson(row.ir));\n }\n\n replaceRoutes(bundle: BundleIR): Promise<void> {\n return this.sql.transaction((tx) => this.swapRoutes(tx, bundle));\n }\n\n async liveBundleVersion(): Promise<BundleVersion | undefined> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ version_id: string; created_at: number | string }>(\n `SELECT version_id, (extract(epoch FROM version_created_at) * 1000)::double precision AS created_at\n FROM ${this.t.deployment} WHERE scope = 'routes'`\n )\n );\n const row = rows.at(0);\n return row === undefined\n ? undefined\n : { id: row.version_id, createdAt: Number(row.created_at) };\n }\n\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n // The row lock decides between versions applying at once: the loser's WHERE re-reads the\n // winner's committed row and updates nothing\n const claimed = await tx.query(\n `INSERT INTO ${this.t.deployment} AS live (scope, version_id, version_created_at, applied_at)\n VALUES ('routes', $1, ${TS('$2')}, ${TS('$3')})\n ON CONFLICT (scope) DO UPDATE SET version_id = EXCLUDED.version_id,\n version_created_at = EXCLUDED.version_created_at, applied_at = EXCLUDED.applied_at\n WHERE live.version_created_at < EXCLUDED.version_created_at\n RETURNING scope`,\n [version.id, version.createdAt, Date.now()]\n );\n if (claimed.length === 0) return false;\n await this.swapRoutes(tx, bundle);\n return true;\n });\n }\n\n private async swapRoutes(tx: SqlClientLike, bundle: BundleIR): Promise<void> {\n await tx.query(`DELETE FROM ${this.t.trigger}`);\n await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);\n await tx.query(`DELETE FROM ${this.t.segment}`);\n for (const segment of bundle.segments) {\n await tx.query(\n `INSERT INTO ${this.t.segment} (id, condition, hash) VALUES ($1, $2::text::jsonb, $3)`,\n [segment.id, JSON.stringify(segment.condition), segment.contentHash]\n );\n }\n for (const workflow of bundle.workflows) {\n if (workflow.trigger.type === 'event') {\n await tx.query(\n `INSERT INTO ${this.t.trigger} (workflow, hash, event, \"where\", filter) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb)`,\n [\n workflow.id,\n workflow.contentHash,\n workflow.trigger.event,\n workflow.trigger.where === undefined ? null : JSON.stringify(workflow.trigger.where),\n workflow.trigger.filter === undefined ? null : JSON.stringify(workflow.trigger.filter),\n ]\n );\n } else if (workflow.trigger.type === 'segment') {\n await tx.query(\n `INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment) VALUES ($1, $2, $3)`,\n [workflow.id, workflow.contentHash, workflow.trigger.segment]\n );\n }\n }\n }\n\n async isSegmentMember(segment: string, userId: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.length > 0;\n }\n\n async addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(\n `INSERT INTO ${this.t.segmentMember} (segment, user_id, ts) VALUES ($1, $2, ${TS('$3')}) ON CONFLICT DO NOTHING`,\n [segment, userId, ts]\n );\n for (const workflow of workflows) {\n await tx.query(\n `INSERT INTO ${this.t.segmentStart} (segment, workflow, user_id, ts)\n VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [segment, workflow, userId, ts]\n );\n }\n });\n }\n\n async pendingSegmentStarts(segment: string, userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ workflow: string }>(\n `SELECT workflow FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.map((row) => row.workflow);\n }\n\n async completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void> {\n await this.sql.query(\n `DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2 AND workflow = $3`,\n [segment, userId, workflow]\n );\n }\n\n async removeSegmentMember(segment: string, userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(`DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n await tx.query(`DELETE FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n });\n }\n\n async enterJourney(entry: EntryInput): Promise<EntryOutcome> {\n const { execution } = entry;\n if (execution === undefined) return this.claimEntry(this.sql, entry);\n // The entry and the start it owes commit together: a crash between them would leave a\n // running entry no retry could ever start\n return this.sql.transaction(async (tx) => {\n const outcome = await this.claimEntry(tx, entry);\n if (outcome !== null) await this.recordStart(tx, entry, execution);\n return outcome;\n });\n }\n\n private async claimEntry(sql: SqlClientLike, entry: EntryInput): Promise<EntryOutcome> {\n // The (workflow, user_id) primary key makes the once policy atomic:\n // concurrent ingests race on the insert and exactly one wins.\n const inserted = await sql.query(\n `INSERT INTO ${this.t.entry} (workflow, user_id, instance_id, hash, status, ts)\n VALUES ($1, $2, $3, $4, 'running', ${TS('$5')})\n ON CONFLICT (workflow, user_id) DO NOTHING RETURNING instance_id`,\n [entry.workflow, entry.userId, entry.instanceId, entry.hash, entry.ts]\n );\n if (inserted.length > 0) return 'entered';\n\n // An existing row blocks the entry unless it records an instance that died:\n // 'failed' is reclaimed rather than barring the user forever over one\n // outage. The status test is inside the UPDATE, so of two concurrent\n // retries exactly one gets a row back.\n const claimed = await sql.query(\n `UPDATE ${this.t.entry} SET instance_id = $1, hash = $2, status = 'running', ts = ${TS('$3')}\n WHERE workflow = $4 AND user_id = $5 AND status = 'failed' RETURNING instance_id`,\n [entry.instanceId, entry.hash, entry.ts, entry.workflow, entry.userId]\n );\n return claimed.length > 0 ? 'reclaimed' : null;\n }\n\n private async recordStart(\n tx: SqlClientLike,\n entry: EntryInput,\n execution: ExecutionStart\n ): Promise<void> {\n await tx.query(\n `INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)\n VALUES ($1, $2, $3, $4, $5, $6, ${TS('$7')}, 0) ON CONFLICT (instance_id) DO NOTHING`,\n [\n entry.instanceId,\n entry.workflow,\n entry.userId,\n execution.name,\n execution.target,\n execution.input,\n // The start's own age (the retry budget), not the event's ts, which the producer chose\n Date.now(),\n ]\n );\n }\n\n async removeEntry(instanceId: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.entry} WHERE instance_id = $1`, [instanceId]);\n }\n\n async setEntryStatus(instanceId: string, status: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.t.entry} SET status = $1 WHERE instance_id = $2`, [\n status,\n instanceId,\n ]);\n }\n\n async findWakeHandles(userId: string, event: string): Promise<string[]> {\n const rows = await this.sql.query<{ handle: string }>(\n `SELECT DISTINCT wake_handle AS handle FROM ${this.t.subscription} WHERE user_id = $1 AND event = $2`,\n [userId, event]\n );\n return rows.map((row) => row.handle);\n }\n\n async subscribe(\n handle: string,\n userId: string,\n events: readonly string[],\n ts: number\n ): Promise<void> {\n for (const event of events) {\n await this.sql.query(\n `INSERT INTO ${this.t.subscription} (user_id, event, wake_handle, ts) VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [userId, event, handle, ts]\n );\n }\n }\n\n async unsubscribe(handle: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.subscription} WHERE wake_handle = $1`, [handle]);\n }\n}\n\ninterface ExecutionRow {\n instance_id: string;\n workflow: string;\n user_id: string;\n name: string;\n target: string;\n input: string;\n // float8 comes back as a number from most drivers, as a string from some\n created_at: number | string;\n submitted_at: number | string | null;\n arn: string | null;\n unresolved_at: number | string | null;\n callback_id: string | null;\n generation: number | string;\n deadline_at: number | string | null;\n checked_at: number | string | null;\n}\n\nconst PLAIN_COLUMNS = ['instance_id', 'workflow', 'user_id', 'name', 'target', 'input', 'arn'];\nconst MORE_PLAIN = ['callback_id', 'generation'];\nconst TIME_COLUMNS = ['created_at', 'submitted_at', 'unresolved_at', 'deadline_at', 'checked_at'];\n\n/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */\nfunction executionColumns(alias = ''): string {\n const q = alias === '' ? '' : `${alias}.`;\n return [\n ...[...PLAIN_COLUMNS, ...MORE_PLAIN].map((column) => `${q}${column}`),\n ...TIME_COLUMNS.map(\n (column) => `(extract(epoch from ${q}${column}) * 1000)::double precision AS ${column}`\n ),\n ].join(', ');\n}\n\nconst optional = <T>(value: T | null): T | undefined => value ?? undefined;\nconst ms = (value: number | string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\nfunction toRecord(row: ExecutionRow): ExecutionRecord {\n return {\n instanceId: row.instance_id,\n workflow: row.workflow,\n userId: row.user_id,\n name: row.name,\n target: row.target,\n input: row.input,\n createdAt: Number(row.created_at),\n submittedAt: ms(row.submitted_at),\n arn: optional(row.arn),\n unresolvedAt: ms(row.unresolved_at),\n callbackId: optional(row.callback_id),\n generation: Number(row.generation),\n deadlineAt: ms(row.deadline_at),\n checkedAt: ms(row.checked_at),\n };\n}\n\n/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */\nclass PostgresExecutions implements ExecutionRegistry {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly table: string,\n private readonly entry: string\n ) {}\n\n async get(instanceId: string): Promise<ExecutionRecord | undefined> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns()} FROM ${this.table} WHERE instance_id = $1`,\n [instanceId]\n );\n return rows.length === 0 ? undefined : toRecord(rows[0]);\n }\n\n async pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]> {\n const where = ['x.submitted_at IS NULL', 'x.unresolved_at IS NULL', \"e.status = 'running'\"];\n const params: unknown[] = [];\n if (filter.workflow !== undefined) {\n params.push(filter.workflow);\n where.push(`x.workflow = $${params.length}`);\n }\n if (filter.userId !== undefined) {\n params.push(filter.userId);\n where.push(`x.user_id = $${params.length}`);\n }\n if (filter.createdBefore !== undefined) {\n params.push(filter.createdBefore);\n where.push(`x.created_at < ${TS(`$${params.length}`)}`);\n }\n params.push(filter.limit);\n // Only the start the entry still names: a reclaimed entry's old start is history\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE ${where.join(' AND ')} ORDER BY x.created_at LIMIT $${params.length}`,\n params\n );\n return rows.map(toRecord);\n }\n\n async markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET submitted_at = COALESCE(submitted_at, ${TS('$2')}), arn = COALESCE($3, arn) WHERE instance_id = $1`,\n [instanceId, at, arn ?? null]\n );\n }\n\n async markUnresolved(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET unresolved_at = ${TS('$2')} WHERE instance_id = $1 AND submitted_at IS NULL`,\n [instanceId, at]\n );\n }\n\n async setArn(instanceId: string, arn: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.table} SET arn = $2 WHERE instance_id = $1`, [\n instanceId,\n arn,\n ]);\n }\n\n async armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean> {\n // The generation test is inside the UPDATE: a retried arm of an older wait cannot overwrite\n // the callback a newer one parks on\n const rows = await this.sql.query(\n `UPDATE ${this.table} SET callback_id = $2, generation = $3,\n deadline_at = CASE WHEN $4::double precision IS NULL THEN NULL ELSE ${TS('$4')} END\n WHERE instance_id = $1 AND generation <= $3 RETURNING instance_id`,\n [instanceId, callback.id, callback.generation, callback.deadlineAt ?? null]\n );\n return rows.length > 0;\n }\n\n async clearCallback(instanceId: string, generation: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET callback_id = NULL, deadline_at = NULL WHERE instance_id = $1 AND generation = $2`,\n [instanceId, generation]\n );\n }\n\n async toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE e.status = 'running' AND x.submitted_at IS NOT NULL\n AND (x.checked_at IS NULL OR x.checked_at < ${TS('$1')})\n ORDER BY x.checked_at NULLS FIRST LIMIT $2`,\n [checkedBefore, limit]\n );\n return rows.map(toRecord);\n }\n\n async markChecked(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET checked_at = ${TS('$2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AAU,iBAAiB,GAAG,EAAE;cACxB,KAAK,MAAM,UAAU,KAAK,MAAM;;uDAES,GAAG,IAAI,EAAE;oDAE1D,CAAC,eAAe,KAAK,CACvB,EAAA,CACY,IAAI,QAAQ;CAC1B;CAEA,MAAM,YAAY,YAAoB,IAA2B;EAC/D,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,oBAAoB,GAAG,IAAI,EAAE,0BAClD,CAAC,YAAY,EAAE,CACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"postgres.cjs","names":["TABLES","PostgresReporting","columnName","uuidv7","ConditionIR","WorkflowIR"],"sources":["../../src/store/postgres.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport { type BundleIR, ConditionIR, WorkflowIR } from '../ir';\nimport type {\n BundleVersion,\n DeviceInput,\n EntryInput,\n EntryOutcome,\n EventInput,\n EventWindow,\n ExecutionRecord,\n ExecutionRegistry,\n ExecutionStart,\n JourneyReporting,\n JourneyStore,\n ProfileProps,\n SegmentTriggerRoute,\n TriggerRoute,\n} from './index';\nimport { PostgresReporting } from './postgres-reporting';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport { type ColumnType, DEFAULT_SCHEMA, TABLES, type TableKey, columnName } from './tables';\n\nexport { DEFAULT_SCHEMA } from './tables';\nexport { type SqlClientLike, uuidv7 } from './sql';\n\nexport interface PostgresJourneyStoreOptions {\n /**\n * The Postgres schema the engine's tables live in — `workflow` by default, the config's\n * `database.schema` under journeyWorker. A schema of its own keeps the tables apart from the\n * app's. The host creates them with its own migrations, from the drizzle file\n * `renderDrizzleSchema` generates (or the plain `renderPostgresDdl`).\n */\n schema?: string;\n}\n\n/** information_schema's udt_name per column type. */\nconst UDT: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'int4',\n boolean: 'bool',\n};\n\n/** Epoch milliseconds → timestamptz, so the tables keep the database's native type. */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\n\nfunction asJson<T>(value: unknown): T {\n return (typeof value === 'string' ? JSON.parse(value) : value) as T;\n}\n\n/**\n * Journey data plane on Postgres. Same contract as D1JourneyStore, native\n * types where Postgres has them (jsonb, timestamptz), and the concurrency\n * guarantees come from the database: ON CONFLICT for the once policy and\n * idempotent subscriptions, a transaction for the route swap, a jsonb merge\n * for /identify. The tables are declared in tables.ts.\n */\nexport class PostgresJourneyStore implements JourneyStore {\n private readonly t: Record<TableKey, string>;\n private readonly schema: string;\n readonly reporting: JourneyReporting;\n readonly executions: ExecutionRegistry;\n\n constructor(\n private readonly sql: SqlClientLike,\n options: PostgresJourneyStoreOptions = {}\n ) {\n this.schema = options.schema ?? DEFAULT_SCHEMA;\n const qualify = (name: string) => `\"${this.schema}\".\"${name}\"`;\n this.t = Object.fromEntries(\n (Object.keys(TABLES) as TableKey[]).map((key) => [key, qualify(TABLES[key].name)])\n ) as Record<TableKey, string>;\n this.reporting = new PostgresReporting(sql, this.t);\n this.executions = new PostgresExecutions(sql, this.t.execution, this.t.entry);\n }\n\n /**\n * What the live database lacks against tables.ts: missing tables, missing columns, a column\n * of another type or nullability. Read-only — the engine never migrates the host's database; a\n * deploy fails with these problems listed, and the fix is to regenerate the drizzle file and\n * run the host's migrations.\n */\n async checkSchema(): Promise<string[]> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache — a\n // deploy right after the migration must see the new columns\n const rows = await this.sql.transaction((tx) =>\n tx.query<{\n table_name: string;\n column_name: string;\n udt_name: string;\n is_nullable: string;\n }>(\n `SELECT table_name, column_name, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = $1`,\n [this.schema]\n )\n );\n const live = new Map(rows.map((row) => [`${row.table_name}.${row.column_name}`, row]));\n const tables = new Set(rows.map((row) => row.table_name));\n const problems: string[] = [];\n for (const spec of Object.values(TABLES)) {\n const where = `\"${this.schema}\".\"${spec.name}\"`;\n if (!tables.has(spec.name)) {\n problems.push(`table ${where} is missing`);\n continue;\n }\n for (const [key, column] of Object.entries(spec.columns)) {\n const name = columnName(key);\n const row = live.get(`${spec.name}.${name}`);\n if (row === undefined) problems.push(`column ${where}.\"${name}\" is missing`);\n else if (row.udt_name !== UDT[column.type])\n problems.push(\n `column ${where}.\"${name}\" is ${row.udt_name}, expected ${UDT[column.type]}`\n );\n else if ((row.is_nullable === 'YES') !== (column.nullable === true))\n problems.push(\n `column ${where}.\"${name}\" should be ${column.nullable ? 'nullable' : 'NOT NULL'}`\n );\n }\n }\n return problems;\n }\n\n async insertEvent(input: EventInput): Promise<boolean> {\n // The row key stays a UUID v7 (the house rule for every table); the\n // sender's occurrence id lives in event_id, whose unique index is what\n // makes a second delivery a no-op. ON CONFLICT DO NOTHING + RETURNING\n // reports which of the two happened without a second round trip.\n const rows = await this.sql.query(\n `INSERT INTO ${this.t.event} (id, event_id, user_id, name, ts, payload)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6::text::jsonb)\n ON CONFLICT (event_id) DO NOTHING RETURNING id`,\n [\n uuidv7(input.ts),\n input.id,\n input.userId,\n input.event,\n input.ts,\n JSON.stringify(input.payload),\n ]\n );\n return rows.length > 0;\n }\n\n /** The event rows of one user and name, within the window's bounds (both inclusive). */\n private eventWindow(userId: string, event: string, window?: EventWindow) {\n const params: unknown[] = [userId, event];\n let where = 'user_id = $1 AND name = $2';\n if (window?.sinceMs !== undefined) {\n params.push(window.sinceMs);\n where += ` AND ts >= ${TS(`$${params.length}`)}`;\n }\n if (window?.untilMs !== undefined) {\n params.push(window.untilMs);\n where += ` AND ts <= ${TS(`$${params.length}`)}`;\n }\n return { where, params };\n }\n\n async countEvents(userId: string, event: string, window?: EventWindow): Promise<number> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ c: number | string }>(\n `SELECT count(*)::int AS c FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return Number(rows.at(0)?.c ?? 0);\n }\n\n async listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ payload: unknown }>(\n `SELECT payload FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return rows.map((row) => asJson<Record<string, unknown>>(row.payload));\n }\n\n async getProfile(userId: string): Promise<ProfileProps | undefined> {\n const rows = await this.sql.query<{ props: unknown }>(\n `SELECT props FROM ${this.t.profile} WHERE user_id = $1`,\n [userId]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : asJson<ProfileProps>(row.props);\n }\n\n async mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps> {\n // RFC 7386 merge-patch in one statement: jsonb `||` overwrites key by key\n // and jsonb_strip_nulls then drops the keys the patch set to null (the\n // API's only way to unset a property). Atomic in the database, so two\n // concurrent identifies cannot lose each other's keys.\n const rows = await this.sql.query<{ props: unknown }>(\n `INSERT INTO ${this.t.profile} (user_id, props) VALUES ($1, jsonb_strip_nulls($2::text::jsonb))\n ON CONFLICT (user_id) DO UPDATE SET props = jsonb_strip_nulls(${this.t.profile}.props || $3::text::jsonb)\n RETURNING props`,\n // EXCLUDED.props would be the stripped insert value, so the update merges the raw patch again\n [userId, JSON.stringify(props), JSON.stringify(props)]\n );\n return asJson<ProfileProps>(rows.at(0)?.props ?? {});\n }\n\n async listUserIds(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.profile} UNION SELECT DISTINCT user_id FROM ${this.t.event}`\n );\n return rows.map((row) => row.user_id);\n }\n\n listDevices(userId: string): Promise<PushDevice[]> {\n return this.sql.query<PushDevice>(\n `SELECT token, platform FROM ${this.t.device} WHERE user_id = $1 ORDER BY ts DESC`,\n [userId]\n );\n }\n\n async upsertDevice(device: DeviceInput): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.device} (token, user_id, platform, ts) VALUES ($1, $2, $3, ${TS('$4')})\n ON CONFLICT (token) DO UPDATE SET user_id = EXCLUDED.user_id, platform = EXCLUDED.platform, ts = EXCLUDED.ts`,\n [device.token, device.userId, device.platform, device.ts]\n );\n }\n\n async requestErasure(userId: string, at: number): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.erasure} (user_id, requested_at) VALUES ($1, ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n }\n\n async pendingErasures(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.erasure} ORDER BY requested_at`\n );\n return rows.map((row) => row.user_id);\n }\n\n async runningInstances(userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ instance_id: string }>(\n `SELECT instance_id FROM ${this.t.entry} WHERE user_id = $1 AND status = 'running'`,\n [userId]\n );\n return rows.map((row) => row.instance_id);\n }\n\n async forgetUser(userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n // Children before the copies they belong to\n for (const child of [this.t.messageOpen, this.t.messageClick, this.t.messageLink]) {\n await tx.query(\n `DELETE FROM ${child} WHERE message_id IN (SELECT id FROM ${this.t.message} WHERE user_id = $1)`,\n [userId]\n );\n }\n for (const table of [\n this.t.message,\n this.t.instance,\n this.t.entry,\n this.t.execution,\n this.t.subscription,\n this.t.segmentStart,\n this.t.segmentMember,\n this.t.suppression,\n this.t.device,\n this.t.event,\n this.t.profile,\n // The request goes with the data it asked to erase\n this.t.erasure,\n ]) {\n await tx.query(`DELETE FROM ${table} WHERE user_id = $1`, [userId]);\n }\n });\n }\n\n async isSuppressed(userId: string, channel: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.suppression} WHERE user_id = $1 AND channel = $2`,\n [userId, channel]\n );\n return rows.length > 0;\n }\n\n async removeDevice(token: string): Promise<string | undefined> {\n const rows = await this.sql.query<{ user_id: string | null }>(\n `DELETE FROM ${this.t.device} WHERE token = $1 RETURNING user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async unbindDevice(token: string): Promise<string | undefined> {\n // The owner as it was before the update: RETURNING alone would only show the null\n const rows = await this.sql.query<{ user_id: string | null }>(\n `WITH old AS (SELECT token, user_id FROM ${this.t.device} WHERE token = $1 FOR UPDATE)\n UPDATE ${this.t.device} d SET user_id = NULL FROM old WHERE d.token = old.token\n RETURNING old.user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async listSegments(): Promise<{ id: string; condition: ConditionIR }[]> {\n const rows = await this.sql.query<{ id: string; condition: unknown }>(\n `SELECT id, condition FROM ${this.t.segment} ORDER BY id`\n );\n return rows.map((row) => ({\n id: row.id,\n condition: ConditionIR.parse(asJson(row.condition)),\n }));\n }\n\n async getSegmentCondition(id: string): Promise<ConditionIR | undefined> {\n const rows = await this.sql.query<{ condition: unknown }>(\n `SELECT condition FROM ${this.t.segment} WHERE id = $1`,\n [id]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : ConditionIR.parse(asJson(row.condition));\n }\n\n async findTriggers(event: string): Promise<TriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n where_clause: unknown;\n filter: unknown;\n version: string | null;\n }>(\n `SELECT workflow, hash, \"where\" AS where_clause, filter, version FROM ${this.t.trigger} WHERE event = $1`,\n [event]\n );\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n where: row.where_clause === null ? null : ConditionIR.parse(asJson(row.where_clause)),\n filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter)),\n version: row.version ?? undefined,\n }));\n }\n\n async listSegmentTriggers(): Promise<SegmentTriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n segment: string;\n version: string | null;\n }>(`SELECT workflow, hash, segment, version FROM ${this.t.segmentTrigger}`);\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n segment: row.segment,\n version: row.version ?? undefined,\n }));\n }\n\n async putWorkflowIR(workflow: WorkflowIR): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)\n ON CONFLICT (content_hash) DO UPDATE SET ir = EXCLUDED.ir`,\n [workflow.contentHash, JSON.stringify(workflow)]\n );\n }\n\n async getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined> {\n const rows = await this.sql.query<{ ir: unknown }>(\n `SELECT ir FROM ${this.t.ir} WHERE content_hash = $1`,\n [contentHash]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : WorkflowIR.parse(asJson(row.ir));\n }\n\n replaceRoutes(bundle: BundleIR): Promise<void> {\n return this.sql.transaction((tx) => this.swapRoutes(tx, bundle));\n }\n\n async liveBundleVersion(): Promise<BundleVersion | undefined> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ version_id: string; created_at: number | string }>(\n `SELECT version_id, (extract(epoch FROM version_created_at) * 1000)::double precision AS created_at\n FROM ${this.t.deployment} WHERE scope = 'routes'`\n )\n );\n const row = rows.at(0);\n return row === undefined\n ? undefined\n : { id: row.version_id, createdAt: Number(row.created_at) };\n }\n\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n // The row lock decides between versions applying at once: the loser's WHERE re-reads the\n // winner's committed row and updates nothing\n const claimed = await tx.query(\n `INSERT INTO ${this.t.deployment} AS live (scope, version_id, version_created_at, applied_at)\n VALUES ('routes', $1, ${TS('$2')}, ${TS('$3')})\n ON CONFLICT (scope) DO UPDATE SET version_id = EXCLUDED.version_id,\n version_created_at = EXCLUDED.version_created_at, applied_at = EXCLUDED.applied_at\n WHERE live.version_created_at < EXCLUDED.version_created_at\n RETURNING scope`,\n [version.id, version.createdAt, Date.now()]\n );\n if (claimed.length === 0) return false;\n await this.swapRoutes(tx, bundle, version.id);\n return true;\n });\n }\n\n /** `version`: the code version applying the bundle, kept on every route it writes. */\n private async swapRoutes(tx: SqlClientLike, bundle: BundleIR, version?: string): Promise<void> {\n await tx.query(`DELETE FROM ${this.t.trigger}`);\n await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);\n await tx.query(`DELETE FROM ${this.t.segment}`);\n for (const segment of bundle.segments) {\n await tx.query(\n `INSERT INTO ${this.t.segment} (id, condition, hash) VALUES ($1, $2::text::jsonb, $3)`,\n [segment.id, JSON.stringify(segment.condition), segment.contentHash]\n );\n }\n for (const workflow of bundle.workflows) {\n if (workflow.trigger.type === 'event') {\n await tx.query(\n `INSERT INTO ${this.t.trigger} (workflow, hash, event, \"where\", filter, version) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6)`,\n [\n workflow.id,\n workflow.contentHash,\n workflow.trigger.event,\n workflow.trigger.where === undefined ? null : JSON.stringify(workflow.trigger.where),\n workflow.trigger.filter === undefined ? null : JSON.stringify(workflow.trigger.filter),\n version ?? null,\n ]\n );\n } else if (workflow.trigger.type === 'segment') {\n await tx.query(\n `INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment, version) VALUES ($1, $2, $3, $4)`,\n [workflow.id, workflow.contentHash, workflow.trigger.segment, version ?? null]\n );\n }\n }\n }\n\n async isSegmentMember(segment: string, userId: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.length > 0;\n }\n\n async addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(\n `INSERT INTO ${this.t.segmentMember} (segment, user_id, ts) VALUES ($1, $2, ${TS('$3')}) ON CONFLICT DO NOTHING`,\n [segment, userId, ts]\n );\n for (const workflow of workflows) {\n await tx.query(\n `INSERT INTO ${this.t.segmentStart} (segment, workflow, user_id, ts)\n VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [segment, workflow, userId, ts]\n );\n }\n });\n }\n\n async pendingSegmentStarts(segment: string, userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ workflow: string }>(\n `SELECT workflow FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.map((row) => row.workflow);\n }\n\n async completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void> {\n await this.sql.query(\n `DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2 AND workflow = $3`,\n [segment, userId, workflow]\n );\n }\n\n async removeSegmentMember(segment: string, userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(`DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n await tx.query(`DELETE FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n });\n }\n\n async enterJourney(entry: EntryInput): Promise<EntryOutcome> {\n const { execution } = entry;\n if (execution === undefined) return this.claimEntry(this.sql, entry);\n // The entry and the start it owes commit together: a crash between them would leave a\n // running entry no retry could ever start\n return this.sql.transaction(async (tx) => {\n const outcome = await this.claimEntry(tx, entry);\n if (outcome !== null) await this.recordStart(tx, entry, execution);\n return outcome;\n });\n }\n\n private async claimEntry(sql: SqlClientLike, entry: EntryInput): Promise<EntryOutcome> {\n // The (workflow, user_id) primary key makes the once policy atomic:\n // concurrent ingests race on the insert and exactly one wins.\n const inserted = await sql.query(\n `INSERT INTO ${this.t.entry} (workflow, user_id, instance_id, hash, status, ts)\n VALUES ($1, $2, $3, $4, 'running', ${TS('$5')})\n ON CONFLICT (workflow, user_id) DO NOTHING RETURNING instance_id`,\n [entry.workflow, entry.userId, entry.instanceId, entry.hash, entry.ts]\n );\n if (inserted.length > 0) return 'entered';\n\n // An existing row blocks the entry unless it records an instance that died:\n // 'failed' is reclaimed rather than barring the user forever over one\n // outage. The status test is inside the UPDATE, so of two concurrent\n // retries exactly one gets a row back.\n const claimed = await sql.query(\n `UPDATE ${this.t.entry} SET instance_id = $1, hash = $2, status = 'running', ts = ${TS('$3')}\n WHERE workflow = $4 AND user_id = $5 AND status = 'failed' RETURNING instance_id`,\n [entry.instanceId, entry.hash, entry.ts, entry.workflow, entry.userId]\n );\n return claimed.length > 0 ? 'reclaimed' : null;\n }\n\n /**\n * Only an entry this call claimed records a start, so a row already there is a previous\n * attempt's — a failed entry reclaimed under the same instance id (an event replayed with its\n * ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.\n */\n private async recordStart(\n tx: SqlClientLike,\n entry: EntryInput,\n execution: ExecutionStart\n ): Promise<void> {\n await tx.query(\n `INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)\n VALUES ($1, $2, $3, $4, $5, $6, ${TS('$7')}, 0)\n ON CONFLICT (instance_id) DO UPDATE SET\n name = EXCLUDED.name, target = EXCLUDED.target, input = EXCLUDED.input,\n created_at = EXCLUDED.created_at, generation = 0, submitted_at = NULL, arn = NULL,\n unresolved_at = NULL, callback_id = NULL, deadline_at = NULL, checked_at = NULL,\n stopped_at = NULL`,\n [\n entry.instanceId,\n entry.workflow,\n entry.userId,\n execution.name,\n execution.target,\n execution.input,\n // The start's own age (the retry budget), not the event's ts, which the producer chose\n Date.now(),\n ]\n );\n }\n\n async removeEntry(instanceId: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.entry} WHERE instance_id = $1`, [instanceId]);\n }\n\n async setEntryStatus(instanceId: string, status: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.t.entry} SET status = $1 WHERE instance_id = $2`, [\n status,\n instanceId,\n ]);\n }\n\n async findWakeHandles(userId: string, event: string): Promise<string[]> {\n const rows = await this.sql.query<{ handle: string }>(\n `SELECT DISTINCT wake_handle AS handle FROM ${this.t.subscription} WHERE user_id = $1 AND event = $2`,\n [userId, event]\n );\n return rows.map((row) => row.handle);\n }\n\n async subscribe(\n handle: string,\n userId: string,\n events: readonly string[],\n ts: number\n ): Promise<void> {\n for (const event of events) {\n await this.sql.query(\n `INSERT INTO ${this.t.subscription} (user_id, event, wake_handle, ts) VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [userId, event, handle, ts]\n );\n }\n }\n\n async unsubscribe(handle: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.subscription} WHERE wake_handle = $1`, [handle]);\n }\n}\n\ninterface ExecutionRow {\n instance_id: string;\n workflow: string;\n user_id: string;\n name: string;\n target: string;\n input: string;\n // float8 comes back as a number from most drivers, as a string from some\n created_at: number | string;\n submitted_at: number | string | null;\n arn: string | null;\n unresolved_at: number | string | null;\n callback_id: string | null;\n generation: number | string;\n deadline_at: number | string | null;\n checked_at: number | string | null;\n stopped_at: number | string | null;\n}\n\nconst PLAIN_COLUMNS = ['instance_id', 'workflow', 'user_id', 'name', 'target', 'input', 'arn'];\nconst MORE_PLAIN = ['callback_id', 'generation'];\nconst TIME_COLUMNS = [\n 'created_at',\n 'submitted_at',\n 'unresolved_at',\n 'deadline_at',\n 'checked_at',\n 'stopped_at',\n];\n\n/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */\nfunction executionColumns(alias = ''): string {\n const q = alias === '' ? '' : `${alias}.`;\n return [\n ...[...PLAIN_COLUMNS, ...MORE_PLAIN].map((column) => `${q}${column}`),\n ...TIME_COLUMNS.map(\n (column) => `(extract(epoch from ${q}${column}) * 1000)::double precision AS ${column}`\n ),\n ].join(', ');\n}\n\nconst optional = <T>(value: T | null): T | undefined => value ?? undefined;\nconst ms = (value: number | string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\nfunction toRecord(row: ExecutionRow): ExecutionRecord {\n return {\n instanceId: row.instance_id,\n workflow: row.workflow,\n userId: row.user_id,\n name: row.name,\n target: row.target,\n input: row.input,\n createdAt: Number(row.created_at),\n submittedAt: ms(row.submitted_at),\n arn: optional(row.arn),\n unresolvedAt: ms(row.unresolved_at),\n callbackId: optional(row.callback_id),\n generation: Number(row.generation),\n deadlineAt: ms(row.deadline_at),\n checkedAt: ms(row.checked_at),\n stoppedAt: ms(row.stopped_at),\n };\n}\n\n/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */\nclass PostgresExecutions implements ExecutionRegistry {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly table: string,\n private readonly entry: string\n ) {}\n\n async get(instanceId: string): Promise<ExecutionRecord | undefined> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns()} FROM ${this.table} WHERE instance_id = $1`,\n [instanceId]\n );\n return rows.length === 0 ? undefined : toRecord(rows[0]);\n }\n\n async pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]> {\n const where = ['x.submitted_at IS NULL', 'x.unresolved_at IS NULL', \"e.status = 'running'\"];\n const params: unknown[] = [];\n if (filter.workflow !== undefined) {\n params.push(filter.workflow);\n where.push(`x.workflow = $${params.length}`);\n }\n if (filter.userId !== undefined) {\n params.push(filter.userId);\n where.push(`x.user_id = $${params.length}`);\n }\n if (filter.createdBefore !== undefined) {\n params.push(filter.createdBefore);\n where.push(`x.created_at < ${TS(`$${params.length}`)}`);\n }\n params.push(filter.limit);\n // Only the start the entry still names: a reclaimed entry's old start is history\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE ${where.join(' AND ')} ORDER BY x.created_at LIMIT $${params.length}`,\n params\n );\n return rows.map(toRecord);\n }\n\n async markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET submitted_at = COALESCE(submitted_at, ${TS('$2')}), arn = COALESCE($3, arn) WHERE instance_id = $1`,\n [instanceId, at, arn ?? null]\n );\n }\n\n async markUnresolved(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET unresolved_at = ${TS('$2')} WHERE instance_id = $1 AND submitted_at IS NULL`,\n [instanceId, at]\n );\n }\n\n async setArn(instanceId: string, arn: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.table} SET arn = $2 WHERE instance_id = $1`, [\n instanceId,\n arn,\n ]);\n }\n\n async armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean> {\n // The generation test is inside the UPDATE: a retried arm of an older wait cannot overwrite\n // the callback a newer one parks on\n const rows = await this.sql.query(\n `UPDATE ${this.table} SET callback_id = $2, generation = $3,\n deadline_at = CASE WHEN $4::double precision IS NULL THEN NULL ELSE ${TS('$4')} END\n WHERE instance_id = $1 AND generation <= $3 RETURNING instance_id`,\n [instanceId, callback.id, callback.generation, callback.deadlineAt ?? null]\n );\n return rows.length > 0;\n }\n\n async clearCallback(instanceId: string, generation: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET callback_id = NULL, deadline_at = NULL WHERE instance_id = $1 AND generation = $2`,\n [instanceId, generation]\n );\n }\n\n async toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE e.status = 'running' AND x.submitted_at IS NOT NULL\n AND (x.checked_at IS NULL OR x.checked_at < ${TS('$1')})\n ORDER BY x.checked_at NULLS FIRST LIMIT $2`,\n [checkedBefore, limit]\n );\n return rows.map(toRecord);\n }\n\n async markStopped(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET stopped_at = COALESCE(stopped_at, ${TS('$2')}) WHERE instance_id = $1`,\n [instanceId, at]\n );\n }\n\n async markChecked(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET checked_at = ${TS('$2')} WHERE instance_id = $1`,\n [instanceId, at]\n );\n }\n}\n"],"mappings":";;;;;;;AAoCA,MAAM,MAAkC;CACtC,MAAM;CACN,MAAM;CACN,OAAO;CACP,aAAa;CACb,SAAS;CACT,SAAS;AACX;;AAGA,MAAM,MAAM,UAAkB,gBAAgB,MA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AAM,YAAY,OAAe,eAAmD;EASlF,QAAO,MARY,KAAK,IAAI,MAC1B,UAAU,iBAAiB,GAAG,EAAE;cACxB,KAAK,MAAM,UAAU,KAAK,MAAM;;uDAES,GAAG,IAAI,EAAE;oDAE1D,CAAC,eAAe,KAAK,CACvB,EAAA,CACY,IAAI,QAAQ;CAC1B;CAEA,MAAM,YAAY,YAAoB,IAA2B;EAC/D,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,yCAAyC,GAAG,IAAI,EAAE,2BACvE,CAAC,YAAY,EAAE,CACjB;CACF;CAEA,MAAM,YAAY,YAAoB,IAA2B;EAC/D,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,oBAAoB,GAAG,IAAI,EAAE,0BAClD,CAAC,YAAY,EAAE,CACjB;CACF;AACF"}
|
|
@@ -63,6 +63,7 @@ export declare class PostgresJourneyStore implements JourneyStore {
|
|
|
63
63
|
replaceRoutes(bundle: BundleIR): Promise<void>;
|
|
64
64
|
liveBundleVersion(): Promise<BundleVersion | undefined>;
|
|
65
65
|
replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;
|
|
66
|
+
/** `version`: the code version applying the bundle, kept on every route it writes. */
|
|
66
67
|
private swapRoutes;
|
|
67
68
|
isSegmentMember(segment: string, userId: string): Promise<boolean>;
|
|
68
69
|
addSegmentMember(segment: string, userId: string, ts: number, workflows: readonly string[]): Promise<void>;
|
|
@@ -71,6 +72,11 @@ export declare class PostgresJourneyStore implements JourneyStore {
|
|
|
71
72
|
removeSegmentMember(segment: string, userId: string): Promise<void>;
|
|
72
73
|
enterJourney(entry: EntryInput): Promise<EntryOutcome>;
|
|
73
74
|
private claimEntry;
|
|
75
|
+
/**
|
|
76
|
+
* Only an entry this call claimed records a start, so a row already there is a previous
|
|
77
|
+
* attempt's — a failed entry reclaimed under the same instance id (an event replayed with its
|
|
78
|
+
* ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.
|
|
79
|
+
*/
|
|
74
80
|
private recordStart;
|
|
75
81
|
removeEntry(instanceId: string): Promise<void>;
|
|
76
82
|
setEntryStatus(instanceId: string, status: string): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.cts","names":[],"sources":["../../src/store/postgres.ts"],"mappings":";;;;;;iBAyBiB;;;;;;;EAOf;;;;;;;;;qBA2BW,gCAAgC;mBAOxB;mBANF;mBACA;WACR,WAAW;WACX,YAAY;EAErB,YACmB,KAAK,eACtB,UAAS;;;;;;;EAiBL,eAAe;EAwCf,YAAY,OAAO,aAAa;;UAsB9B;EAcF,YAAY,gBAAgB,eAAe,SAAS,cAAc;EASlE,kBACJ,gBACA,eACA,SAAS,cACR,QAAQ;EASL,WAAW,iBAAiB,QAAQ;EASpC,aAAa,gBAAgB,OAAO,eAAe,QAAQ;EAe3D,eAAe;EAOrB,YAAY,iBAAiB,QAAQ;EAO/B,aAAa,QAAQ,cAAc;EAQnC,eAAe,gBAAgB,aAAa;EAQ5C,mBAAmB;EAOnB,iBAAiB,iBAAiB;EAQlC,WAAW,iBAAiB;EA6B5B,aAAa,gBAAgB,kBAAkB;EAQ/C,aAAa,gBAAgB;EAQ7B,aAAa,gBAAgB;EAW7B,gBAAgB;IAAU;IAAY,WAAW;;EAUjD,oBAAoB,aAAa,QAAQ;EASzC,aAAa,gBAAgB,QAAQ;
|
|
1
|
+
{"version":3,"file":"postgres.d.cts","names":[],"sources":["../../src/store/postgres.ts"],"mappings":";;;;;;iBAyBiB;;;;;;;EAOf;;;;;;;;;qBA2BW,gCAAgC;mBAOxB;mBANF;mBACA;WACR,WAAW;WACX,YAAY;EAErB,YACmB,KAAK,eACtB,UAAS;;;;;;;EAiBL,eAAe;EAwCf,YAAY,OAAO,aAAa;;UAsB9B;EAcF,YAAY,gBAAgB,eAAe,SAAS,cAAc;EASlE,kBACJ,gBACA,eACA,SAAS,cACR,QAAQ;EASL,WAAW,iBAAiB,QAAQ;EASpC,aAAa,gBAAgB,OAAO,eAAe,QAAQ;EAe3D,eAAe;EAOrB,YAAY,iBAAiB,QAAQ;EAO/B,aAAa,QAAQ,cAAc;EAQnC,eAAe,gBAAgB,aAAa;EAQ5C,mBAAmB;EAOnB,iBAAiB,iBAAiB;EAQlC,WAAW,iBAAiB;EA6B5B,aAAa,gBAAgB,kBAAkB;EAQ/C,aAAa,gBAAgB;EAQ7B,aAAa,gBAAgB;EAW7B,gBAAgB;IAAU;IAAY,WAAW;;EAUjD,oBAAoB,aAAa,QAAQ;EASzC,aAAa,gBAAgB,QAAQ;EAoBrC,uBAAuB,QAAQ;EAe/B,cAAc,UAAU,aAAa;EAQrC,cAAc,sBAAsB,QAAQ;EASlD,cAAc,QAAQ,WAAW;EAI3B,qBAAqB,QAAQ;EAcnC,qBAAqB,QAAQ,UAAU,SAAS,gBAAgB;;UAoBlD;EAgCR,gBAAgB,iBAAiB,iBAAiB;EAQlD,iBACJ,iBACA,gBACA,YACA,+BACC;EAgBG,qBAAqB,iBAAiB,iBAAiB;EAQvD,qBAAqB,iBAAiB,gBAAgB,mBAAmB;EAOzE,oBAAoB,iBAAiB,iBAAiB;EAatD,aAAa,OAAO,aAAa,QAAQ;UAYjC;;;;;;UA4BA;EA0BR,YAAY,qBAAqB;EAIjC,eAAe,oBAAoB,iBAAiB;EAOpD,gBAAgB,gBAAgB,gBAAgB;EAQhD,UACJ,gBACA,gBACA,2BACA,aACC;EASG,YAAY,iBAAiB"}
|
|
@@ -63,6 +63,7 @@ export declare class PostgresJourneyStore implements JourneyStore {
|
|
|
63
63
|
replaceRoutes(bundle: BundleIR): Promise<void>;
|
|
64
64
|
liveBundleVersion(): Promise<BundleVersion | undefined>;
|
|
65
65
|
replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;
|
|
66
|
+
/** `version`: the code version applying the bundle, kept on every route it writes. */
|
|
66
67
|
private swapRoutes;
|
|
67
68
|
isSegmentMember(segment: string, userId: string): Promise<boolean>;
|
|
68
69
|
addSegmentMember(segment: string, userId: string, ts: number, workflows: readonly string[]): Promise<void>;
|
|
@@ -71,6 +72,11 @@ export declare class PostgresJourneyStore implements JourneyStore {
|
|
|
71
72
|
removeSegmentMember(segment: string, userId: string): Promise<void>;
|
|
72
73
|
enterJourney(entry: EntryInput): Promise<EntryOutcome>;
|
|
73
74
|
private claimEntry;
|
|
75
|
+
/**
|
|
76
|
+
* Only an entry this call claimed records a start, so a row already there is a previous
|
|
77
|
+
* attempt's — a failed entry reclaimed under the same instance id (an event replayed with its
|
|
78
|
+
* ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.
|
|
79
|
+
*/
|
|
74
80
|
private recordStart;
|
|
75
81
|
removeEntry(instanceId: string): Promise<void>;
|
|
76
82
|
setEntryStatus(instanceId: string, status: string): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.mts","names":[],"sources":["../../src/store/postgres.ts"],"mappings":";;;;;;iBAyBiB;;;;;;;EAOf;;;;;;;;;qBA2BW,gCAAgC;mBAOxB;mBANF;mBACA;WACR,WAAW;WACX,YAAY;EAErB,YACmB,KAAK,eACtB,UAAS;;;;;;;EAiBL,eAAe;EAwCf,YAAY,OAAO,aAAa;;UAsB9B;EAcF,YAAY,gBAAgB,eAAe,SAAS,cAAc;EASlE,kBACJ,gBACA,eACA,SAAS,cACR,QAAQ;EASL,WAAW,iBAAiB,QAAQ;EASpC,aAAa,gBAAgB,OAAO,eAAe,QAAQ;EAe3D,eAAe;EAOrB,YAAY,iBAAiB,QAAQ;EAO/B,aAAa,QAAQ,cAAc;EAQnC,eAAe,gBAAgB,aAAa;EAQ5C,mBAAmB;EAOnB,iBAAiB,iBAAiB;EAQlC,WAAW,iBAAiB;EA6B5B,aAAa,gBAAgB,kBAAkB;EAQ/C,aAAa,gBAAgB;EAQ7B,aAAa,gBAAgB;EAW7B,gBAAgB;IAAU;IAAY,WAAW;;EAUjD,oBAAoB,aAAa,QAAQ;EASzC,aAAa,gBAAgB,QAA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J,gBACA,gBACA,2BACA,aACC;EASG,YAAY,iBAAiB"}
|
package/dist/store/postgres.mjs
CHANGED
|
@@ -186,15 +186,21 @@ var PostgresJourneyStore = class {
|
|
|
186
186
|
return row === void 0 ? void 0 : ConditionIR.parse(asJson(row.condition));
|
|
187
187
|
}
|
|
188
188
|
async findTriggers(event) {
|
|
189
|
-
return (await this.sql.query(`SELECT workflow, hash, "where" AS where_clause, filter FROM ${this.t.trigger} WHERE event = $1`, [event])).map((row) => ({
|
|
189
|
+
return (await this.sql.query(`SELECT workflow, hash, "where" AS where_clause, filter, version FROM ${this.t.trigger} WHERE event = $1`, [event])).map((row) => ({
|
|
190
190
|
workflow: row.workflow,
|
|
191
191
|
hash: row.hash,
|
|
192
192
|
where: row.where_clause === null ? null : ConditionIR.parse(asJson(row.where_clause)),
|
|
193
|
-
filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter))
|
|
193
|
+
filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter)),
|
|
194
|
+
version: row.version ?? void 0
|
|
194
195
|
}));
|
|
195
196
|
}
|
|
196
|
-
listSegmentTriggers() {
|
|
197
|
-
return this.sql.query(`SELECT workflow, hash, segment FROM ${this.t.segmentTrigger}`)
|
|
197
|
+
async listSegmentTriggers() {
|
|
198
|
+
return (await this.sql.query(`SELECT workflow, hash, segment, version FROM ${this.t.segmentTrigger}`)).map((row) => ({
|
|
199
|
+
workflow: row.workflow,
|
|
200
|
+
hash: row.hash,
|
|
201
|
+
segment: row.segment,
|
|
202
|
+
version: row.version ?? void 0
|
|
203
|
+
}));
|
|
198
204
|
}
|
|
199
205
|
async putWorkflowIR(workflow) {
|
|
200
206
|
await this.sql.query(`INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)
|
|
@@ -227,11 +233,12 @@ var PostgresJourneyStore = class {
|
|
|
227
233
|
version.createdAt,
|
|
228
234
|
Date.now()
|
|
229
235
|
])).length === 0) return false;
|
|
230
|
-
await this.swapRoutes(tx, bundle);
|
|
236
|
+
await this.swapRoutes(tx, bundle, version.id);
|
|
231
237
|
return true;
|
|
232
238
|
});
|
|
233
239
|
}
|
|
234
|
-
|
|
240
|
+
/** `version`: the code version applying the bundle, kept on every route it writes. */
|
|
241
|
+
async swapRoutes(tx, bundle, version) {
|
|
235
242
|
await tx.query(`DELETE FROM ${this.t.trigger}`);
|
|
236
243
|
await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);
|
|
237
244
|
await tx.query(`DELETE FROM ${this.t.segment}`);
|
|
@@ -240,17 +247,19 @@ var PostgresJourneyStore = class {
|
|
|
240
247
|
JSON.stringify(segment.condition),
|
|
241
248
|
segment.contentHash
|
|
242
249
|
]);
|
|
243
|
-
for (const workflow of bundle.workflows) if (workflow.trigger.type === "event") await tx.query(`INSERT INTO ${this.t.trigger} (workflow, hash, event, "where", filter) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb)`, [
|
|
250
|
+
for (const workflow of bundle.workflows) if (workflow.trigger.type === "event") await tx.query(`INSERT INTO ${this.t.trigger} (workflow, hash, event, "where", filter, version) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6)`, [
|
|
244
251
|
workflow.id,
|
|
245
252
|
workflow.contentHash,
|
|
246
253
|
workflow.trigger.event,
|
|
247
254
|
workflow.trigger.where === void 0 ? null : JSON.stringify(workflow.trigger.where),
|
|
248
|
-
workflow.trigger.filter === void 0 ? null : JSON.stringify(workflow.trigger.filter)
|
|
255
|
+
workflow.trigger.filter === void 0 ? null : JSON.stringify(workflow.trigger.filter),
|
|
256
|
+
version ?? null
|
|
249
257
|
]);
|
|
250
|
-
else if (workflow.trigger.type === "segment") await tx.query(`INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment) VALUES ($1, $2, $3)`, [
|
|
258
|
+
else if (workflow.trigger.type === "segment") await tx.query(`INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment, version) VALUES ($1, $2, $3, $4)`, [
|
|
251
259
|
workflow.id,
|
|
252
260
|
workflow.contentHash,
|
|
253
|
-
workflow.trigger.segment
|
|
261
|
+
workflow.trigger.segment,
|
|
262
|
+
version ?? null
|
|
254
263
|
]);
|
|
255
264
|
}
|
|
256
265
|
async isSegmentMember(segment, userId) {
|
|
@@ -316,9 +325,19 @@ var PostgresJourneyStore = class {
|
|
|
316
325
|
entry.userId
|
|
317
326
|
])).length > 0 ? "reclaimed" : null;
|
|
318
327
|
}
|
|
328
|
+
/**
|
|
329
|
+
* Only an entry this call claimed records a start, so a row already there is a previous
|
|
330
|
+
* attempt's — a failed entry reclaimed under the same instance id (an event replayed with its
|
|
331
|
+
* ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.
|
|
332
|
+
*/
|
|
319
333
|
async recordStart(tx, entry, execution) {
|
|
320
334
|
await tx.query(`INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)
|
|
321
|
-
VALUES ($1, $2, $3, $4, $5, $6, ${TS("$7")}, 0)
|
|
335
|
+
VALUES ($1, $2, $3, $4, $5, $6, ${TS("$7")}, 0)
|
|
336
|
+
ON CONFLICT (instance_id) DO UPDATE SET
|
|
337
|
+
name = EXCLUDED.name, target = EXCLUDED.target, input = EXCLUDED.input,
|
|
338
|
+
created_at = EXCLUDED.created_at, generation = 0, submitted_at = NULL, arn = NULL,
|
|
339
|
+
unresolved_at = NULL, callback_id = NULL, deadline_at = NULL, checked_at = NULL,
|
|
340
|
+
stopped_at = NULL`, [
|
|
322
341
|
entry.instanceId,
|
|
323
342
|
entry.workflow,
|
|
324
343
|
entry.userId,
|
|
@@ -364,7 +383,8 @@ const TIME_COLUMNS = [
|
|
|
364
383
|
"submitted_at",
|
|
365
384
|
"unresolved_at",
|
|
366
385
|
"deadline_at",
|
|
367
|
-
"checked_at"
|
|
386
|
+
"checked_at",
|
|
387
|
+
"stopped_at"
|
|
368
388
|
];
|
|
369
389
|
/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */
|
|
370
390
|
function executionColumns(alias = "") {
|
|
@@ -388,7 +408,8 @@ function toRecord(row) {
|
|
|
388
408
|
callbackId: optional(row.callback_id),
|
|
389
409
|
generation: Number(row.generation),
|
|
390
410
|
deadlineAt: ms(row.deadline_at),
|
|
391
|
-
checkedAt: ms(row.checked_at)
|
|
411
|
+
checkedAt: ms(row.checked_at),
|
|
412
|
+
stoppedAt: ms(row.stopped_at)
|
|
392
413
|
};
|
|
393
414
|
}
|
|
394
415
|
/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */
|
|
@@ -462,6 +483,9 @@ var PostgresExecutions = class {
|
|
|
462
483
|
AND (x.checked_at IS NULL OR x.checked_at < ${TS("$1")})
|
|
463
484
|
ORDER BY x.checked_at NULLS FIRST LIMIT $2`, [checkedBefore, limit])).map(toRecord);
|
|
464
485
|
}
|
|
486
|
+
async markStopped(instanceId, at) {
|
|
487
|
+
await this.sql.query(`UPDATE ${this.table} SET stopped_at = COALESCE(stopped_at, ${TS("$2")}) WHERE instance_id = $1`, [instanceId, at]);
|
|
488
|
+
}
|
|
465
489
|
async markChecked(instanceId, at) {
|
|
466
490
|
await this.sql.query(`UPDATE ${this.table} SET checked_at = ${TS("$2")} WHERE instance_id = $1`, [instanceId, at]);
|
|
467
491
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.mjs","names":[],"sources":["../../src/store/postgres.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport { type BundleIR, ConditionIR, WorkflowIR } from '../ir';\nimport type {\n BundleVersion,\n DeviceInput,\n EntryInput,\n EntryOutcome,\n EventInput,\n EventWindow,\n ExecutionRecord,\n ExecutionRegistry,\n ExecutionStart,\n JourneyReporting,\n JourneyStore,\n ProfileProps,\n SegmentTriggerRoute,\n TriggerRoute,\n} from './index';\nimport { PostgresReporting } from './postgres-reporting';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport { type ColumnType, DEFAULT_SCHEMA, TABLES, type TableKey, columnName } from './tables';\n\nexport { DEFAULT_SCHEMA } from './tables';\nexport { type SqlClientLike, uuidv7 } from './sql';\n\nexport interface PostgresJourneyStoreOptions {\n /**\n * The Postgres schema the engine's tables live in — `workflow` by default, the config's\n * `database.schema` under journeyWorker. A schema of its own keeps the tables apart from the\n * app's. The host creates them with its own migrations, from the drizzle file\n * `renderDrizzleSchema` generates (or the plain `renderPostgresDdl`).\n */\n schema?: string;\n}\n\n/** information_schema's udt_name per column type. */\nconst UDT: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'int4',\n boolean: 'bool',\n};\n\n/** Epoch milliseconds → timestamptz, so the tables keep the database's native type. */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\n\nfunction asJson<T>(value: unknown): T {\n return (typeof value === 'string' ? JSON.parse(value) : value) as T;\n}\n\n/**\n * Journey data plane on Postgres. Same contract as D1JourneyStore, native\n * types where Postgres has them (jsonb, timestamptz), and the concurrency\n * guarantees come from the database: ON CONFLICT for the once policy and\n * idempotent subscriptions, a transaction for the route swap, a jsonb merge\n * for /identify. The tables are declared in tables.ts.\n */\nexport class PostgresJourneyStore implements JourneyStore {\n private readonly t: Record<TableKey, string>;\n private readonly schema: string;\n readonly reporting: JourneyReporting;\n readonly executions: ExecutionRegistry;\n\n constructor(\n private readonly sql: SqlClientLike,\n options: PostgresJourneyStoreOptions = {}\n ) {\n this.schema = options.schema ?? DEFAULT_SCHEMA;\n const qualify = (name: string) => `\"${this.schema}\".\"${name}\"`;\n this.t = Object.fromEntries(\n (Object.keys(TABLES) as TableKey[]).map((key) => [key, qualify(TABLES[key].name)])\n ) as Record<TableKey, string>;\n this.reporting = new PostgresReporting(sql, this.t);\n this.executions = new PostgresExecutions(sql, this.t.execution, this.t.entry);\n }\n\n /**\n * What the live database lacks against tables.ts: missing tables, missing columns, a column\n * of another type or nullability. Read-only — the engine never migrates the host's database; a\n * deploy fails with these problems listed, and the fix is to regenerate the drizzle file and\n * run the host's migrations.\n */\n async checkSchema(): Promise<string[]> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache — a\n // deploy right after the migration must see the new columns\n const rows = await this.sql.transaction((tx) =>\n tx.query<{\n table_name: string;\n column_name: string;\n udt_name: string;\n is_nullable: string;\n }>(\n `SELECT table_name, column_name, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = $1`,\n [this.schema]\n )\n );\n const live = new Map(rows.map((row) => [`${row.table_name}.${row.column_name}`, row]));\n const tables = new Set(rows.map((row) => row.table_name));\n const problems: string[] = [];\n for (const spec of Object.values(TABLES)) {\n const where = `\"${this.schema}\".\"${spec.name}\"`;\n if (!tables.has(spec.name)) {\n problems.push(`table ${where} is missing`);\n continue;\n }\n for (const [key, column] of Object.entries(spec.columns)) {\n const name = columnName(key);\n const row = live.get(`${spec.name}.${name}`);\n if (row === undefined) problems.push(`column ${where}.\"${name}\" is missing`);\n else if (row.udt_name !== UDT[column.type])\n problems.push(\n `column ${where}.\"${name}\" is ${row.udt_name}, expected ${UDT[column.type]}`\n );\n else if ((row.is_nullable === 'YES') !== (column.nullable === true))\n problems.push(\n `column ${where}.\"${name}\" should be ${column.nullable ? 'nullable' : 'NOT NULL'}`\n );\n }\n }\n return problems;\n }\n\n async insertEvent(input: EventInput): Promise<boolean> {\n // The row key stays a UUID v7 (the house rule for every table); the\n // sender's occurrence id lives in event_id, whose unique index is what\n // makes a second delivery a no-op. ON CONFLICT DO NOTHING + RETURNING\n // reports which of the two happened without a second round trip.\n const rows = await this.sql.query(\n `INSERT INTO ${this.t.event} (id, event_id, user_id, name, ts, payload)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6::text::jsonb)\n ON CONFLICT (event_id) DO NOTHING RETURNING id`,\n [\n uuidv7(input.ts),\n input.id,\n input.userId,\n input.event,\n input.ts,\n JSON.stringify(input.payload),\n ]\n );\n return rows.length > 0;\n }\n\n /** The event rows of one user and name, within the window's bounds (both inclusive). */\n private eventWindow(userId: string, event: string, window?: EventWindow) {\n const params: unknown[] = [userId, event];\n let where = 'user_id = $1 AND name = $2';\n if (window?.sinceMs !== undefined) {\n params.push(window.sinceMs);\n where += ` AND ts >= ${TS(`$${params.length}`)}`;\n }\n if (window?.untilMs !== undefined) {\n params.push(window.untilMs);\n where += ` AND ts <= ${TS(`$${params.length}`)}`;\n }\n return { where, params };\n }\n\n async countEvents(userId: string, event: string, window?: EventWindow): Promise<number> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ c: number | string }>(\n `SELECT count(*)::int AS c FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return Number(rows.at(0)?.c ?? 0);\n }\n\n async listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ payload: unknown }>(\n `SELECT payload FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return rows.map((row) => asJson<Record<string, unknown>>(row.payload));\n }\n\n async getProfile(userId: string): Promise<ProfileProps | undefined> {\n const rows = await this.sql.query<{ props: unknown }>(\n `SELECT props FROM ${this.t.profile} WHERE user_id = $1`,\n [userId]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : asJson<ProfileProps>(row.props);\n }\n\n async mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps> {\n // RFC 7386 merge-patch in one statement: jsonb `||` overwrites key by key\n // and jsonb_strip_nulls then drops the keys the patch set to null (the\n // API's only way to unset a property). Atomic in the database, so two\n // concurrent identifies cannot lose each other's keys.\n const rows = await this.sql.query<{ props: unknown }>(\n `INSERT INTO ${this.t.profile} (user_id, props) VALUES ($1, jsonb_strip_nulls($2::text::jsonb))\n ON CONFLICT (user_id) DO UPDATE SET props = jsonb_strip_nulls(${this.t.profile}.props || $3::text::jsonb)\n RETURNING props`,\n // EXCLUDED.props would be the stripped insert value, so the update merges the raw patch again\n [userId, JSON.stringify(props), JSON.stringify(props)]\n );\n return asJson<ProfileProps>(rows.at(0)?.props ?? {});\n }\n\n async listUserIds(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.profile} UNION SELECT DISTINCT user_id FROM ${this.t.event}`\n );\n return rows.map((row) => row.user_id);\n }\n\n listDevices(userId: string): Promise<PushDevice[]> {\n return this.sql.query<PushDevice>(\n `SELECT token, platform FROM ${this.t.device} WHERE user_id = $1 ORDER BY ts DESC`,\n [userId]\n );\n }\n\n async upsertDevice(device: DeviceInput): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.device} (token, user_id, platform, ts) VALUES ($1, $2, $3, ${TS('$4')})\n ON CONFLICT (token) DO UPDATE SET user_id = EXCLUDED.user_id, platform = EXCLUDED.platform, ts = EXCLUDED.ts`,\n [device.token, device.userId, device.platform, device.ts]\n );\n }\n\n async requestErasure(userId: string, at: number): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.erasure} (user_id, requested_at) VALUES ($1, ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n }\n\n async pendingErasures(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.erasure} ORDER BY requested_at`\n );\n return rows.map((row) => row.user_id);\n }\n\n async runningInstances(userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ instance_id: string }>(\n `SELECT instance_id FROM ${this.t.entry} WHERE user_id = $1 AND status = 'running'`,\n [userId]\n );\n return rows.map((row) => row.instance_id);\n }\n\n async forgetUser(userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n // Children before the copies they belong to\n for (const child of [this.t.messageOpen, this.t.messageClick, this.t.messageLink]) {\n await tx.query(\n `DELETE FROM ${child} WHERE message_id IN (SELECT id FROM ${this.t.message} WHERE user_id = $1)`,\n [userId]\n );\n }\n for (const table of [\n this.t.message,\n this.t.instance,\n this.t.entry,\n this.t.execution,\n this.t.subscription,\n this.t.segmentStart,\n this.t.segmentMember,\n this.t.suppression,\n this.t.device,\n this.t.event,\n this.t.profile,\n // The request goes with the data it asked to erase\n this.t.erasure,\n ]) {\n await tx.query(`DELETE FROM ${table} WHERE user_id = $1`, [userId]);\n }\n });\n }\n\n async isSuppressed(userId: string, channel: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.suppression} WHERE user_id = $1 AND channel = $2`,\n [userId, channel]\n );\n return rows.length > 0;\n }\n\n async removeDevice(token: string): Promise<string | undefined> {\n const rows = await this.sql.query<{ user_id: string | null }>(\n `DELETE FROM ${this.t.device} WHERE token = $1 RETURNING user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async unbindDevice(token: string): Promise<string | undefined> {\n // The owner as it was before the update: RETURNING alone would only show the null\n const rows = await this.sql.query<{ user_id: string | null }>(\n `WITH old AS (SELECT token, user_id FROM ${this.t.device} WHERE token = $1 FOR UPDATE)\n UPDATE ${this.t.device} d SET user_id = NULL FROM old WHERE d.token = old.token\n RETURNING old.user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async listSegments(): Promise<{ id: string; condition: ConditionIR }[]> {\n const rows = await this.sql.query<{ id: string; condition: unknown }>(\n `SELECT id, condition FROM ${this.t.segment} ORDER BY id`\n );\n return rows.map((row) => ({\n id: row.id,\n condition: ConditionIR.parse(asJson(row.condition)),\n }));\n }\n\n async getSegmentCondition(id: string): Promise<ConditionIR | undefined> {\n const rows = await this.sql.query<{ condition: unknown }>(\n `SELECT condition FROM ${this.t.segment} WHERE id = $1`,\n [id]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : ConditionIR.parse(asJson(row.condition));\n }\n\n async findTriggers(event: string): Promise<TriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n where_clause: unknown;\n filter: unknown;\n }>(\n `SELECT workflow, hash, \"where\" AS where_clause, filter FROM ${this.t.trigger} WHERE event = $1`,\n [event]\n );\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n where: row.where_clause === null ? null : ConditionIR.parse(asJson(row.where_clause)),\n filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter)),\n }));\n }\n\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]> {\n return this.sql.query<SegmentTriggerRoute>(\n `SELECT workflow, hash, segment FROM ${this.t.segmentTrigger}`\n );\n }\n\n async putWorkflowIR(workflow: WorkflowIR): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)\n ON CONFLICT (content_hash) DO UPDATE SET ir = EXCLUDED.ir`,\n [workflow.contentHash, JSON.stringify(workflow)]\n );\n }\n\n async getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined> {\n const rows = await this.sql.query<{ ir: unknown }>(\n `SELECT ir FROM ${this.t.ir} WHERE content_hash = $1`,\n [contentHash]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : WorkflowIR.parse(asJson(row.ir));\n }\n\n replaceRoutes(bundle: BundleIR): Promise<void> {\n return this.sql.transaction((tx) => this.swapRoutes(tx, bundle));\n }\n\n async liveBundleVersion(): Promise<BundleVersion | undefined> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ version_id: string; created_at: number | string }>(\n `SELECT version_id, (extract(epoch FROM version_created_at) * 1000)::double precision AS created_at\n FROM ${this.t.deployment} WHERE scope = 'routes'`\n )\n );\n const row = rows.at(0);\n return row === undefined\n ? undefined\n : { id: row.version_id, createdAt: Number(row.created_at) };\n }\n\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n // The row lock decides between versions applying at once: the loser's WHERE re-reads the\n // winner's committed row and updates nothing\n const claimed = await tx.query(\n `INSERT INTO ${this.t.deployment} AS live (scope, version_id, version_created_at, applied_at)\n VALUES ('routes', $1, ${TS('$2')}, ${TS('$3')})\n ON CONFLICT (scope) DO UPDATE SET version_id = EXCLUDED.version_id,\n version_created_at = EXCLUDED.version_created_at, applied_at = EXCLUDED.applied_at\n WHERE live.version_created_at < EXCLUDED.version_created_at\n RETURNING scope`,\n [version.id, version.createdAt, Date.now()]\n );\n if (claimed.length === 0) return false;\n await this.swapRoutes(tx, bundle);\n return true;\n });\n }\n\n private async swapRoutes(tx: SqlClientLike, bundle: BundleIR): Promise<void> {\n await tx.query(`DELETE FROM ${this.t.trigger}`);\n await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);\n await tx.query(`DELETE FROM ${this.t.segment}`);\n for (const segment of bundle.segments) {\n await tx.query(\n `INSERT INTO ${this.t.segment} (id, condition, hash) VALUES ($1, $2::text::jsonb, $3)`,\n [segment.id, JSON.stringify(segment.condition), segment.contentHash]\n );\n }\n for (const workflow of bundle.workflows) {\n if (workflow.trigger.type === 'event') {\n await tx.query(\n `INSERT INTO ${this.t.trigger} (workflow, hash, event, \"where\", filter) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb)`,\n [\n workflow.id,\n workflow.contentHash,\n workflow.trigger.event,\n workflow.trigger.where === undefined ? null : JSON.stringify(workflow.trigger.where),\n workflow.trigger.filter === undefined ? null : JSON.stringify(workflow.trigger.filter),\n ]\n );\n } else if (workflow.trigger.type === 'segment') {\n await tx.query(\n `INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment) VALUES ($1, $2, $3)`,\n [workflow.id, workflow.contentHash, workflow.trigger.segment]\n );\n }\n }\n }\n\n async isSegmentMember(segment: string, userId: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.length > 0;\n }\n\n async addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(\n `INSERT INTO ${this.t.segmentMember} (segment, user_id, ts) VALUES ($1, $2, ${TS('$3')}) ON CONFLICT DO NOTHING`,\n [segment, userId, ts]\n );\n for (const workflow of workflows) {\n await tx.query(\n `INSERT INTO ${this.t.segmentStart} (segment, workflow, user_id, ts)\n VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [segment, workflow, userId, ts]\n );\n }\n });\n }\n\n async pendingSegmentStarts(segment: string, userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ workflow: string }>(\n `SELECT workflow FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.map((row) => row.workflow);\n }\n\n async completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void> {\n await this.sql.query(\n `DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2 AND workflow = $3`,\n [segment, userId, workflow]\n );\n }\n\n async removeSegmentMember(segment: string, userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(`DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n await tx.query(`DELETE FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n });\n }\n\n async enterJourney(entry: EntryInput): Promise<EntryOutcome> {\n const { execution } = entry;\n if (execution === undefined) return this.claimEntry(this.sql, entry);\n // The entry and the start it owes commit together: a crash between them would leave a\n // running entry no retry could ever start\n return this.sql.transaction(async (tx) => {\n const outcome = await this.claimEntry(tx, entry);\n if (outcome !== null) await this.recordStart(tx, entry, execution);\n return outcome;\n });\n }\n\n private async claimEntry(sql: SqlClientLike, entry: EntryInput): Promise<EntryOutcome> {\n // The (workflow, user_id) primary key makes the once policy atomic:\n // concurrent ingests race on the insert and exactly one wins.\n const inserted = await sql.query(\n `INSERT INTO ${this.t.entry} (workflow, user_id, instance_id, hash, status, ts)\n VALUES ($1, $2, $3, $4, 'running', ${TS('$5')})\n ON CONFLICT (workflow, user_id) DO NOTHING RETURNING instance_id`,\n [entry.workflow, entry.userId, entry.instanceId, entry.hash, entry.ts]\n );\n if (inserted.length > 0) return 'entered';\n\n // An existing row blocks the entry unless it records an instance that died:\n // 'failed' is reclaimed rather than barring the user forever over one\n // outage. The status test is inside the UPDATE, so of two concurrent\n // retries exactly one gets a row back.\n const claimed = await sql.query(\n `UPDATE ${this.t.entry} SET instance_id = $1, hash = $2, status = 'running', ts = ${TS('$3')}\n WHERE workflow = $4 AND user_id = $5 AND status = 'failed' RETURNING instance_id`,\n [entry.instanceId, entry.hash, entry.ts, entry.workflow, entry.userId]\n );\n return claimed.length > 0 ? 'reclaimed' : null;\n }\n\n private async recordStart(\n tx: SqlClientLike,\n entry: EntryInput,\n execution: ExecutionStart\n ): Promise<void> {\n await tx.query(\n `INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)\n VALUES ($1, $2, $3, $4, $5, $6, ${TS('$7')}, 0) ON CONFLICT (instance_id) DO NOTHING`,\n [\n entry.instanceId,\n entry.workflow,\n entry.userId,\n execution.name,\n execution.target,\n execution.input,\n // The start's own age (the retry budget), not the event's ts, which the producer chose\n Date.now(),\n ]\n );\n }\n\n async removeEntry(instanceId: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.entry} WHERE instance_id = $1`, [instanceId]);\n }\n\n async setEntryStatus(instanceId: string, status: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.t.entry} SET status = $1 WHERE instance_id = $2`, [\n status,\n instanceId,\n ]);\n }\n\n async findWakeHandles(userId: string, event: string): Promise<string[]> {\n const rows = await this.sql.query<{ handle: string }>(\n `SELECT DISTINCT wake_handle AS handle FROM ${this.t.subscription} WHERE user_id = $1 AND event = $2`,\n [userId, event]\n );\n return rows.map((row) => row.handle);\n }\n\n async subscribe(\n handle: string,\n userId: string,\n events: readonly string[],\n ts: number\n ): Promise<void> {\n for (const event of events) {\n await this.sql.query(\n `INSERT INTO ${this.t.subscription} (user_id, event, wake_handle, ts) VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [userId, event, handle, ts]\n );\n }\n }\n\n async unsubscribe(handle: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.subscription} WHERE wake_handle = $1`, [handle]);\n }\n}\n\ninterface ExecutionRow {\n instance_id: string;\n workflow: string;\n user_id: string;\n name: string;\n target: string;\n input: string;\n // float8 comes back as a number from most drivers, as a string from some\n created_at: number | string;\n submitted_at: number | string | null;\n arn: string | null;\n unresolved_at: number | string | null;\n callback_id: string | null;\n generation: number | string;\n deadline_at: number | string | null;\n checked_at: number | string | null;\n}\n\nconst PLAIN_COLUMNS = ['instance_id', 'workflow', 'user_id', 'name', 'target', 'input', 'arn'];\nconst MORE_PLAIN = ['callback_id', 'generation'];\nconst TIME_COLUMNS = ['created_at', 'submitted_at', 'unresolved_at', 'deadline_at', 'checked_at'];\n\n/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */\nfunction executionColumns(alias = ''): string {\n const q = alias === '' ? '' : `${alias}.`;\n return [\n ...[...PLAIN_COLUMNS, ...MORE_PLAIN].map((column) => `${q}${column}`),\n ...TIME_COLUMNS.map(\n (column) => `(extract(epoch from ${q}${column}) * 1000)::double precision AS ${column}`\n ),\n ].join(', ');\n}\n\nconst optional = <T>(value: T | null): T | undefined => value ?? undefined;\nconst ms = (value: number | string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\nfunction toRecord(row: ExecutionRow): ExecutionRecord {\n return {\n instanceId: row.instance_id,\n workflow: row.workflow,\n userId: row.user_id,\n name: row.name,\n target: row.target,\n input: row.input,\n createdAt: Number(row.created_at),\n submittedAt: ms(row.submitted_at),\n arn: optional(row.arn),\n unresolvedAt: ms(row.unresolved_at),\n callbackId: optional(row.callback_id),\n generation: Number(row.generation),\n deadlineAt: ms(row.deadline_at),\n checkedAt: ms(row.checked_at),\n };\n}\n\n/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */\nclass PostgresExecutions implements ExecutionRegistry {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly table: string,\n private readonly entry: string\n ) {}\n\n async get(instanceId: string): Promise<ExecutionRecord | undefined> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns()} FROM ${this.table} WHERE instance_id = $1`,\n [instanceId]\n );\n return rows.length === 0 ? undefined : toRecord(rows[0]);\n }\n\n async pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]> {\n const where = ['x.submitted_at IS NULL', 'x.unresolved_at IS NULL', \"e.status = 'running'\"];\n const params: unknown[] = [];\n if (filter.workflow !== undefined) {\n params.push(filter.workflow);\n where.push(`x.workflow = $${params.length}`);\n }\n if (filter.userId !== undefined) {\n params.push(filter.userId);\n where.push(`x.user_id = $${params.length}`);\n }\n if (filter.createdBefore !== undefined) {\n params.push(filter.createdBefore);\n where.push(`x.created_at < ${TS(`$${params.length}`)}`);\n }\n params.push(filter.limit);\n // Only the start the entry still names: a reclaimed entry's old start is history\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE ${where.join(' AND ')} ORDER BY x.created_at LIMIT $${params.length}`,\n params\n );\n return rows.map(toRecord);\n }\n\n async markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET submitted_at = COALESCE(submitted_at, ${TS('$2')}), arn = COALESCE($3, arn) WHERE instance_id = $1`,\n [instanceId, at, arn ?? null]\n );\n }\n\n async markUnresolved(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET unresolved_at = ${TS('$2')} WHERE instance_id = $1 AND submitted_at IS NULL`,\n [instanceId, at]\n );\n }\n\n async setArn(instanceId: string, arn: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.table} SET arn = $2 WHERE instance_id = $1`, [\n instanceId,\n arn,\n ]);\n }\n\n async armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean> {\n // The generation test is inside the UPDATE: a retried arm of an older wait cannot overwrite\n // the callback a newer one parks on\n const rows = await this.sql.query(\n `UPDATE ${this.table} SET callback_id = $2, generation = $3,\n deadline_at = CASE WHEN $4::double precision IS NULL THEN NULL ELSE ${TS('$4')} END\n WHERE instance_id = $1 AND generation <= $3 RETURNING instance_id`,\n [instanceId, callback.id, callback.generation, callback.deadlineAt ?? null]\n );\n return rows.length > 0;\n }\n\n async clearCallback(instanceId: string, generation: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET callback_id = NULL, deadline_at = NULL WHERE instance_id = $1 AND generation = $2`,\n [instanceId, generation]\n );\n }\n\n async toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE e.status = 'running' AND x.submitted_at IS NOT NULL\n AND (x.checked_at IS NULL OR x.checked_at < ${TS('$1')})\n ORDER BY x.checked_at NULLS FIRST LIMIT $2`,\n [checkedBefore, limit]\n );\n return rows.map(toRecord);\n }\n\n async markChecked(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET checked_at = ${TS('$2')} WHERE instance_id = $1`,\n [instanceId, at]\n );\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,MAAkC;CACtC,MAAM;CACN,MAAM;CACN,OAAO;CACP,aAAa;CACb,SAAS;CACT,SAAS;AACX;;AAGA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AAEpD,SAAS,OAAU,OAAmB;CACpC,OAAQ,OAAO,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;AAC1D;;;;;;;;AASA,IAAa,uBAAb,MAA0D;CAOrC;CANnB;CACA;CACA;CACA;CAEA,YACE,KACA,UAAuC,CAAC,GACxC;EAFiB,KAAA,MAAA;EAGjB,KAAK,SAAS,QAAQ,UAAA;EACt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EAAE,oDAC3E;GAAC;GAAY;GAAI,OAAO;EAAI,CAC9B;CACF;CAEA,MAAM,eAAe,YAAoB,IAA2B;EAClE,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,uBAAuB,GAAG,IAAI,EAAE,mDACrD,CAAC,YAAY,EAAE,CACjB;CACF;CAEA,MAAM,OAAO,YAAoB,KAA4B;EAC3D,MAAM,KAAK,IAAI,MAAM,UAAU,KAAK,MAAM,uCAAuC,CAC/E,YACA,GACF,CAAC;CACH;CAEA,MAAM,YACJ,YACA,UACkB;EASlB,QAAO,MANY,KAAK,IAAI,MAC1B,UAAU,KAAK,MAAM;+EACoD,GAAG,IAAI,EAAE;2EAElF;GAAC;GAAY,SAAS;GAAI,SAAS;GAAY,SAAS,cAAc;EAAI,CAC5E,EAAA,CACY,SAAS;CACvB;CAEA,MAAM,cAAc,YAAoB,YAAmC;EACzE,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,yFACrB,CAAC,YAAY,UAAU,CACzB;CACF;CAEA,MAAM,YAAY,OAAe,eAAmD;EASlF,QAAO,MARY,KAAK,IAAI,MAC1B,UAAU,iBAAiB,GAAG,EAAE;cACxB,KAAK,MAAM,UAAU,KAAK,MAAM;;uDAES,GAAG,IAAI,EAAE;oDAE1D,CAAC,eAAe,KAAK,CACvB,EAAA,CACY,IAAI,QAAQ;CAC1B;CAEA,MAAM,YAAY,YAAoB,IAA2B;EAC/D,MAAM,KAAK,IAAI,MACb,UAAU,KAAK,MAAM,oBAAoB,GAAG,IAAI,EAAE,0BAClD,CAAC,YAAY,EAAE,CACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"postgres.mjs","names":[],"sources":["../../src/store/postgres.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport { type BundleIR, ConditionIR, WorkflowIR } from '../ir';\nimport type {\n BundleVersion,\n DeviceInput,\n EntryInput,\n EntryOutcome,\n EventInput,\n EventWindow,\n ExecutionRecord,\n ExecutionRegistry,\n ExecutionStart,\n JourneyReporting,\n JourneyStore,\n ProfileProps,\n SegmentTriggerRoute,\n TriggerRoute,\n} from './index';\nimport { PostgresReporting } from './postgres-reporting';\nimport { type SqlClientLike, uuidv7 } from './sql';\nimport { type ColumnType, DEFAULT_SCHEMA, TABLES, type TableKey, columnName } from './tables';\n\nexport { DEFAULT_SCHEMA } from './tables';\nexport { type SqlClientLike, uuidv7 } from './sql';\n\nexport interface PostgresJourneyStoreOptions {\n /**\n * The Postgres schema the engine's tables live in — `workflow` by default, the config's\n * `database.schema` under journeyWorker. A schema of its own keeps the tables apart from the\n * app's. The host creates them with its own migrations, from the drizzle file\n * `renderDrizzleSchema` generates (or the plain `renderPostgresDdl`).\n */\n schema?: string;\n}\n\n/** information_schema's udt_name per column type. */\nconst UDT: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'int4',\n boolean: 'bool',\n};\n\n/** Epoch milliseconds → timestamptz, so the tables keep the database's native type. */\nconst TS = (param: string) => `to_timestamp(${param}::double precision / 1000)`;\n\nfunction asJson<T>(value: unknown): T {\n return (typeof value === 'string' ? JSON.parse(value) : value) as T;\n}\n\n/**\n * Journey data plane on Postgres. Same contract as D1JourneyStore, native\n * types where Postgres has them (jsonb, timestamptz), and the concurrency\n * guarantees come from the database: ON CONFLICT for the once policy and\n * idempotent subscriptions, a transaction for the route swap, a jsonb merge\n * for /identify. The tables are declared in tables.ts.\n */\nexport class PostgresJourneyStore implements JourneyStore {\n private readonly t: Record<TableKey, string>;\n private readonly schema: string;\n readonly reporting: JourneyReporting;\n readonly executions: ExecutionRegistry;\n\n constructor(\n private readonly sql: SqlClientLike,\n options: PostgresJourneyStoreOptions = {}\n ) {\n this.schema = options.schema ?? DEFAULT_SCHEMA;\n const qualify = (name: string) => `\"${this.schema}\".\"${name}\"`;\n this.t = Object.fromEntries(\n (Object.keys(TABLES) as TableKey[]).map((key) => [key, qualify(TABLES[key].name)])\n ) as Record<TableKey, string>;\n this.reporting = new PostgresReporting(sql, this.t);\n this.executions = new PostgresExecutions(sql, this.t.execution, this.t.entry);\n }\n\n /**\n * What the live database lacks against tables.ts: missing tables, missing columns, a column\n * of another type or nullability. Read-only — the engine never migrates the host's database; a\n * deploy fails with these problems listed, and the fix is to regenerate the drizzle file and\n * run the host's migrations.\n */\n async checkSchema(): Promise<string[]> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache — a\n // deploy right after the migration must see the new columns\n const rows = await this.sql.transaction((tx) =>\n tx.query<{\n table_name: string;\n column_name: string;\n udt_name: string;\n is_nullable: string;\n }>(\n `SELECT table_name, column_name, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = $1`,\n [this.schema]\n )\n );\n const live = new Map(rows.map((row) => [`${row.table_name}.${row.column_name}`, row]));\n const tables = new Set(rows.map((row) => row.table_name));\n const problems: string[] = [];\n for (const spec of Object.values(TABLES)) {\n const where = `\"${this.schema}\".\"${spec.name}\"`;\n if (!tables.has(spec.name)) {\n problems.push(`table ${where} is missing`);\n continue;\n }\n for (const [key, column] of Object.entries(spec.columns)) {\n const name = columnName(key);\n const row = live.get(`${spec.name}.${name}`);\n if (row === undefined) problems.push(`column ${where}.\"${name}\" is missing`);\n else if (row.udt_name !== UDT[column.type])\n problems.push(\n `column ${where}.\"${name}\" is ${row.udt_name}, expected ${UDT[column.type]}`\n );\n else if ((row.is_nullable === 'YES') !== (column.nullable === true))\n problems.push(\n `column ${where}.\"${name}\" should be ${column.nullable ? 'nullable' : 'NOT NULL'}`\n );\n }\n }\n return problems;\n }\n\n async insertEvent(input: EventInput): Promise<boolean> {\n // The row key stays a UUID v7 (the house rule for every table); the\n // sender's occurrence id lives in event_id, whose unique index is what\n // makes a second delivery a no-op. ON CONFLICT DO NOTHING + RETURNING\n // reports which of the two happened without a second round trip.\n const rows = await this.sql.query(\n `INSERT INTO ${this.t.event} (id, event_id, user_id, name, ts, payload)\n VALUES ($1, $2, $3, $4, ${TS('$5')}, $6::text::jsonb)\n ON CONFLICT (event_id) DO NOTHING RETURNING id`,\n [\n uuidv7(input.ts),\n input.id,\n input.userId,\n input.event,\n input.ts,\n JSON.stringify(input.payload),\n ]\n );\n return rows.length > 0;\n }\n\n /** The event rows of one user and name, within the window's bounds (both inclusive). */\n private eventWindow(userId: string, event: string, window?: EventWindow) {\n const params: unknown[] = [userId, event];\n let where = 'user_id = $1 AND name = $2';\n if (window?.sinceMs !== undefined) {\n params.push(window.sinceMs);\n where += ` AND ts >= ${TS(`$${params.length}`)}`;\n }\n if (window?.untilMs !== undefined) {\n params.push(window.untilMs);\n where += ` AND ts <= ${TS(`$${params.length}`)}`;\n }\n return { where, params };\n }\n\n async countEvents(userId: string, event: string, window?: EventWindow): Promise<number> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ c: number | string }>(\n `SELECT count(*)::int AS c FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return Number(rows.at(0)?.c ?? 0);\n }\n\n async listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]> {\n const { where, params } = this.eventWindow(userId, event, window);\n const rows = await this.sql.query<{ payload: unknown }>(\n `SELECT payload FROM ${this.t.event} WHERE ${where}`,\n params\n );\n return rows.map((row) => asJson<Record<string, unknown>>(row.payload));\n }\n\n async getProfile(userId: string): Promise<ProfileProps | undefined> {\n const rows = await this.sql.query<{ props: unknown }>(\n `SELECT props FROM ${this.t.profile} WHERE user_id = $1`,\n [userId]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : asJson<ProfileProps>(row.props);\n }\n\n async mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps> {\n // RFC 7386 merge-patch in one statement: jsonb `||` overwrites key by key\n // and jsonb_strip_nulls then drops the keys the patch set to null (the\n // API's only way to unset a property). Atomic in the database, so two\n // concurrent identifies cannot lose each other's keys.\n const rows = await this.sql.query<{ props: unknown }>(\n `INSERT INTO ${this.t.profile} (user_id, props) VALUES ($1, jsonb_strip_nulls($2::text::jsonb))\n ON CONFLICT (user_id) DO UPDATE SET props = jsonb_strip_nulls(${this.t.profile}.props || $3::text::jsonb)\n RETURNING props`,\n // EXCLUDED.props would be the stripped insert value, so the update merges the raw patch again\n [userId, JSON.stringify(props), JSON.stringify(props)]\n );\n return asJson<ProfileProps>(rows.at(0)?.props ?? {});\n }\n\n async listUserIds(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.profile} UNION SELECT DISTINCT user_id FROM ${this.t.event}`\n );\n return rows.map((row) => row.user_id);\n }\n\n listDevices(userId: string): Promise<PushDevice[]> {\n return this.sql.query<PushDevice>(\n `SELECT token, platform FROM ${this.t.device} WHERE user_id = $1 ORDER BY ts DESC`,\n [userId]\n );\n }\n\n async upsertDevice(device: DeviceInput): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.device} (token, user_id, platform, ts) VALUES ($1, $2, $3, ${TS('$4')})\n ON CONFLICT (token) DO UPDATE SET user_id = EXCLUDED.user_id, platform = EXCLUDED.platform, ts = EXCLUDED.ts`,\n [device.token, device.userId, device.platform, device.ts]\n );\n }\n\n async requestErasure(userId: string, at: number): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.erasure} (user_id, requested_at) VALUES ($1, ${TS('$2')})\n ON CONFLICT DO NOTHING`,\n [userId, at]\n );\n }\n\n async pendingErasures(): Promise<string[]> {\n const rows = await this.sql.query<{ user_id: string }>(\n `SELECT user_id FROM ${this.t.erasure} ORDER BY requested_at`\n );\n return rows.map((row) => row.user_id);\n }\n\n async runningInstances(userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ instance_id: string }>(\n `SELECT instance_id FROM ${this.t.entry} WHERE user_id = $1 AND status = 'running'`,\n [userId]\n );\n return rows.map((row) => row.instance_id);\n }\n\n async forgetUser(userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n // Children before the copies they belong to\n for (const child of [this.t.messageOpen, this.t.messageClick, this.t.messageLink]) {\n await tx.query(\n `DELETE FROM ${child} WHERE message_id IN (SELECT id FROM ${this.t.message} WHERE user_id = $1)`,\n [userId]\n );\n }\n for (const table of [\n this.t.message,\n this.t.instance,\n this.t.entry,\n this.t.execution,\n this.t.subscription,\n this.t.segmentStart,\n this.t.segmentMember,\n this.t.suppression,\n this.t.device,\n this.t.event,\n this.t.profile,\n // The request goes with the data it asked to erase\n this.t.erasure,\n ]) {\n await tx.query(`DELETE FROM ${table} WHERE user_id = $1`, [userId]);\n }\n });\n }\n\n async isSuppressed(userId: string, channel: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.suppression} WHERE user_id = $1 AND channel = $2`,\n [userId, channel]\n );\n return rows.length > 0;\n }\n\n async removeDevice(token: string): Promise<string | undefined> {\n const rows = await this.sql.query<{ user_id: string | null }>(\n `DELETE FROM ${this.t.device} WHERE token = $1 RETURNING user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async unbindDevice(token: string): Promise<string | undefined> {\n // The owner as it was before the update: RETURNING alone would only show the null\n const rows = await this.sql.query<{ user_id: string | null }>(\n `WITH old AS (SELECT token, user_id FROM ${this.t.device} WHERE token = $1 FOR UPDATE)\n UPDATE ${this.t.device} d SET user_id = NULL FROM old WHERE d.token = old.token\n RETURNING old.user_id`,\n [token]\n );\n return rows[0]?.user_id ?? undefined;\n }\n\n async listSegments(): Promise<{ id: string; condition: ConditionIR }[]> {\n const rows = await this.sql.query<{ id: string; condition: unknown }>(\n `SELECT id, condition FROM ${this.t.segment} ORDER BY id`\n );\n return rows.map((row) => ({\n id: row.id,\n condition: ConditionIR.parse(asJson(row.condition)),\n }));\n }\n\n async getSegmentCondition(id: string): Promise<ConditionIR | undefined> {\n const rows = await this.sql.query<{ condition: unknown }>(\n `SELECT condition FROM ${this.t.segment} WHERE id = $1`,\n [id]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : ConditionIR.parse(asJson(row.condition));\n }\n\n async findTriggers(event: string): Promise<TriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n where_clause: unknown;\n filter: unknown;\n version: string | null;\n }>(\n `SELECT workflow, hash, \"where\" AS where_clause, filter, version FROM ${this.t.trigger} WHERE event = $1`,\n [event]\n );\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n where: row.where_clause === null ? null : ConditionIR.parse(asJson(row.where_clause)),\n filter: row.filter === null ? null : ConditionIR.parse(asJson(row.filter)),\n version: row.version ?? undefined,\n }));\n }\n\n async listSegmentTriggers(): Promise<SegmentTriggerRoute[]> {\n const rows = await this.sql.query<{\n workflow: string;\n hash: string;\n segment: string;\n version: string | null;\n }>(`SELECT workflow, hash, segment, version FROM ${this.t.segmentTrigger}`);\n return rows.map((row) => ({\n workflow: row.workflow,\n hash: row.hash,\n segment: row.segment,\n version: row.version ?? undefined,\n }));\n }\n\n async putWorkflowIR(workflow: WorkflowIR): Promise<void> {\n await this.sql.query(\n `INSERT INTO ${this.t.ir} (content_hash, ir) VALUES ($1, $2::text::jsonb)\n ON CONFLICT (content_hash) DO UPDATE SET ir = EXCLUDED.ir`,\n [workflow.contentHash, JSON.stringify(workflow)]\n );\n }\n\n async getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined> {\n const rows = await this.sql.query<{ ir: unknown }>(\n `SELECT ir FROM ${this.t.ir} WHERE content_hash = $1`,\n [contentHash]\n );\n const row = rows.at(0);\n return row === undefined ? undefined : WorkflowIR.parse(asJson(row.ir));\n }\n\n replaceRoutes(bundle: BundleIR): Promise<void> {\n return this.sql.transaction((tx) => this.swapRoutes(tx, bundle));\n }\n\n async liveBundleVersion(): Promise<BundleVersion | undefined> {\n // In a transaction, so Hyperdrive answers from the database, not from its read cache\n const rows = await this.sql.transaction((tx) =>\n tx.query<{ version_id: string; created_at: number | string }>(\n `SELECT version_id, (extract(epoch FROM version_created_at) * 1000)::double precision AS created_at\n FROM ${this.t.deployment} WHERE scope = 'routes'`\n )\n );\n const row = rows.at(0);\n return row === undefined\n ? undefined\n : { id: row.version_id, createdAt: Number(row.created_at) };\n }\n\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean> {\n return this.sql.transaction(async (tx) => {\n // The row lock decides between versions applying at once: the loser's WHERE re-reads the\n // winner's committed row and updates nothing\n const claimed = await tx.query(\n `INSERT INTO ${this.t.deployment} AS live (scope, version_id, version_created_at, applied_at)\n VALUES ('routes', $1, ${TS('$2')}, ${TS('$3')})\n ON CONFLICT (scope) DO UPDATE SET version_id = EXCLUDED.version_id,\n version_created_at = EXCLUDED.version_created_at, applied_at = EXCLUDED.applied_at\n WHERE live.version_created_at < EXCLUDED.version_created_at\n RETURNING scope`,\n [version.id, version.createdAt, Date.now()]\n );\n if (claimed.length === 0) return false;\n await this.swapRoutes(tx, bundle, version.id);\n return true;\n });\n }\n\n /** `version`: the code version applying the bundle, kept on every route it writes. */\n private async swapRoutes(tx: SqlClientLike, bundle: BundleIR, version?: string): Promise<void> {\n await tx.query(`DELETE FROM ${this.t.trigger}`);\n await tx.query(`DELETE FROM ${this.t.segmentTrigger}`);\n await tx.query(`DELETE FROM ${this.t.segment}`);\n for (const segment of bundle.segments) {\n await tx.query(\n `INSERT INTO ${this.t.segment} (id, condition, hash) VALUES ($1, $2::text::jsonb, $3)`,\n [segment.id, JSON.stringify(segment.condition), segment.contentHash]\n );\n }\n for (const workflow of bundle.workflows) {\n if (workflow.trigger.type === 'event') {\n await tx.query(\n `INSERT INTO ${this.t.trigger} (workflow, hash, event, \"where\", filter, version) VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6)`,\n [\n workflow.id,\n workflow.contentHash,\n workflow.trigger.event,\n workflow.trigger.where === undefined ? null : JSON.stringify(workflow.trigger.where),\n workflow.trigger.filter === undefined ? null : JSON.stringify(workflow.trigger.filter),\n version ?? null,\n ]\n );\n } else if (workflow.trigger.type === 'segment') {\n await tx.query(\n `INSERT INTO ${this.t.segmentTrigger} (workflow, hash, segment, version) VALUES ($1, $2, $3, $4)`,\n [workflow.id, workflow.contentHash, workflow.trigger.segment, version ?? null]\n );\n }\n }\n }\n\n async isSegmentMember(segment: string, userId: string): Promise<boolean> {\n const rows = await this.sql.query(\n `SELECT 1 AS x FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.length > 0;\n }\n\n async addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(\n `INSERT INTO ${this.t.segmentMember} (segment, user_id, ts) VALUES ($1, $2, ${TS('$3')}) ON CONFLICT DO NOTHING`,\n [segment, userId, ts]\n );\n for (const workflow of workflows) {\n await tx.query(\n `INSERT INTO ${this.t.segmentStart} (segment, workflow, user_id, ts)\n VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [segment, workflow, userId, ts]\n );\n }\n });\n }\n\n async pendingSegmentStarts(segment: string, userId: string): Promise<string[]> {\n const rows = await this.sql.query<{ workflow: string }>(\n `SELECT workflow FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`,\n [segment, userId]\n );\n return rows.map((row) => row.workflow);\n }\n\n async completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void> {\n await this.sql.query(\n `DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2 AND workflow = $3`,\n [segment, userId, workflow]\n );\n }\n\n async removeSegmentMember(segment: string, userId: string): Promise<void> {\n await this.sql.transaction(async (tx) => {\n await tx.query(`DELETE FROM ${this.t.segmentStart} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n await tx.query(`DELETE FROM ${this.t.segmentMember} WHERE segment = $1 AND user_id = $2`, [\n segment,\n userId,\n ]);\n });\n }\n\n async enterJourney(entry: EntryInput): Promise<EntryOutcome> {\n const { execution } = entry;\n if (execution === undefined) return this.claimEntry(this.sql, entry);\n // The entry and the start it owes commit together: a crash between them would leave a\n // running entry no retry could ever start\n return this.sql.transaction(async (tx) => {\n const outcome = await this.claimEntry(tx, entry);\n if (outcome !== null) await this.recordStart(tx, entry, execution);\n return outcome;\n });\n }\n\n private async claimEntry(sql: SqlClientLike, entry: EntryInput): Promise<EntryOutcome> {\n // The (workflow, user_id) primary key makes the once policy atomic:\n // concurrent ingests race on the insert and exactly one wins.\n const inserted = await sql.query(\n `INSERT INTO ${this.t.entry} (workflow, user_id, instance_id, hash, status, ts)\n VALUES ($1, $2, $3, $4, 'running', ${TS('$5')})\n ON CONFLICT (workflow, user_id) DO NOTHING RETURNING instance_id`,\n [entry.workflow, entry.userId, entry.instanceId, entry.hash, entry.ts]\n );\n if (inserted.length > 0) return 'entered';\n\n // An existing row blocks the entry unless it records an instance that died:\n // 'failed' is reclaimed rather than barring the user forever over one\n // outage. The status test is inside the UPDATE, so of two concurrent\n // retries exactly one gets a row back.\n const claimed = await sql.query(\n `UPDATE ${this.t.entry} SET instance_id = $1, hash = $2, status = 'running', ts = ${TS('$3')}\n WHERE workflow = $4 AND user_id = $5 AND status = 'failed' RETURNING instance_id`,\n [entry.instanceId, entry.hash, entry.ts, entry.workflow, entry.userId]\n );\n return claimed.length > 0 ? 'reclaimed' : null;\n }\n\n /**\n * Only an entry this call claimed records a start, so a row already there is a previous\n * attempt's — a failed entry reclaimed under the same instance id (an event replayed with its\n * ts). It is replaced whole: the new attempt's name and payload, nothing submitted yet.\n */\n private async recordStart(\n tx: SqlClientLike,\n entry: EntryInput,\n execution: ExecutionStart\n ): Promise<void> {\n await tx.query(\n `INSERT INTO ${this.t.execution} (instance_id, workflow, user_id, name, target, input, created_at, generation)\n VALUES ($1, $2, $3, $4, $5, $6, ${TS('$7')}, 0)\n ON CONFLICT (instance_id) DO UPDATE SET\n name = EXCLUDED.name, target = EXCLUDED.target, input = EXCLUDED.input,\n created_at = EXCLUDED.created_at, generation = 0, submitted_at = NULL, arn = NULL,\n unresolved_at = NULL, callback_id = NULL, deadline_at = NULL, checked_at = NULL,\n stopped_at = NULL`,\n [\n entry.instanceId,\n entry.workflow,\n entry.userId,\n execution.name,\n execution.target,\n execution.input,\n // The start's own age (the retry budget), not the event's ts, which the producer chose\n Date.now(),\n ]\n );\n }\n\n async removeEntry(instanceId: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.entry} WHERE instance_id = $1`, [instanceId]);\n }\n\n async setEntryStatus(instanceId: string, status: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.t.entry} SET status = $1 WHERE instance_id = $2`, [\n status,\n instanceId,\n ]);\n }\n\n async findWakeHandles(userId: string, event: string): Promise<string[]> {\n const rows = await this.sql.query<{ handle: string }>(\n `SELECT DISTINCT wake_handle AS handle FROM ${this.t.subscription} WHERE user_id = $1 AND event = $2`,\n [userId, event]\n );\n return rows.map((row) => row.handle);\n }\n\n async subscribe(\n handle: string,\n userId: string,\n events: readonly string[],\n ts: number\n ): Promise<void> {\n for (const event of events) {\n await this.sql.query(\n `INSERT INTO ${this.t.subscription} (user_id, event, wake_handle, ts) VALUES ($1, $2, $3, ${TS('$4')}) ON CONFLICT DO NOTHING`,\n [userId, event, handle, ts]\n );\n }\n }\n\n async unsubscribe(handle: string): Promise<void> {\n await this.sql.query(`DELETE FROM ${this.t.subscription} WHERE wake_handle = $1`, [handle]);\n }\n}\n\ninterface ExecutionRow {\n instance_id: string;\n workflow: string;\n user_id: string;\n name: string;\n target: string;\n input: string;\n // float8 comes back as a number from most drivers, as a string from some\n created_at: number | string;\n submitted_at: number | string | null;\n arn: string | null;\n unresolved_at: number | string | null;\n callback_id: string | null;\n generation: number | string;\n deadline_at: number | string | null;\n checked_at: number | string | null;\n stopped_at: number | string | null;\n}\n\nconst PLAIN_COLUMNS = ['instance_id', 'workflow', 'user_id', 'name', 'target', 'input', 'arn'];\nconst MORE_PLAIN = ['callback_id', 'generation'];\nconst TIME_COLUMNS = [\n 'created_at',\n 'submitted_at',\n 'unresolved_at',\n 'deadline_at',\n 'checked_at',\n 'stopped_at',\n];\n\n/** The execution columns, timestamps as epoch ms; `alias` qualifies them in a join. */\nfunction executionColumns(alias = ''): string {\n const q = alias === '' ? '' : `${alias}.`;\n return [\n ...[...PLAIN_COLUMNS, ...MORE_PLAIN].map((column) => `${q}${column}`),\n ...TIME_COLUMNS.map(\n (column) => `(extract(epoch from ${q}${column}) * 1000)::double precision AS ${column}`\n ),\n ].join(', ');\n}\n\nconst optional = <T>(value: T | null): T | undefined => value ?? undefined;\nconst ms = (value: number | string | null): number | undefined =>\n value === null ? undefined : Number(value);\n\nfunction toRecord(row: ExecutionRow): ExecutionRecord {\n return {\n instanceId: row.instance_id,\n workflow: row.workflow,\n userId: row.user_id,\n name: row.name,\n target: row.target,\n input: row.input,\n createdAt: Number(row.created_at),\n submittedAt: ms(row.submitted_at),\n arn: optional(row.arn),\n unresolvedAt: ms(row.unresolved_at),\n callbackId: optional(row.callback_id),\n generation: Number(row.generation),\n deadlineAt: ms(row.deadline_at),\n checkedAt: ms(row.checked_at),\n stoppedAt: ms(row.stopped_at),\n };\n}\n\n/** The execution table (tables.ts): starts to confirm, and the callback each wait parks on. */\nclass PostgresExecutions implements ExecutionRegistry {\n constructor(\n private readonly sql: SqlClientLike,\n private readonly table: string,\n private readonly entry: string\n ) {}\n\n async get(instanceId: string): Promise<ExecutionRecord | undefined> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns()} FROM ${this.table} WHERE instance_id = $1`,\n [instanceId]\n );\n return rows.length === 0 ? undefined : toRecord(rows[0]);\n }\n\n async pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]> {\n const where = ['x.submitted_at IS NULL', 'x.unresolved_at IS NULL', \"e.status = 'running'\"];\n const params: unknown[] = [];\n if (filter.workflow !== undefined) {\n params.push(filter.workflow);\n where.push(`x.workflow = $${params.length}`);\n }\n if (filter.userId !== undefined) {\n params.push(filter.userId);\n where.push(`x.user_id = $${params.length}`);\n }\n if (filter.createdBefore !== undefined) {\n params.push(filter.createdBefore);\n where.push(`x.created_at < ${TS(`$${params.length}`)}`);\n }\n params.push(filter.limit);\n // Only the start the entry still names: a reclaimed entry's old start is history\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE ${where.join(' AND ')} ORDER BY x.created_at LIMIT $${params.length}`,\n params\n );\n return rows.map(toRecord);\n }\n\n async markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET submitted_at = COALESCE(submitted_at, ${TS('$2')}), arn = COALESCE($3, arn) WHERE instance_id = $1`,\n [instanceId, at, arn ?? null]\n );\n }\n\n async markUnresolved(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET unresolved_at = ${TS('$2')} WHERE instance_id = $1 AND submitted_at IS NULL`,\n [instanceId, at]\n );\n }\n\n async setArn(instanceId: string, arn: string): Promise<void> {\n await this.sql.query(`UPDATE ${this.table} SET arn = $2 WHERE instance_id = $1`, [\n instanceId,\n arn,\n ]);\n }\n\n async armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean> {\n // The generation test is inside the UPDATE: a retried arm of an older wait cannot overwrite\n // the callback a newer one parks on\n const rows = await this.sql.query(\n `UPDATE ${this.table} SET callback_id = $2, generation = $3,\n deadline_at = CASE WHEN $4::double precision IS NULL THEN NULL ELSE ${TS('$4')} END\n WHERE instance_id = $1 AND generation <= $3 RETURNING instance_id`,\n [instanceId, callback.id, callback.generation, callback.deadlineAt ?? null]\n );\n return rows.length > 0;\n }\n\n async clearCallback(instanceId: string, generation: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET callback_id = NULL, deadline_at = NULL WHERE instance_id = $1 AND generation = $2`,\n [instanceId, generation]\n );\n }\n\n async toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]> {\n const rows = await this.sql.query<ExecutionRow>(\n `SELECT ${executionColumns('x')}\n FROM ${this.table} x JOIN ${this.entry} e ON e.instance_id = x.instance_id\n WHERE e.status = 'running' AND x.submitted_at IS NOT NULL\n AND (x.checked_at IS NULL OR x.checked_at < ${TS('$1')})\n ORDER BY x.checked_at NULLS FIRST LIMIT $2`,\n [checkedBefore, limit]\n );\n return rows.map(toRecord);\n }\n\n async markStopped(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET stopped_at = COALESCE(stopped_at, ${TS('$2')}) WHERE instance_id = $1`,\n [instanceId, at]\n );\n }\n\n async markChecked(instanceId: string, at: number): Promise<void> {\n await this.sql.query(\n `UPDATE ${this.table} SET checked_at = ${TS('$2')} WHERE instance_id = $1`,\n [instanceId, at]\n );\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,MAAkC;CACtC,MAAM;CACN,MAAM;CACN,OAAO;CACP,aAAa;CACb,SAAS;CACT,SAAS;AACX;;AAGA,MAAM,MAAM,UAAkB,gBAAgB,MAAM;AAEpD,SAAS,OAAU,OAAmB;CACpC,OAAQ,OAAO,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;AAC1D;;;;;;;;AASA,IAAa,uBAAb,MAA0D;CAOrC;CANnB;CACA;CACA;CACA;CAEA,YACE,KACA,UAAuC,CAAC,GACxC;EAFiB,KAAA,MAAA;EAGjB,KAAK,SAAS,QAAQ,UAAA;EACtB,MAAM,WAAW,SAAiB,IAAI,KAAK,OAAO,KAAK,KAAK;EAC5D,KAAK,IAAI,OAAO,YACb,OAAO,KAAK,MAAM,CAAC,CAAgB,KAAK,QAAQ,CAAC,KAAK,QAAQ,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CACnF;EACA,KAAK,YAAY,IAAI,kBAAkB,KAAK,KAAK,CAAC;EAClD,KAAK,aAAa,IAAI,mBAAmB,KAAK,KAAK,EAAE,WAAW,KAAK,EAAE,KAAK;CAC9E;;;;;;;CAQA,MA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