Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions migrations/health_index.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- up
CREATE INDEX IF NOT EXISTS idx_audit_logs_action_created_at ON audit_logs (action, created_at DESC);

-- down
DROP INDEX IF NOT EXISTS idx_audit_logs_action_created_at;
60 changes: 42 additions & 18 deletions src/routes/health.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,55 @@
import { Router } from "express";
import { createAuditLog } from "../services/auditService";
import { getRequestId } from "../lib/requestContext";
import { db } from "../db/client";
import { auditLogs } from "../db/schema";
import { eq, desc } from "drizzle-orm";

export const healthRouter = Router();

// Mock memory state for demonstration purposes on health state
let currentHealthState = { mode: "active", maintenance: false };
healthRouter.get("/", async (_req, res, next) => {
try {
const [latest] = await db
.select()
.from(auditLogs)
.where(eq(auditLogs.action, "health.state_mutation"))
.orderBy(desc(auditLogs.createdAt))
.limit(1);

healthRouter.get("/", (_req, res) => {
res.json({ status: "ok", state: currentHealthState });
const state = (latest?.afterState as Record<string, unknown>) || { mode: "active", maintenance: false };
res.json({ status: "ok", state });
} catch (err) {
next(err);
}
});

healthRouter.post("/mutations", async (req, res) => {
const ip = req.ip || req.socket.remoteAddress || "unknown";
const correlationId = getRequestId();
const beforeState = { ...currentHealthState };
healthRouter.post("/mutations", async (req, res, next) => {
try {
const ip = req.ip || req.socket.remoteAddress || "unknown";
const correlationId = getRequestId();

// Apply changes from body payload
currentHealthState = { ...currentHealthState, ...req.body };
const [latest] = await db
.select()
.from(auditLogs)
.where(eq(auditLogs.action, "health.state_mutation"))
.orderBy(desc(auditLogs.createdAt))
.limit(1);

await createAuditLog({
action: "health.state_mutation",
ip,
correlationId,
beforeState,
afterState: currentHealthState,
});
const beforeState = (latest?.afterState as Record<string, unknown>) || { mode: "active", maintenance: false };

res.json({ status: "updated", state: currentHealthState });
// Apply changes from body payload
const afterState = { ...beforeState, ...req.body };

await createAuditLog({
action: "health.state_mutation",
ip,
correlationId,
beforeState,
afterState,
});

res.json({ status: "updated", state: afterState });
} catch (err) {
next(err);
}
});
50 changes: 45 additions & 5 deletions tests/health.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,51 @@ process.env.PREDICTIFY_CONTRACT_ID = "test-contract-id";

import request from "supertest";
import { createApp } from "../src/index";
import { db } from "../src/db/client";

describe("GET /health", () => {
it("returns ok status", async () => {
const res = await request(createApp()).get("/health");
expect(res.status).toBe(200);
expect(res.body.status).toBe("ok");
jest.mock("../src/db/client", () => ({
db: {
select: jest.fn().mockReturnThis(),
from: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
limit: jest.fn().mockResolvedValue([
{ afterState: { mode: "active", maintenance: false } }
]),
},
pool: {
query: jest.fn(),
},
}));

jest.mock("../src/services/auditService", () => ({
createAuditLog: jest.fn().mockResolvedValue("mock-correlation-id"),
}));

describe("healthRouter endpoints", () => {
beforeEach(() => {
jest.clearAllMocks();
});

describe("GET /health", () => {
it("returns ok status and db state", async () => {
const res = await request(createApp()).get("/health");
expect(res.status).toBe(200);
expect(res.body.status).toBe("ok");
expect(res.body.state).toEqual({ mode: "active", maintenance: false });
});
});

describe("POST /health/mutations", () => {
it("updates health state and logs audit", async () => {
const res = await request(createApp())
.post("/health/mutations")
.send({ mode: "maintenance", maintenance: true });

expect(res.status).toBe(200);
expect(res.body.status).toBe("updated");
expect(res.body.state.mode).toBe("maintenance");
expect(res.body.state.maintenance).toBe(true);
});
});
});
Loading