Skip to content

Commit 5281b90

Browse files
feat: add production logging with context (#14)
1 parent 26d6ca6 commit 5281b90

8 files changed

Lines changed: 223 additions & 131 deletions

File tree

‎src/cla/cla.controller.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import { randomUUID } from "node:crypto";
12
import { Body, Controller, HttpCode, Post, Req } from "@nestjs/common";
23
import type { Request } from "express";
4+
import { withCorrelationId } from "../correlation.js";
35
// biome-ignore lint/style/useImportType: DI paramtype — `import type` gets erased
46
import { ClaService } from "./cla.service.js";
57

@@ -11,16 +13,20 @@ export class ClaController {
1113
@HttpCode(200)
1214
sign(@Body() body: unknown, @Req() request: Request): Promise<{ message: string }> {
1315
const forwardedFor = request.headers["x-forwarded-for"];
14-
return this.claService.sign(
15-
body,
16-
Array.isArray(forwardedFor) ? forwardedFor.join(", ") : (forwardedFor ?? ""),
17-
request.headers["user-agent"] ?? "",
16+
// cla:<uuid> — there's no upstream delivery ID; the generated one still
17+
// correlates the sign request with the PR re-evaluation it triggers.
18+
return withCorrelationId(`cla:${randomUUID()}`, () =>
19+
this.claService.sign(
20+
body,
21+
Array.isArray(forwardedFor) ? forwardedFor.join(", ") : (forwardedFor ?? ""),
22+
request.headers["user-agent"] ?? "",
23+
),
1824
);
1925
}
2026

2127
@Post("authorize")
2228
@HttpCode(200)
2329
authorize(@Body() body: unknown): Promise<Record<string, unknown>> {
24-
return this.claService.authorize(body);
30+
return withCorrelationId(`cla:${randomUUID()}`, () => this.claService.authorize(body));
2531
}
2632
}

‎src/cla/cla.service.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,24 @@ export class ClaService {
3434

3535
async sign(payload: unknown, ipAddress: string, userAgent: string): Promise<{ message: string }> {
3636
const store = this.store;
37-
if (!store) throw new HttpException({ message: "CLA sign flow is not configured" }, 503);
37+
if (!store) {
38+
log.info("cla: sign rejected", { reason: "store not configured" });
39+
throw new HttpException({ message: "CLA sign flow is not configured" }, 503);
40+
}
3841

3942
const body = asRecord(payload);
4043
if (!body || typeof body.github_username !== "string" || !body.github_username) {
44+
log.info("cla: sign rejected", { reason: "missing github_username" });
4145
throw new HttpException({ message: "Missing required data in payload" }, 400);
4246
}
4347
const login = body.github_username;
4448

4549
const pending = await store.getPendingSigner(login);
4650
if (!pending) {
51+
// Rejections go out as HttpExceptions, which the exception filter
52+
// deliberately doesn't log — this line is the only trace of "I signed
53+
// but the bot didn't notice" support cases.
54+
log.info("cla: sign rejected", { login, reason: "no pending request" });
4755
throw new HttpException(
4856
{
4957
message:
@@ -65,6 +73,11 @@ export class ClaService {
6573
};
6674
await store.recordSignature(signature);
6775
await store.deletePendingSigner(login);
76+
log.info("cla: signature recorded", {
77+
login,
78+
repository: `${pending.owner}/${pending.repo}`,
79+
number: pending.number,
80+
});
6881

6982
try {
7083
await evaluatePR(this.env, registryConfig, this.octokit, pending);
@@ -82,11 +95,13 @@ export class ClaService {
8295
/** OAuth code exchange backing the sign form's GitHub login. */
8396
async authorize(payload: unknown): Promise<Record<string, unknown>> {
8497
if (!this.env.CLA_SIGN_CLIENT_ID || !this.env.CLA_SIGN_CLIENT_SECRET) {
98+
log.info("cla: authorize rejected", { reason: "OAuth credentials not configured" });
8599
throw new HttpException({ message: "CLA sign flow is not configured" }, 503);
86100
}
87101

88102
const body = asRecord(payload);
89103
if (!body || typeof body.code !== "string" || !body.code) {
104+
log.info("cla: authorize rejected", { reason: "missing code" });
90105
throw new HttpException({ message: "Missing required data in payload" }, 400);
91106
}
92107

@@ -104,6 +119,12 @@ export class ClaService {
104119
});
105120
const data = (await resp.json()) as Record<string, unknown>;
106121
if (!resp.ok || "error" in data) {
122+
// Usually an expired/reused code (user-side), but the same shape covers
123+
// a misconfigured client secret — warn so operators see it.
124+
log.warn("cla: authorize failed", {
125+
status: resp.status,
126+
error: String(data.error_description ?? data.error ?? "unknown"),
127+
});
107128
throw new HttpException(
108129
{ message: (data.error_description as string) ?? "Could not authorize" },
109130
400,

‎src/correlation.ts‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,34 @@
11
import { AsyncLocalStorage } from "node:async_hooks";
22

33
/**
4-
* Correlation ID for the unit of work currently executing — `gh:<delivery>`
5-
* for GitHub webhook deliveries, `dc:<snowflake>` for Discord events. Stored
6-
* in AsyncLocalStorage so `log` can stamp it onto every entry without the
7-
* call sites threading it through.
4+
* Ambient log context for the unit of work currently executing. Established
5+
* with a correlation ID — `gh:<delivery>` for GitHub webhook deliveries,
6+
* `dc:<snowflake>` for Discord events, `cla:<uuid>` for CLA sign requests —
7+
* and enriched via `addLogContext` as the work figures out what it is
8+
* handling (repository, number, eventType, …). Stored in AsyncLocalStorage
9+
* so `log` can stamp it onto every entry without the call sites threading it
10+
* through.
811
*/
9-
const storage = new AsyncLocalStorage<string>();
12+
type LogContext = Record<string, unknown>;
13+
14+
const storage = new AsyncLocalStorage<LogContext>();
1015

1116
/** Run `fn` (and everything async it starts) under the given correlation ID. */
1217
export function withCorrelationId<T>(id: string, fn: () => T): T {
13-
return storage.run(id, fn);
18+
return storage.run({ correlationId: id }, fn);
19+
}
20+
21+
/**
22+
* Merge attributes into the ambient context — every log call in the current
23+
* unit of work carries them from here on. Keep it to a few flat identity
24+
* fields; everything added lands on every subsequent line. No-op outside a
25+
* correlation scope.
26+
*/
27+
export function addLogContext(attributes: LogContext): void {
28+
const store = storage.getStore();
29+
if (store) Object.assign(store, attributes);
1430
}
1531

16-
export function correlationId(): string | undefined {
32+
export function logContext(): LogContext | undefined {
1733
return storage.getStore();
1834
}

‎src/discord/engine/dispatch.ts‎

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -37,18 +37,12 @@ function errorReply(err: unknown): DiscordEffect {
3737
};
3838
}
3939

40-
/** Sentry events need to say where they came from without the transcript. */
41-
function reportException(
42-
err: unknown,
43-
context: DiscordContext,
44-
attributes: Record<string, string>,
45-
): void {
46-
log.exception(err instanceof Error ? err : new Error(String(err)), {
47-
guildId: context.guildId,
48-
channel: context.channel.name,
49-
user: context.user.username,
50-
...attributes,
51-
});
40+
/**
41+
* Guild/channel/user ride along ambiently (the gateway stamps them, see
42+
* correlation.ts) — only what's local to the failing handler goes here.
43+
*/
44+
function reportException(err: unknown, attributes: Record<string, string>): void {
45+
log.exception(err instanceof Error ? err : new Error(String(err)), attributes);
5246
}
5347

5448
function isAnswered(effects: DiscordEffect[]): boolean {
@@ -62,16 +56,11 @@ async function dispatchCommand(
6256
const { command: name, guildId } = context.event;
6357
const command = findGuildCommand(registry, guildId, name);
6458
if (!command) {
65-
log.warn("discord: unknown command", { guildId, command: name });
59+
log.warn("discord: unknown command", { command: name });
6660
return [{ type: "reply", content: "Unknown command", ephemeral: true }];
6761
}
6862

69-
log.info("discord: command", {
70-
guildId,
71-
command: name,
72-
channel: context.channel.name,
73-
user: context.user.username,
74-
});
63+
log.info("discord: command", { command: name });
7564

7665
try {
7766
const effects = (await command.handle(context)) ?? [];
@@ -81,7 +70,7 @@ async function dispatchCommand(
8170
? effects
8271
: [...effects, { type: "reply", content: "Command completed", ephemeral: true }];
8372
} catch (err) {
84-
reportException(err, context, { command: name });
73+
reportException(err, { command: name });
8574
return [errorReply(err)];
8675
}
8776
}
@@ -95,7 +84,7 @@ async function dispatchAutocomplete(
9584
try {
9685
return [{ type: "autocomplete", choices: await command.autocomplete(context) }];
9786
} catch (err) {
98-
reportException(err, context, { command: context.event.command });
87+
reportException(err, { command: context.event.command });
9988
// Still answer the interaction — an empty list renders as "no results".
10089
return [{ type: "autocomplete", choices: [] }];
10190
}
@@ -114,7 +103,7 @@ async function dispatchModal(
114103
try {
115104
return (await command.handleModal(context)) ?? [];
116105
} catch (err) {
117-
reportException(err, context, { customId: context.event.customId });
106+
reportException(err, { customId: context.event.customId });
118107
return [errorReply(err)];
119108
}
120109
}
@@ -131,7 +120,7 @@ async function dispatchMessage(
131120
try {
132121
effects.push(...((await handler(context)) ?? []));
133122
} catch (err) {
134-
reportException(err, context, { listener: listener.name });
123+
reportException(err, { listener: listener.name });
135124
}
136125
}
137126
return effects;

‎src/discord/engine/gateway.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
TextInputBuilder,
1818
TextInputStyle,
1919
} from "discord.js";
20-
import { withCorrelationId } from "../../correlation.js";
20+
import { addLogContext, withCorrelationId } from "../../correlation.js";
2121
import { log } from "../../log.js";
2222
import type { ChannelPort, EffectPorts, ResponderPort } from "./apply.js";
2323
import { applyDiscordEffects } from "./apply.js";
@@ -288,11 +288,31 @@ export async function startDiscordGateway(
288288

289289
const handle = async (event: DiscordEvent | undefined, responder?: ResponderPort) => {
290290
if (!event) return;
291+
addLogContext({
292+
guildId: event.guildId,
293+
channel: event.channel.name,
294+
user: event.user.username,
295+
});
291296
config.onEvent?.(event);
292297
const effects = await dispatchDiscordEvent(registry, event, reader);
293298
await applyDiscordEffects(effects, { ...ports, responder });
294299
};
295300

301+
// Gateway health. discord.js reconnects dropped shards on its own, so
302+
// disconnect/resume are informational — but Invalidated is terminal: the
303+
// client stops and only a process restart brings the bot back.
304+
client.on(Events.Error, (err) => log.exception(err));
305+
client.on(Events.Warn, (message) => log.warn("discord: client warning", { message }));
306+
client.on(Events.ShardDisconnect, (event, shardId) => {
307+
log.warn("discord: gateway disconnected", { shardId, code: event.code });
308+
});
309+
client.on(Events.ShardResume, (shardId, replayedEvents) => {
310+
log.info("discord: gateway resumed", { shardId, replayedEvents });
311+
});
312+
client.on(Events.Invalidated, () => {
313+
log.error("discord: session invalidated — gateway stopped, restart required");
314+
});
315+
296316
// dc:<snowflake> — the interaction/message ID correlates every log line of
297317
// one event's handling, mirroring gh:<delivery> on the webhook side.
298318
client.on(Events.InteractionCreate, (interaction) => {

0 commit comments

Comments
 (0)