|
| 1 | +import { getMeter, type Meter } from "@internal/tracing"; |
| 2 | +import { Logger, type LogLevel } from "@trigger.dev/core/logger"; |
| 3 | +import type { |
| 4 | + DeploymentChecksController, |
| 5 | + DeploymentChecksPlugin, |
| 6 | + DeploymentChecksPluginConfig, |
| 7 | +} from "@trigger.dev/plugins"; |
| 8 | +import { Worker as RedisWorker } from "@trigger.dev/redis-worker"; |
| 9 | +import type { RedisOptions } from "ioredis"; |
| 10 | +import { z } from "zod"; |
| 11 | +import { prisma as defaultPrisma, type PrismaClientOrTransaction } from "~/db.server"; |
| 12 | +import { env } from "~/env.server"; |
| 13 | +import { logger } from "~/services/logger.server"; |
| 14 | +import { isCloud } from "~/services/platform.v3.server"; |
| 15 | +import { singleton } from "~/utils/singleton"; |
| 16 | +import { resolvePlanState } from "~/v3/freeSchedulePolicy.server"; |
| 17 | + |
| 18 | +const MODULE_NAME = "@triggerdotdev/plugins/deployment-checks"; |
| 19 | +const JOB = "deployments.check"; |
| 20 | +const MAX_ATTEMPTS = 5; |
| 21 | +// A missing or unconfigured plugin is looked for again after this long. |
| 22 | +const RELOAD_AFTER_MS = 5 * 60_000; |
| 23 | + |
| 24 | +export const deploymentCheckJob = { |
| 25 | + schema: z.object({ deploymentId: z.string() }), |
| 26 | + visibilityTimeoutMs: 10 * 60_000, |
| 27 | + retry: { |
| 28 | + maxAttempts: MAX_ATTEMPTS, |
| 29 | + minTimeoutInMs: 30_000, |
| 30 | + maxTimeoutInMs: 10 * 60_000, |
| 31 | + factor: 2, |
| 32 | + }, |
| 33 | +}; |
| 34 | + |
| 35 | +export function deploymentCheckTelemetry(meter: Meter) { |
| 36 | + return { |
| 37 | + decisions: meter.createCounter("deployment_checks.decisions_total", { |
| 38 | + description: "Deployment check decisions by mode, selection and outcome", |
| 39 | + }), |
| 40 | + duration: meter.createHistogram("deployment_checks.duration_ms", { |
| 41 | + description: "Deployment check duration", |
| 42 | + unit: "ms", |
| 43 | + }), |
| 44 | + pluginMissing: meter.createCounter("deployment_checks.plugin_missing_total", { |
| 45 | + description: "Times the deployment checks plugin did not load on Cloud", |
| 46 | + }), |
| 47 | + }; |
| 48 | +} |
| 49 | + |
| 50 | +type DeploymentCheckTelemetry = ReturnType<typeof deploymentCheckTelemetry>; |
| 51 | + |
| 52 | +const defaultTelemetry = singleton("deploymentCheckTelemetry", () => |
| 53 | + deploymentCheckTelemetry(getMeter("deployment-checks")) |
| 54 | +); |
| 55 | + |
| 56 | +/** What the plugin gets from the host. It reads its own settings with this database. */ |
| 57 | +function pluginConfig(): DeploymentChecksPluginConfig { |
| 58 | + return { |
| 59 | + // Small pools: one primary-key read per check, off the request path. They connect lazily, so |
| 60 | + // a process that never runs a check opens no connection. |
| 61 | + database: { |
| 62 | + writerUrl: env.CONTROL_PLANE_DATABASE_URL ?? env.DATABASE_URL, |
| 63 | + readerUrl: env.CONTROL_PLANE_DATABASE_READ_REPLICA_URL ?? env.DATABASE_READ_REPLICA_URL, |
| 64 | + writerConnectionLimit: 1, |
| 65 | + readerConnectionLimit: 1, |
| 66 | + }, |
| 67 | + billingStatus: resolvePlanState, |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Loads the plugin. Null when checks are off: not Cloud, no plugin, or the plugin isn't configured. |
| 73 | + * With REQUIRE_PLUGINS=1 a plugin that doesn't load throws, wherever the webapp runs. |
| 74 | + */ |
| 75 | +export async function loadDeploymentChecksController({ |
| 76 | + requirePlugins, |
| 77 | + cloud, |
| 78 | + moduleName = MODULE_NAME, |
| 79 | + telemetry = defaultTelemetry, |
| 80 | + config = pluginConfig, |
| 81 | +}: { |
| 82 | + requirePlugins: boolean; |
| 83 | + cloud: boolean; |
| 84 | + moduleName?: string; |
| 85 | + telemetry?: DeploymentCheckTelemetry; |
| 86 | + config?: () => DeploymentChecksPluginConfig; |
| 87 | +}): Promise<DeploymentChecksController | null> { |
| 88 | + if (!requirePlugins && !cloud) return null; |
| 89 | + |
| 90 | + let plugin: DeploymentChecksPlugin; |
| 91 | + try { |
| 92 | + plugin = ((await import(/* @vite-ignore */ moduleName)) as { default: DeploymentChecksPlugin }) |
| 93 | + .default; |
| 94 | + } catch (error) { |
| 95 | + if (requirePlugins) { |
| 96 | + throw new Error( |
| 97 | + `REQUIRE_PLUGINS=1 but plugin "${moduleName}" did not load: ${errorMessage(error)}`, |
| 98 | + { cause: error } |
| 99 | + ); |
| 100 | + } |
| 101 | + logger.warn("Deployment checks plugin did not load", { error: errorMessage(error) }); |
| 102 | + telemetry.pluginMissing.add(1); |
| 103 | + return null; |
| 104 | + } |
| 105 | + return plugin.create(config()); |
| 106 | +} |
| 107 | + |
| 108 | +type ControllerLoad = { |
| 109 | + promise: Promise<DeploymentChecksController | null>; |
| 110 | + at: number; |
| 111 | + /** Undefined while loading. */ |
| 112 | + result?: DeploymentChecksController | null; |
| 113 | +}; |
| 114 | + |
| 115 | +const controllerLoad = singleton("deploymentChecksControllerLoad", () => ({ |
| 116 | + current: undefined as ControllerLoad | undefined, |
| 117 | +})); |
| 118 | + |
| 119 | +/** |
| 120 | + * The loaded controller. Callers share one load, so a process creates one controller and one set |
| 121 | + * of database pools. A null result is looked for again after a while; a failed load isn't kept. |
| 122 | + */ |
| 123 | +export function getDeploymentChecksController(): Promise<DeploymentChecksController | null> { |
| 124 | + const current = controllerLoad.current; |
| 125 | + if (current && (current.result !== null || Date.now() - current.at < RELOAD_AFTER_MS)) { |
| 126 | + return current.promise; |
| 127 | + } |
| 128 | + const load: ControllerLoad = { |
| 129 | + at: Date.now(), |
| 130 | + promise: loadDeploymentChecksController({ |
| 131 | + requirePlugins: env.REQUIRE_PLUGINS === "1", |
| 132 | + cloud: isCloud(), |
| 133 | + }), |
| 134 | + }; |
| 135 | + controllerLoad.current = load; |
| 136 | + load.promise.then( |
| 137 | + (controller) => { |
| 138 | + load.result = controller; |
| 139 | + }, |
| 140 | + () => { |
| 141 | + if (controllerLoad.current === load) controllerLoad.current = undefined; |
| 142 | + } |
| 143 | + ); |
| 144 | + return load.promise; |
| 145 | +} |
| 146 | + |
| 147 | +type DeploymentCheckQueue = { |
| 148 | + enqueueOnce(options: { |
| 149 | + id: string; |
| 150 | + job: typeof JOB; |
| 151 | + payload: { deploymentId: string }; |
| 152 | + }): Promise<unknown>; |
| 153 | +}; |
| 154 | + |
| 155 | +/** |
| 156 | + * Queues one check per deployment: the job id is stable. Does nothing without the plugin. Never |
| 157 | + * throws. |
| 158 | + */ |
| 159 | +export async function enqueueDeploymentCheck( |
| 160 | + queue: DeploymentCheckQueue, |
| 161 | + deploymentId: string, |
| 162 | + controller: () => Promise<DeploymentChecksController | null> = getDeploymentChecksController |
| 163 | +): Promise<void> { |
| 164 | + try { |
| 165 | + if (!(await controller())) return; |
| 166 | + await queue.enqueueOnce({ |
| 167 | + id: `deploymentCheck:${deploymentId}`, |
| 168 | + job: JOB, |
| 169 | + payload: { deploymentId }, |
| 170 | + }); |
| 171 | + } catch (error) { |
| 172 | + logger.error("Failed to queue the deployment check", { |
| 173 | + deploymentId, |
| 174 | + error: errorMessage(error), |
| 175 | + }); |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +export function createDeploymentChecksWorker({ |
| 180 | + redisOptions, |
| 181 | + concurrency, |
| 182 | + shutdownTimeoutMs, |
| 183 | + pollIntervalMs, |
| 184 | + logLevel = "info", |
| 185 | + dependencies, |
| 186 | +}: { |
| 187 | + redisOptions: RedisOptions; |
| 188 | + concurrency: { workers: number; tasksPerWorker: number; limit: number }; |
| 189 | + shutdownTimeoutMs: number; |
| 190 | + pollIntervalMs?: number; |
| 191 | + logLevel?: LogLevel; |
| 192 | + dependencies?: DeploymentCheckJobDependencies; |
| 193 | +}) { |
| 194 | + return new RedisWorker({ |
| 195 | + name: "deployment-checks-worker", |
| 196 | + redisOptions, |
| 197 | + catalog: { [JOB]: deploymentCheckJob }, |
| 198 | + jobs: { |
| 199 | + [JOB]: async ({ payload, attempt }) => { |
| 200 | + await runDeploymentCheck({ deploymentId: payload.deploymentId, attempt }, dependencies); |
| 201 | + }, |
| 202 | + }, |
| 203 | + concurrency, |
| 204 | + shutdownTimeoutMs, |
| 205 | + pollIntervalMs, |
| 206 | + logger: new Logger("DeploymentChecksWorker", logLevel), |
| 207 | + }); |
| 208 | +} |
| 209 | + |
| 210 | +/** Thrown to retry the job later. The worker logs it at warn, not error. */ |
| 211 | +class DeploymentCheckRetryError extends Error { |
| 212 | + readonly logLevel = "warn"; |
| 213 | +} |
| 214 | + |
| 215 | +export type DeploymentCheckJobOutcome = |
| 216 | + | "no_plugin" |
| 217 | + | "not_found" |
| 218 | + | "skipped" |
| 219 | + | "pass" |
| 220 | + | "fail" |
| 221 | + | "unavailable"; |
| 222 | + |
| 223 | +export type DeploymentCheckJobDependencies = { |
| 224 | + prisma?: PrismaClientOrTransaction; |
| 225 | + /** Null means no plugin. Loaded when left out. */ |
| 226 | + controller?: DeploymentChecksController | null; |
| 227 | + telemetry?: DeploymentCheckTelemetry; |
| 228 | +}; |
| 229 | + |
| 230 | +/** |
| 231 | + * Runs the check for one deployment. It reads the deployment and never writes it: the outcome goes |
| 232 | + * to a log line and a metric. An unavailable answer that may change throws, so the worker retries |
| 233 | + * later; the last attempt records it instead. |
| 234 | + */ |
| 235 | +export async function runDeploymentCheck( |
| 236 | + { deploymentId, attempt }: { deploymentId: string; attempt: number }, |
| 237 | + { |
| 238 | + prisma = defaultPrisma, |
| 239 | + controller: injectedController, |
| 240 | + telemetry = defaultTelemetry, |
| 241 | + }: DeploymentCheckJobDependencies = {} |
| 242 | +): Promise<DeploymentCheckJobOutcome> { |
| 243 | + const controller = |
| 244 | + injectedController === undefined ? await getDeploymentChecksController() : injectedController; |
| 245 | + if (!controller) return "no_plugin"; |
| 246 | + |
| 247 | + const deployment = await prisma.workerDeployment.findFirst({ |
| 248 | + where: { id: deploymentId }, |
| 249 | + select: { |
| 250 | + id: true, |
| 251 | + friendlyId: true, |
| 252 | + imageReference: true, |
| 253 | + project: { select: { externalRef: true, organizationId: true } }, |
| 254 | + }, |
| 255 | + }); |
| 256 | + if (!deployment) { |
| 257 | + logger.warn("Deployment check skipped: deployment not found", { deploymentId }); |
| 258 | + return "not_found"; |
| 259 | + } |
| 260 | + |
| 261 | + const organizationId = deployment.project.organizationId; |
| 262 | + const decision = await controller.decide({ organizationId, deploymentId: deployment.id }); |
| 263 | + const log = { |
| 264 | + deploymentId: deployment.id, |
| 265 | + deploymentFriendlyId: deployment.friendlyId, |
| 266 | + organizationId, |
| 267 | + projectRef: deployment.project.externalRef, |
| 268 | + mode: decision.plan, |
| 269 | + selectedBy: decision.selectedBy, |
| 270 | + }; |
| 271 | + const finish = ( |
| 272 | + outcome: DeploymentCheckJobOutcome, |
| 273 | + details: Record<string, unknown> = {} |
| 274 | + ): DeploymentCheckJobOutcome => { |
| 275 | + telemetry.decisions.add(1, { |
| 276 | + mode: decision.plan, |
| 277 | + selected_by: decision.selectedBy, |
| 278 | + outcome, |
| 279 | + }); |
| 280 | + const line = { ...log, outcome, attempt, ...details }; |
| 281 | + if (outcome === "unavailable") logger.warn("deploymentChecks.result", line); |
| 282 | + else if (outcome === "skipped") logger.debug("deploymentChecks.result", line); |
| 283 | + else logger.info("deploymentChecks.result", line); |
| 284 | + return outcome; |
| 285 | + }; |
| 286 | + |
| 287 | + if (decision.plan === "skip") return finish("skipped"); |
| 288 | + |
| 289 | + const imageDigest = deployment.imageReference?.match(/@(sha256:[a-f0-9]{64})$/)?.[1]; |
| 290 | + if (!imageDigest) return finish("skipped"); |
| 291 | + |
| 292 | + const startedAt = performance.now(); |
| 293 | + const result = await controller.check({ |
| 294 | + organizationId, |
| 295 | + projectRef: deployment.project.externalRef, |
| 296 | + deploymentId: deployment.id, |
| 297 | + imageDigest, |
| 298 | + decision: { plan: decision.plan, selectedBy: decision.selectedBy }, |
| 299 | + }); |
| 300 | + const durationMs = Math.round(performance.now() - startedAt); |
| 301 | + telemetry.duration.record(durationMs, { mode: decision.plan, outcome: result.outcome }); |
| 302 | + |
| 303 | + const lastAttempt = attempt >= MAX_ATTEMPTS - 1; |
| 304 | + if (result.outcome === "unavailable" && result.retryable && !lastAttempt) { |
| 305 | + logger.info("Deployment check unavailable, retrying later", { |
| 306 | + ...log, |
| 307 | + checkId: result.id, |
| 308 | + attempt, |
| 309 | + durationMs, |
| 310 | + }); |
| 311 | + throw new DeploymentCheckRetryError("Deployment check unavailable, retrying later"); |
| 312 | + } |
| 313 | + |
| 314 | + return finish(result.outcome, { checkId: result.id, durationMs }); |
| 315 | +} |
| 316 | + |
| 317 | +function errorMessage(error: unknown): string { |
| 318 | + return error instanceof Error ? error.message : String(error); |
| 319 | +} |
0 commit comments