Skip to content

Commit 505b91e

Browse files
committed
fix(notifications): integrate PR #868 with actual job exit status
2 parents 98bbf60 + 64f53a2 commit 505b91e

4 files changed

Lines changed: 198 additions & 20 deletions

File tree

‎apps/api/test/lib/notification-headline.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,46 @@ describe("delivered headline vs the category it was subscribed through", () => {
111111
expect(msg.body).toContain("Policy: pol_1");
112112
expect(msg.body).toContain("Destination: dst_1");
113113
});
114+
115+
it("renders job name, exit code, error, duration, resource, and logs in job failure alerts", () => {
116+
const msg = renderMessage(
117+
delivery("job.run.failed", {
118+
eventType: "job_run.failed",
119+
jobName: "Audit unconfigured backups",
120+
exitCode: 1,
121+
errorMessage: "Command exited with code 1",
122+
durationMs: 2500,
123+
resourceType: "job",
124+
resourceId: "custom:BlS_iYp2_kUnHTbj",
125+
logExcerpt: "ALERT: Found 1 project(s) without backup configuration!",
126+
}),
127+
);
128+
129+
expect(msg.title).toBe("Job failed");
130+
expect(msg.body).toContain("Job: Audit unconfigured backups");
131+
expect(msg.body).toContain("Exit Code: 1");
132+
expect(msg.body).toContain("Error: Command exited with code 1");
133+
expect(msg.body).toContain("Duration: 3s");
134+
expect(msg.body).toContain("Resource: job (custom:BlS_iYp2_kUnHTbj)");
135+
expect(msg.body).toContain("Logs:\nALERT: Found 1 project(s) without backup configuration!");
136+
});
137+
138+
it("renders job name and exit code 0 for successful job runs", () => {
139+
const msg = renderMessage(
140+
delivery("job.run.succeeded", {
141+
eventType: "job_run.succeeded",
142+
label: "Audit disk space",
143+
exitCode: 0,
144+
durationMs: 500,
145+
resourceType: "job",
146+
resourceId: "custom:t6GN81ItRPW_qAkX",
147+
}),
148+
);
149+
150+
expect(msg.title).toBe("Job succeeded");
151+
expect(msg.body).toContain("Job: Audit disk space");
152+
expect(msg.body).toContain("Exit Code: 0");
153+
expect(msg.body).toContain("Duration: 1s");
154+
expect(msg.body).toContain("Resource: job (custom:t6GN81ItRPW_qAkX)");
155+
});
114156
});

‎apps/api/test/modules/jobs/job-command.test.ts‎

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ const h = vi.hoisted(() => ({
77
finishCalls: [] as Array<Record<string, unknown>>,
88
startedRuns: [] as Array<Record<string, unknown>>,
99
cmds: [] as string[],
10+
notifications: [] as Array<Record<string, unknown>>,
11+
members: [] as Array<{ organizationId: string }>,
1012
retain: 0,
1113
release: 0,
1214
runSeq: 0,
1315
execImpl: null as
1416
| null
15-
| ((cmd: string, onLog: (e: { message: string; level: string }) => void, serverId: string) => Promise<{ code: number; output: string }>),
17+
| ((
18+
cmd: string,
19+
onLog: (e: { message: string; level: string }) => void,
20+
serverId: string,
21+
) => Promise<{ code: number; output: string }>),
1622
}));
1723

1824
vi.mock("@repo/db", () => ({
@@ -33,14 +39,26 @@ vi.mock("@repo/db", () => ({
3339
},
3440
listRecent: async () => [],
3541
},
36-
// Notification fan-out — no org resolvable in tests, so these stay quiet.
37-
member: { listByUser: async () => [] },
42+
// Notification fan-out — controllable via h.members and h.notifications
43+
member: { listByUser: async () => h.members },
3844
notificationChannel: { findById: async () => null },
39-
notificationDelivery: { create: async () => {} },
45+
notificationDelivery: {
46+
create: async (d: Record<string, unknown>) => {
47+
h.notifications.push(d);
48+
},
49+
},
4050
notificationSubscription: { listEnabledForDispatch: async () => [] },
4151
},
4252
}));
4353

54+
vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({
55+
notification: {
56+
emit: (input: Record<string, unknown>) => {
57+
h.notifications.push(input);
58+
},
59+
},
60+
}));
61+
4462
vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({
4563
sshManager: {
4664
retain: () => {
@@ -74,6 +92,8 @@ beforeEach(() => {
7492
h.finishCalls.length = 0;
7593
h.startedRuns.length = 0;
7694
h.cmds.length = 0;
95+
h.notifications.length = 0;
96+
h.members.length = 0;
7797
h.jobRows = {};
7898
h.retain = 0;
7999
h.release = 0;
@@ -231,6 +251,56 @@ describe("custom job executor (runCommandJobTick)", () => {
231251
expect(String(f.output)).toContain("srvA");
232252
expect(String(f.output)).toContain("srvB");
233253
});
254+
255+
it("failure emits notification with jobName, exitCode, error, duration, and logExcerpt", async () => {
256+
h.members.push({ organizationId: "org_1" });
257+
h.jobRows["custom:fail"] = {
258+
...cmdJob("custom:fail", { serverId: "srv1", command: "fail.sh" }),
259+
label: "Audit unconfigured backups",
260+
createdBy: "user_1",
261+
};
262+
h.execImpl = async () => ({
263+
code: 17,
264+
output: "ALERT: Found 1 project(s) without backup configuration!\n",
265+
});
266+
267+
await runCommandJobTick("custom:fail");
268+
269+
const failedEmit = h.notifications.find((n) => n.eventType === "job_run.failed");
270+
expect(failedEmit).toBeDefined();
271+
expect(failedEmit?.payload).toMatchObject({
272+
jobName: "Audit unconfigured backups",
273+
label: "Audit unconfigured backups",
274+
jobKey: "custom:fail",
275+
status: "failed",
276+
exitCode: 17,
277+
errorMessage: "Command exited with code 17",
278+
logExcerpt: "ALERT: Found 1 project(s) without backup configuration!",
279+
});
280+
expect(typeof (failedEmit?.payload as Record<string, unknown>)?.durationMs).toBe("number");
281+
expect(h.finishCalls[0].summary).toMatchObject({ exitCode: 17 });
282+
});
283+
284+
it("bounds and scrubs notification output while retaining the failure tail", async () => {
285+
h.members.push({ organizationId: "org_1" });
286+
h.jobRows["custom:logs"] = {
287+
...cmdJob("custom:logs", { serverId: "srv1", command: "run.sh" }),
288+
label: "Backup",
289+
createdBy: "user_1",
290+
};
291+
h.execImpl = async () => ({
292+
code: 2,
293+
output: `${"x".repeat(4000)}\npostgres://user:do-not-deliver@db/app\nlast failure`,
294+
});
295+
296+
await runCommandJobTick("custom:logs");
297+
298+
const event = h.notifications.find((n) => n.eventType === "job_run.failed");
299+
const excerpt = String((event?.payload as Record<string, unknown>)?.logExcerpt);
300+
expect(excerpt.length).toBeLessThanOrEqual(2000);
301+
expect(excerpt).toMatch(/last failure$/);
302+
expect(excerpt).not.toContain("do-not-deliver");
303+
});
234304
});
235305

236306
describe("run SSE bus (createRunBus)", () => {

‎packages/platform/src/engine/lib/notification-workers.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,21 @@ export function renderMessage(delivery: NotificationDelivery): RenderedMessage {
7070
if (payload.destinationName || payload.destinationId) {
7171
lines.push(`Destination: ${payload.destinationName ?? payload.destinationId}`);
7272
}
73+
if (payload.jobName || payload.label) {
74+
lines.push(`Job: ${payload.jobName ?? payload.label}`);
75+
}
7376

7477
if (payload.branch) lines.push(`Branch: ${payload.branch}`);
7578
if (payload.commitSha) {
7679
const sha = String(payload.commitSha).slice(0, 8);
7780
lines.push(`Commit: ${sha}`);
7881
}
7982
if (payload.url) lines.push(`URL: ${payload.url}`);
83+
if (payload.exitCode !== undefined && payload.exitCode !== null) {
84+
lines.push(`Exit Code: ${payload.exitCode}`);
85+
}
8086
if (payload.errorMessage) lines.push(`Error: ${payload.errorMessage}`);
81-
if (payload.durationMs) {
87+
if (payload.durationMs !== undefined && payload.durationMs !== null) {
8288
lines.push(`Duration: ${Math.round(Number(payload.durationMs) / 1000)}s`);
8389
}
8490

@@ -88,6 +94,10 @@ export function renderMessage(delivery: NotificationDelivery): RenderedMessage {
8894
lines.push(`Resource: ${resourceType} (${resourceId})`);
8995
}
9096

97+
if (payload.logExcerpt) {
98+
lines.push(`Logs:\n${String(payload.logExcerpt).trim()}`);
99+
}
100+
91101
return {
92102
title,
93103
body: lines.join("\n"),
@@ -481,7 +491,9 @@ async function sendTelegram(
481491
return; // 200 with an unparseable body: accept rather than retry forever.
482492
}
483493
if (parsed && parsed.ok === false) {
484-
throw new Error(`Telegram rejected the message: ${(parsed.description ?? "unknown error").slice(0, 200)}`);
494+
throw new Error(
495+
`Telegram rejected the message: ${(parsed.description ?? "unknown error").slice(0, 200)}`,
496+
);
485497
}
486498
}
487499

‎packages/platform/src/engine/modules/jobs/job-command.ts‎

Lines changed: 68 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ import { decryptEnvMap } from "../../lib/encryption";
3131
import { notification } from "../../lib/notification-dispatcher";
3232
import { jobRunBus } from "./job-run.sse";
3333
import { boundedStorableText } from "../deployments/build-log-sanitize";
34-
import { resolveServerIds, type CommandConfig, type JobNotifyConfig, type JobRunState } from "./job.types";
34+
import {
35+
resolveServerIds,
36+
type CommandConfig,
37+
type JobNotifyConfig,
38+
type JobRunState,
39+
} from "./job.types";
3540

3641
/** Cap stored output so a chatty command can't bloat the row. */
3742
const MAX_OUTPUT = 200_000;
@@ -103,7 +108,7 @@ async function runOnServer(
103108
async function executeAttempt(
104109
cfg: CommandConfig,
105110
streamId: string,
106-
): Promise<{ status: JobRunState; output: string; error?: string }> {
111+
): Promise<{ status: JobRunState; output: string; error?: string; exitCode?: number }> {
107112
const publish = (line: string, level: LogEntry["level"]) =>
108113
jobRunBus.publish(streamId, { type: "log", line, level });
109114
try {
@@ -113,7 +118,7 @@ async function executeAttempt(
113118
}
114119
const command = buildCommand(cfg);
115120

116-
let code: number;
121+
let code: number | null;
117122
let output: string;
118123
if (servers.length === 1) {
119124
const r = await runOnServer(servers[0], command, (e) => publish(e.message, e.level), cfg.timeoutMs);
@@ -128,17 +133,23 @@ async function executeAttempt(
128133
} catch (err) {
129134
const msg = safeErrorMessage(err);
130135
publish(`[${sid}] ${msg}`, "error");
131-
return { sid, code: 1, output: msg };
136+
return { sid, code: null, output: msg };
132137
}
133138
}),
134139
);
135-
code = results.every((r) => r.code === 0) ? 0 : 1;
136-
output = results.map((r) => `── ${r.sid} (exit ${r.code}) ──\n${r.output}`).join("\n\n");
140+
const firstFailure = results.find((r) => r.code !== 0);
141+
code = firstFailure ? firstFailure.code : 0;
142+
output = results.map((r) => `── ${r.sid} (exit ${r.code ?? "unknown"}) ──\n${r.output}`).join("\n\n");
137143
}
138144

139145
return code === 0
140-
? { status: "success", output }
141-
: { status: "failed", output, error: `Command exited with code ${code}` };
146+
? { status: "success", output, exitCode: 0 }
147+
: {
148+
status: "failed",
149+
output,
150+
exitCode: code ?? undefined,
151+
error: code === null ? "Command failed without an exit status" : `Command exited with code ${code}`,
152+
};
142153
} catch (err) {
143154
const message = safeErrorMessage(err);
144155
publish(message, "error");
@@ -161,7 +172,7 @@ async function runLoop(row: Job, run: JobRun): Promise<void> {
161172
await emitJobRun(row, run.id, "running");
162173

163174
let finalStatus: JobRunState = "failed";
164-
let exitCode = 1;
175+
let exitCode: number | undefined;
165176
let lastError: string | undefined;
166177
let attemptsUsed = 0;
167178
const chunks: string[] = [];
@@ -175,6 +186,7 @@ async function runLoop(row: Job, run: JobRun): Promise<void> {
175186
}
176187
const res = await executeAttempt(cfg, run.id);
177188
chunks.push(res.output);
189+
exitCode = res.exitCode;
178190
if (res.status === "success") {
179191
finalStatus = "success";
180192
exitCode = 0;
@@ -185,9 +197,10 @@ async function runLoop(row: Job, run: JobRun): Promise<void> {
185197
if (attempt < maxAttempts && backoffMs) await sleep(backoffMs);
186198
}
187199

200+
const durationMs = Date.now() - startedMs;
188201
await finishRunRow(run.id, row.key, {
189202
status: finalStatus,
190-
durationMs: Date.now() - startedMs,
203+
durationMs,
191204
summary: { exitCode, attempts: attemptsUsed },
192205
output: boundedStorableText(chunks.join("\n"), MAX_OUTPUT),
193206
error:
@@ -198,10 +211,17 @@ async function runLoop(row: Job, run: JobRun): Promise<void> {
198211
try {
199212
jobRunBus.publish(run.id, { type: "complete", status: finalStatus, error: lastError });
200213
} catch (err) {
201-
console.error(`[job] ${row.key} run ${run.id}: terminal SSE publish failed: ${safeErrorMessage(err)}`);
214+
console.error(
215+
`[job] ${row.key} run ${run.id}: terminal SSE publish failed: ${safeErrorMessage(err)}`,
216+
);
202217
}
203218

204-
await emitJobRun(row, run.id, finalStatus);
219+
await emitJobRun(row, run.id, finalStatus, {
220+
durationMs,
221+
exitCode,
222+
error: lastError ? boundedStorableText(lastError, MAX_ERROR) : undefined,
223+
output: chunks.join("\n"),
224+
});
205225
if (finalStatus === "success") await fireDependents(row.key);
206226
}
207227

@@ -307,11 +327,45 @@ async function resolveOrgIdForUser(userId: string): Promise<string | null> {
307327
return members[0]?.organizationId ?? null;
308328
}
309329

330+
const MAX_NOTIFY_LOG_LINES = 20;
331+
const MAX_NOTIFY_LOG_CHARS = 2000;
332+
333+
function extractLogExcerpt(output?: string): string | undefined {
334+
if (!output) return undefined;
335+
const trimmed = output.trim();
336+
if (!trimmed) return undefined;
337+
const lines = trimmed.split("\n");
338+
const tail = boundedStorableText(lines.slice(-MAX_NOTIFY_LOG_LINES).join("\n"), Number.MAX_SAFE_INTEGER);
339+
if (tail.length <= MAX_NOTIFY_LOG_CHARS) return tail;
340+
return boundedStorableText(`…\n${tail.slice(-(MAX_NOTIFY_LOG_CHARS - 2))}`, MAX_NOTIFY_LOG_CHARS);
341+
}
342+
310343
/** Notify on a run state. Per-job `notifyConfig` (if present) OVERRIDES the
311344
* global Settings subscriptions — its channels/states win, no double-fire. */
312-
async function emitJobRun(row: Job, runId: string, status: JobRunState): Promise<void> {
345+
async function emitJobRun(
346+
row: Job,
347+
runId: string,
348+
status: JobRunState,
349+
meta?: {
350+
durationMs?: number;
351+
exitCode?: number;
352+
error?: string;
353+
output?: string;
354+
},
355+
): Promise<void> {
313356
try {
314-
const payload = { label: row.label, jobKey: row.key, status, runId };
357+
const logExcerpt = extractLogExcerpt(meta?.output);
358+
const payload: Record<string, unknown> = {
359+
label: row.label,
360+
jobName: row.label,
361+
jobKey: row.key,
362+
status,
363+
runId,
364+
...(meta?.durationMs !== undefined ? { durationMs: meta.durationMs } : {}),
365+
...(meta?.exitCode !== undefined ? { exitCode: meta.exitCode } : {}),
366+
...(meta?.error ? { errorMessage: meta.error } : {}),
367+
...(logExcerpt ? { logExcerpt } : {}),
368+
};
315369
const notify = row.notifyConfig as JobNotifyConfig | null;
316370

317371
if (notify?.channels?.length) {

0 commit comments

Comments
 (0)