|
| 1 | +#!/usr/bin/env tsx |
| 2 | +/** Explicit internal operator entry point. Never imported by webapp/server startup. */ |
| 3 | +import { createHash } from "node:crypto"; |
| 4 | +import { readFile, open } from "node:fs/promises"; |
| 5 | +import { parseArgs } from "node:util"; |
| 6 | +import { PrismaClient } from "@trigger.dev/database"; |
| 7 | +import runOpsDatabase from "@internal/run-ops-database"; |
| 8 | +import { resolveShard } from "@trigger.dev/core/v3/isomorphic"; |
| 9 | +import { PostgresRunStore, RoutingRunStore, type RunStore } from "@internal/run-store"; |
| 10 | +import { Redis, type RedisClient, createRedisClusterClient } from "@internal/redis"; |
| 11 | +import { z } from "zod"; |
| 12 | +import { |
| 13 | + ManualWaitpointRollbackRecovery, |
| 14 | + rollbackScopeSchema, |
| 15 | + rollbackPlanSchema, |
| 16 | + recoveryOperationSchema, |
| 17 | +} from "../src/engine/waitpointCoordinator/manualRollbackRecovery.js"; |
| 18 | +import { WaitpointStoreCoordinator } from "../src/engine/waitpointCoordinator/storeCoordinator.js"; |
| 19 | + |
| 20 | +const { RunOpsPrismaClient } = runOpsDatabase; |
| 21 | + |
| 22 | +const configSchema = z |
| 23 | + .object({ |
| 24 | + deployment: z.string().min(1), |
| 25 | + controlPlaneUrlEnv: z.string(), |
| 26 | + redisUrlEnv: z.string(), |
| 27 | + redisCluster: z.boolean().default(true), |
| 28 | + // Must match the deployed read topology, even while creation/split flags are off. |
| 29 | + runStores: z.discriminatedUnion("mode", [ |
| 30 | + z.object({ mode: z.literal("single"), urlEnv: z.string() }).strict(), |
| 31 | + z |
| 32 | + .object({ |
| 33 | + mode: z.literal("routed"), |
| 34 | + legacyUrlEnv: z.string(), |
| 35 | + newUrlEnv: z.string(), |
| 36 | + shards: z |
| 37 | + .array( |
| 38 | + z |
| 39 | + .object({ |
| 40 | + key: z.string(), |
| 41 | + urlEnv: z.string().optional(), |
| 42 | + aliasOf: z.literal("new").optional(), |
| 43 | + }) |
| 44 | + .strict() |
| 45 | + ) |
| 46 | + .max(64) |
| 47 | + .default([]), |
| 48 | + }) |
| 49 | + .strict(), |
| 50 | + ]), |
| 51 | + }) |
| 52 | + .strict(); |
| 53 | + |
| 54 | +async function main() { |
| 55 | + const { values } = parseArgs({ |
| 56 | + options: { |
| 57 | + config: { type: "string" }, |
| 58 | + scope: { type: "string" }, |
| 59 | + discover: { type: "string" }, |
| 60 | + source: { type: "string", multiple: true }, |
| 61 | + operation: { type: "string" }, |
| 62 | + plan: { type: "string" }, |
| 63 | + out: { type: "string" }, |
| 64 | + apply: { type: "boolean", default: false }, |
| 65 | + verify: { type: "boolean", default: false }, |
| 66 | + run: { type: "string", multiple: true }, |
| 67 | + "confirm-maintenance-window": { type: "boolean", default: false }, |
| 68 | + }, |
| 69 | + }); |
| 70 | + if (!values.out) |
| 71 | + throw new Error("An exclusive report output path is required: --out report.json"); |
| 72 | + const output = await open(values.out, "wx", 0o600); |
| 73 | + const clients: Array<PrismaClient | InstanceType<typeof RunOpsPrismaClient>> = []; |
| 74 | + const secrets: string[] = []; |
| 75 | + let redis: RedisClient | undefined; |
| 76 | + let stage = "preflight"; |
| 77 | + let report: unknown; |
| 78 | + try { |
| 79 | + try { |
| 80 | + if ( |
| 81 | + !values.config || |
| 82 | + (values.apply && values.verify) || |
| 83 | + ((values.apply || values.verify || values.discover) && !!values.operation) || |
| 84 | + (values.apply || values.verify |
| 85 | + ? !values.plan || !!values.scope || !!values.discover |
| 86 | + : (!values.scope && !values.discover) || |
| 87 | + (!!values.scope && !!values.discover) || |
| 88 | + !!values.plan) |
| 89 | + ) { |
| 90 | + throw new Error( |
| 91 | + "Usage: --config topology.json --out report.json (--scope scope.json [--operation rollback|contributions-only] | --discover cursor.json | --plan plan.json --verify | --plan plan.json --apply [--run RUN_ID] [--source SOURCE_ID] --confirm-maintenance-window)" |
| 92 | + ); |
| 93 | + } |
| 94 | + const config = configSchema.parse(JSON.parse(await readFile(values.config!, "utf8"))); |
| 95 | + const url = (name: string) => { |
| 96 | + const value = process.env[name]; |
| 97 | + if (!value) throw new Error(`Missing connection environment variable ${name}`); |
| 98 | + secrets.push(value); |
| 99 | + return value; |
| 100 | + }; |
| 101 | + const controlPlane = new PrismaClient({ |
| 102 | + datasources: { db: { url: url(config.controlPlaneUrlEnv) } }, |
| 103 | + }); |
| 104 | + clients.push(controlPlane); |
| 105 | + const leaf = (endpoint: string, dedicated: boolean): RunStore => { |
| 106 | + const client = dedicated |
| 107 | + ? new RunOpsPrismaClient({ datasources: { db: { url: url(endpoint) } } }) |
| 108 | + : new PrismaClient({ datasources: { db: { url: url(endpoint) } } }); |
| 109 | + clients.push(client); |
| 110 | + return new PostgresRunStore({ |
| 111 | + prisma: client, |
| 112 | + readOnlyPrisma: client, |
| 113 | + schemaVariant: dedicated ? "dedicated" : "legacy", |
| 114 | + }); |
| 115 | + }; |
| 116 | + let runStore: RunStore; |
| 117 | + const topology = config.runStores; |
| 118 | + if (topology.mode === "single") runStore = leaf(topology.urlEnv, false); |
| 119 | + else { |
| 120 | + const next = leaf(topology.newUrlEnv, true); |
| 121 | + runStore = new RoutingRunStore({ |
| 122 | + new: next, |
| 123 | + legacy: leaf(topology.legacyUrlEnv, false), |
| 124 | + shards: topology.shards.map((shard) => { |
| 125 | + if (shard.aliasOf) { |
| 126 | + if (shard.urlEnv) throw new Error("Aliased shard must not supply another database"); |
| 127 | + return { key: shard.key, store: next, aliasOf: shard.aliasOf }; |
| 128 | + } |
| 129 | + if (!shard.urlEnv) throw new Error("Shard needs urlEnv or aliasOf"); |
| 130 | + return { key: shard.key, store: leaf(shard.urlEnv, true) }; |
| 131 | + }), |
| 132 | + }); |
| 133 | + } |
| 134 | + const redisUrl = url(config.redisUrlEnv); |
| 135 | + if (config.redisCluster) { |
| 136 | + const endpoint = new URL(redisUrl); |
| 137 | + if ( |
| 138 | + !["redis:", "rediss:"].includes(endpoint.protocol) || |
| 139 | + !["", "/", "/0"].includes(endpoint.pathname) || |
| 140 | + endpoint.search || |
| 141 | + endpoint.hash |
| 142 | + ) |
| 143 | + throw new Error("Invalid cluster endpoint"); |
| 144 | + redis = createRedisClusterClient({ |
| 145 | + nodes: [{ host: endpoint.hostname, port: Number(endpoint.port || 6379) }], |
| 146 | + clusterOptions: { scaleReads: "master" }, |
| 147 | + redisOptions: { |
| 148 | + username: endpoint.username ? decodeURIComponent(endpoint.username) : undefined, |
| 149 | + password: endpoint.password ? decodeURIComponent(endpoint.password) : undefined, |
| 150 | + tls: endpoint.protocol === "rediss:" ? { servername: endpoint.hostname } : undefined, |
| 151 | + maxRetriesPerRequest: 1, |
| 152 | + commandTimeout: 5000, |
| 153 | + connectTimeout: 5000, |
| 154 | + }, |
| 155 | + }); |
| 156 | + } else redis = new Redis(redisUrl, { maxRetriesPerRequest: 1, commandTimeout: 5000 }); |
| 157 | + const target = createHash("sha256") |
| 158 | + .update(JSON.stringify(config)) |
| 159 | + .update(JSON.stringify(secrets)) |
| 160 | + .digest("hex"); |
| 161 | + const store = new WaitpointStoreCoordinator({ client: redis }); |
| 162 | + const recovery = new ManualWaitpointRollbackRecovery({ |
| 163 | + target, |
| 164 | + controlPlane, |
| 165 | + runStore, |
| 166 | + assertRunId: |
| 167 | + topology.mode === "single" |
| 168 | + ? (runId) => { |
| 169 | + if (resolveShard(runId) !== "legacy") |
| 170 | + throw new Error( |
| 171 | + "Single legacy topology cannot read a dedicated-store run; configure routed topology" |
| 172 | + ); |
| 173 | + } |
| 174 | + : undefined, |
| 175 | + redis, |
| 176 | + store, |
| 177 | + }); |
| 178 | + if (values.apply || values.verify) { |
| 179 | + const plan = rollbackPlanSchema.parse(JSON.parse(await readFile(values.plan!, "utf8"))); |
| 180 | + stage = values.apply ? "apply" : "verification"; |
| 181 | + report = values.apply |
| 182 | + ? await recovery.apply( |
| 183 | + plan, |
| 184 | + values.run ?? [], |
| 185 | + values["confirm-maintenance-window"], |
| 186 | + values.source ?? [] |
| 187 | + ) |
| 188 | + : await recovery.verify(plan); |
| 189 | + } else if (values.discover) { |
| 190 | + const discovery = z |
| 191 | + .object({ |
| 192 | + organizationId: z.string(), |
| 193 | + kind: z.enum(["runs", "pending-sources", "due", "quarantine"]), |
| 194 | + partition: z.number().int().min(0).max(15), |
| 195 | + after: z.object({ score: z.string(), member: z.string() }).strict().optional(), |
| 196 | + }) |
| 197 | + .strict() |
| 198 | + .parse(JSON.parse(await readFile(values.discover, "utf8"))); |
| 199 | + stage = "discovery"; |
| 200 | + report = await recovery.discover(discovery); |
| 201 | + } else { |
| 202 | + const scope = rollbackScopeSchema.parse(JSON.parse(await readFile(values.scope!, "utf8"))); |
| 203 | + const operation = recoveryOperationSchema.parse(values.operation ?? "rollback"); |
| 204 | + stage = "inspection"; |
| 205 | + report = await recovery.inspect(scope, operation); |
| 206 | + } |
| 207 | + } catch (error) { |
| 208 | + let message = error instanceof Error ? error.message : String(error); |
| 209 | + for (const secret of secrets) message = message.split(secret).join("[redacted]"); |
| 210 | + report = { errors: [{ stage, error: message }] }; |
| 211 | + process.exitCode = 1; |
| 212 | + } |
| 213 | + await output.writeFile(JSON.stringify(report, null, 2) + "\n"); |
| 214 | + console.log( |
| 215 | + `Saved ${values.out}. Read the operation, coverage and unhandled list in the report.` |
| 216 | + ); |
| 217 | + if ( |
| 218 | + (report as { errors?: unknown[] }).errors?.length || |
| 219 | + (report as { results?: Array<{ verified: boolean }> }).results?.some( |
| 220 | + (result) => !result.verified |
| 221 | + ) || |
| 222 | + (report as { sources?: Array<{ verified: boolean }> }).sources?.some( |
| 223 | + (source) => !source.verified |
| 224 | + ) |
| 225 | + ) |
| 226 | + process.exitCode = 1; |
| 227 | + } finally { |
| 228 | + await output.close(); |
| 229 | + redis?.disconnect(); |
| 230 | + await Promise.all(clients.map((client) => client.$disconnect())); |
| 231 | + } |
| 232 | +} |
| 233 | +main().catch((error) => { |
| 234 | + console.error(error instanceof Error ? error.message : String(error)); |
| 235 | + process.exitCode = 1; |
| 236 | +}); |
0 commit comments