Skip to content

Commit 6264b27

Browse files
hastyyTrigger.dev RepoOps
authored andcommitted
feat(webapp): optional background checks for finished deployments
Adds an optional, off-by-default hook that lets a configured provider run background checks on deployments after they finish. Nothing changes unless a provider is configured. Mono-RevId: faf84343bb37bd864c1db681c84e04e6054ee501
1 parent e7c7240 commit 6264b27

10 files changed

Lines changed: 892 additions & 0 deletions

‎apps/webapp/app/env.server.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2084,6 +2084,16 @@ const EnvironmentSchema = z
20842084
ALERTS_WORKER_REDIS_TLS_DISABLED: z.string().default(process.env.REDIS_TLS_DISABLED ?? "false"),
20852085
ALERTS_WORKER_REDIS_CLUSTER_MODE_ENABLED: z.string().default("0"),
20862086

2087+
// Uses the common worker's Redis under its own key prefix.
2088+
DEPLOYMENT_CHECKS_WORKER_ENABLED: z.string().default(process.env.WORKER_ENABLED ?? "true"),
2089+
DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_WORKERS: z.coerce.number().int().default(1),
2090+
DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_TASKS_PER_WORKER: z.coerce.number().int().default(5),
2091+
DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_LIMIT: z.coerce.number().int().default(5),
2092+
DEPLOYMENT_CHECKS_WORKER_SHUTDOWN_TIMEOUT_MS: z.coerce.number().int().default(300_000),
2093+
DEPLOYMENT_CHECKS_WORKER_LOG_LEVEL: z
2094+
.enum(["log", "error", "warn", "info", "debug"])
2095+
.default("info"),
2096+
20872097
ALERT_ENGINE_WORKER_ENABLED: z.string().default(process.env.WORKER_ENABLED ?? "true"),
20882098
ALERT_ENGINE_WORKER_CONCURRENCY_WORKERS: z.coerce.number().int().default(1),
20892099
ALERT_ENGINE_WORKER_CONCURRENCY_TASKS_PER_WORKER: z.coerce.number().int().default(10),

‎apps/webapp/app/routes/healthcheck.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { getAdminAuditController } from "~/services/adminAudit/adminAudit.server
66
import { getExternalOidcController } from "~/services/oidc/externalOidc.server";
77
import { getSecurityNoticesController } from "~/services/securityNotices.server";
88
import { getDeploymentAccessController } from "~/v3/deploymentAccess.server";
9+
import { getDeploymentChecksController } from "~/v3/deploymentChecks.server";
910
import { isOtlpWorkerPoolHealthy } from "~/v3/otlpWorkerPool.server";
1011

1112
export const loader: LoaderFunction = async ({ request }) => {
@@ -21,6 +22,7 @@ export const loader: LoaderFunction = async ({ request }) => {
2122
await getAdminAuditController();
2223
await getSecurityNoticesController();
2324
await getDeploymentAccessController();
25+
await getDeploymentChecksController();
2426

2527
if (env.OTEL_TRANSFORM_WORKER_POOL_ENABLED && !isOtlpWorkerPoolHealthy()) {
2628
console.log("healthcheck ❌ otlp worker pool has no alive workers");
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
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+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { env } from "~/env.server";
2+
import { singleton } from "~/utils/singleton";
3+
import { createDeploymentChecksWorker, enqueueDeploymentCheck } from "./deploymentChecks.server";
4+
5+
function initializeWorker() {
6+
const worker = createDeploymentChecksWorker({
7+
redisOptions: {
8+
keyPrefix: "deployment-checks:worker:",
9+
host: env.COMMON_WORKER_REDIS_HOST,
10+
port: env.COMMON_WORKER_REDIS_PORT,
11+
username: env.COMMON_WORKER_REDIS_USERNAME,
12+
password: env.COMMON_WORKER_REDIS_PASSWORD,
13+
enableAutoPipelining: true,
14+
...(env.COMMON_WORKER_REDIS_TLS_DISABLED === "true" ? {} : { tls: {} }),
15+
},
16+
concurrency: {
17+
workers: env.DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_WORKERS,
18+
tasksPerWorker: env.DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_TASKS_PER_WORKER,
19+
limit: env.DEPLOYMENT_CHECKS_WORKER_CONCURRENCY_LIMIT,
20+
},
21+
shutdownTimeoutMs: env.DEPLOYMENT_CHECKS_WORKER_SHUTDOWN_TIMEOUT_MS,
22+
logLevel: env.DEPLOYMENT_CHECKS_WORKER_LOG_LEVEL,
23+
});
24+
25+
if (env.DEPLOYMENT_CHECKS_WORKER_ENABLED === "true") {
26+
worker.start();
27+
}
28+
29+
return worker;
30+
}
31+
32+
const deploymentChecksWorker = singleton("deploymentChecksWorker", initializeWorker);
33+
34+
/** Queues the check for a finished deployment. Never throws. */
35+
export function queueDeploymentCheck(deploymentId: string): Promise<void> {
36+
return enqueueDeploymentCheck(deploymentChecksWorker, deploymentId);
37+
}

0 commit comments

Comments
 (0)