-
-
Notifications
You must be signed in to change notification settings - Fork 0
fix: production audit remediation — correctness, reliability, perf, dedup #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f9389cf
fix: production audit remediation — correctness, reliability, perf, d…
nathanialhenniges 7b4ebc4
fix(tests): resolve cross-file mock leakage breaking CI
nathanialhenniges fe4d577
fix(tests): introduce commandRegistry module to eliminate mock leakage
nathanialhenniges b35eefd
fix: address CodeRabbit review feedback
nathanialhenniges 180624a
fix(tests): stop leaking guildDatabase + suggestionHelpers mocks on CI
nathanialhenniges File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| CREATE TYPE "public"."DiscordActivityType" AS ENUM('Custom', 'Listening', 'Streaming', 'Playing');--> statement-breakpoint | ||
| CREATE TYPE "public"."MotivationFrequency" AS ENUM('Daily', 'Weekly', 'Monthly');--> statement-breakpoint | ||
| CREATE TYPE "public"."SuggestionStatus" AS ENUM('Pending', 'Approved', 'Rejected');--> statement-breakpoint | ||
| CREATE TABLE "DiscordActivity" ( | ||
| "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, | ||
| "activity" text NOT NULL, | ||
| "type" "DiscordActivityType" DEFAULT 'Custom' NOT NULL, | ||
| "url" text, | ||
| "createdAt" timestamp DEFAULT now() NOT NULL | ||
| ); | ||
| --> statement-breakpoint | ||
| CREATE TABLE "Guild" ( | ||
| "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, | ||
| "guildId" text NOT NULL, | ||
| "motivationChannelId" text, | ||
| "motivationFrequency" "MotivationFrequency" DEFAULT 'Daily' NOT NULL, | ||
| "motivationTime" text DEFAULT '08:00' NOT NULL, | ||
| "motivationDay" integer, | ||
| "timezone" text DEFAULT 'America/Chicago' NOT NULL, | ||
| "lastMotivationSentAt" timestamp, | ||
| "isPremium" boolean DEFAULT false NOT NULL, | ||
| "joinedAt" timestamp DEFAULT now() NOT NULL, | ||
| "updatedAt" timestamp DEFAULT now() NOT NULL, | ||
| CONSTRAINT "Guild_guildId_unique" UNIQUE("guildId") | ||
| ); | ||
| --> statement-breakpoint | ||
| CREATE TABLE "MotivationQuote" ( | ||
| "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, | ||
| "quote" text NOT NULL, | ||
| "author" text NOT NULL, | ||
| "addedBy" text NOT NULL, | ||
| "createdAt" timestamp DEFAULT now() NOT NULL | ||
| ); | ||
| --> statement-breakpoint | ||
| CREATE TABLE "SuggestionQuote" ( | ||
| "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, | ||
| "quote" text NOT NULL, | ||
| "author" text NOT NULL, | ||
| "addedBy" text NOT NULL, | ||
| "status" "SuggestionStatus" DEFAULT 'Pending' NOT NULL, | ||
| "reviewedBy" text, | ||
| "reviewedAt" timestamp, | ||
| "createdAt" timestamp DEFAULT now() NOT NULL, | ||
| "updatedAt" timestamp DEFAULT now() NOT NULL | ||
| ); | ||
| --> statement-breakpoint | ||
| CREATE INDEX "guild_motivation_channel_idx" ON "Guild" USING btree ("motivationChannelId");--> statement-breakpoint | ||
| CREATE INDEX "suggestion_status_idx" ON "SuggestionQuote" USING btree ("status"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,65 @@ | ||
| import express from "express"; | ||
|
|
||
| import { queryClient } from "../../database/index.js"; | ||
| import redisClient from "../../redis/index.js"; | ||
| import env from "../../utils/env.js"; | ||
| import logger from "../../utils/logger.js"; | ||
|
|
||
| const router: express.Router = express.Router(); | ||
|
|
||
| router.get("/", (_req, res) => { | ||
| res.json({ status: "ok" }); | ||
| const PROBE_TIMEOUT_MS = 1500; | ||
|
|
||
| /** | ||
| * Note: on timeout the underlying probe query keeps running until the driver | ||
| * gives up (postgres-js `connect_timeout: 10`, ioredis default command behavior). | ||
| * The health endpoint is expected to be called infrequently (Coolify/k8s probe | ||
| * cadence, seconds-apart), so a backed-up probe is tolerable. If this endpoint | ||
| * ever moves to high-QPS monitoring, switch to `postgres().cancel()` on the | ||
| * pending query and a dedicated ioredis connection with command timeout. | ||
| */ | ||
| function withTimeout<T>(promise: PromiseLike<T>, ms: number, label: string): Promise<T> { | ||
| return new Promise<T>((resolve, reject) => { | ||
| const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); | ||
| Promise.resolve(promise).then( | ||
| (value) => { | ||
| clearTimeout(timer); | ||
| resolve(value); | ||
| }, | ||
| (err) => { | ||
| clearTimeout(timer); | ||
| reject(err); | ||
| } | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| router.get("/", async (_req, res) => { | ||
| const [dbResult, redisResult] = await Promise.allSettled([ | ||
| withTimeout(queryClient`SELECT 1`, PROBE_TIMEOUT_MS, "db"), | ||
| withTimeout(redisClient.ping(), PROBE_TIMEOUT_MS, "redis"), | ||
| ]); | ||
|
|
||
| const db = dbResult.status === "fulfilled" ? "ok" : "error"; | ||
| const redis = redisResult.status === "fulfilled" ? "ok" : "error"; | ||
| const status = db === "ok" && redis === "ok" ? "ok" : "degraded"; | ||
|
|
||
| const body: Record<string, unknown> = { status, db, redis }; | ||
| const includeDetails = env.NODE_ENV !== "production"; | ||
|
|
||
| if (dbResult.status === "rejected") { | ||
| logger.error("API", "Health probe failed (db)", dbResult.reason); | ||
| if (includeDetails) { | ||
| body["dbError"] = (dbResult.reason as Error)?.message ?? String(dbResult.reason); | ||
| } | ||
| } | ||
| if (redisResult.status === "rejected") { | ||
| logger.error("API", "Health probe failed (redis)", redisResult.reason); | ||
| if (includeDetails) { | ||
| body["redisError"] = (redisResult.reason as Error)?.message ?? String(redisResult.reason); | ||
| } | ||
| } | ||
|
|
||
| res.status(status === "ok" ? 200 : 503).json(body); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }); | ||
|
|
||
| export default router; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,74 +1,33 @@ | ||
| import { Client, CommandInteraction, MessageFlags } from "discord.js"; | ||
| import type { Client, CommandInteraction } from "discord.js"; | ||
|
|
||
| import { desc } from "drizzle-orm"; | ||
|
|
||
| import type { DiscordActivity } from "../../../database/schema.js"; | ||
|
|
||
| import logger from "../../../utils/logger.js"; | ||
| import { safeErrorReply } from "../../../utils/commandErrors.js"; | ||
| import { withCommandLogging } from "../../../utils/commandErrors.js"; | ||
| import { isUserPermitted } from "../../../utils/permissions.js"; | ||
| import { db } from "../../../database/index.js"; | ||
| import { discordActivities } from "../../../database/schema.js"; | ||
| import { replyWithTextFile } from "../../../utils/replyHelpers.js"; | ||
|
|
||
| export default async function ( | ||
| _client: Client, | ||
| interaction: CommandInteraction | ||
| ): Promise<void> { | ||
| try { | ||
| logger.commands.executing( | ||
| "admin activity list", | ||
| interaction.user.username, | ||
| interaction.user.id | ||
| ); | ||
|
|
||
| const isAllowed = await isUserPermitted(interaction); | ||
|
|
||
| if (!isAllowed) { | ||
| return; | ||
| } | ||
| await withCommandLogging("admin activity list", interaction, async () => { | ||
| if (!(await isUserPermitted(interaction))) {return;} | ||
|
|
||
| const activities = await db | ||
| .select() | ||
| .from(discordActivities) | ||
| .orderBy(desc(discordActivities.createdAt)); | ||
|
|
||
| if (activities.length === 0) { | ||
| await interaction.reply({ | ||
| content: "No activities found at the moment. Feel free to add some!", | ||
| flags: MessageFlags.Ephemeral, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| let text = "ID - Activity - Type - URL\n"; | ||
| activities.forEach((activity: DiscordActivity) => { | ||
| text += `${activity.id} - ${activity.activity} - ${activity.type} - ${ | ||
| activity.url || "N/A" | ||
| }\n`; | ||
| await replyWithTextFile({ | ||
| interaction, | ||
| rows: activities, | ||
| header: "ID - Activity - Type - URL", | ||
| formatRow: (a) => `${a.id} - ${a.activity} - ${a.type} - ${a.url || "N/A"}`, | ||
| filename: "activities.txt", | ||
| emptyMessage: "No activities found at the moment. Feel free to add some!", | ||
| ephemeral: false, | ||
| }); | ||
|
|
||
| await interaction.reply({ | ||
| files: [ | ||
| { | ||
| attachment: Buffer.from(text), | ||
| name: "activities.txt", | ||
| }, | ||
| ], | ||
| }); | ||
|
|
||
| logger.commands.success( | ||
| "admin activity list", | ||
| interaction.user.username, | ||
| interaction.user.id | ||
| ); | ||
| } catch (err) { | ||
| logger.commands.error( | ||
| "admin activity list", | ||
| interaction.user.username, | ||
| interaction.user.id, | ||
| err | ||
| ); | ||
|
|
||
| await safeErrorReply(interaction); | ||
| } | ||
| }); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
withTimeoutdoes not cancel the underlying probe.On timeout the outer promise rejects but the
queryClient\SELECT 1`query andredisClient.ping()keep running in the background, still holding a pool connection until the driver itself gives up (connect_timeout: 10` on Postgres). Under a real DB stall, a burst of health calls can pile up pending queries and make the bad state worse rather than surface it quickly.Not a blocker given health checks are typically low-QPS, but worth being aware of — especially if this endpoint is wired up to a liveness probe that runs often. For postgres-js you can call
.cancel()on the pending query, and for ioredis you can sendping()on a dedicated connection with a short command timeout.🤖 Prompt for AI Agents