Files
monlet/web/tests/mock-server.mjs
2026-05-27 10:01:59 +04:00

134 lines
3.1 KiB
JavaScript

import { createServer } from "node:http";
const PORT = Number(process.env.MOCK_PORT ?? 8765);
const now = new Date().toISOString();
const fixtures = {
"/api/v1/health": { status: "ok" },
"/api/v1/agents": {
items: [
{
agent_id: "agent-1",
hostname: "host-1",
status: "alive",
last_seen_at: now,
features: { push: true, metrics: false },
labels: { env: "dev", monlet_agent_version: "0.1.0" },
},
{
agent_id: "agent-2",
hostname: "host-2",
status: "stale",
last_seen_at: now,
features: { push: true, metrics: false },
labels: {},
},
],
next_cursor: null,
},
"/api/v1/agents/agent-1": {
agent_id: "agent-1",
hostname: "host-1",
status: "alive",
last_seen_at: now,
features: { push: true, metrics: false },
labels: { env: "dev", monlet_agent_version: "0.1.0" },
},
"/api/v1/checks": {
items: [
{
agent_id: "agent-1",
check_id: "disk",
status: "ok",
exit_code: 0,
last_observed_at: now,
incident_key: "agent-1:disk",
},
{
agent_id: "agent-1",
check_id: "load",
status: "warning",
exit_code: 1,
last_observed_at: now,
incident_key: "agent-1:load",
},
],
next_cursor: null,
},
"/api/v1/incidents": {
items: [
{
id: "00000000-0000-0000-0000-000000000001",
incident_key: "agent-1:load",
state: "open",
severity: "warning",
agent_id: "agent-1",
check_id: "load",
opened_at: now,
summary: "load high",
},
],
next_cursor: null,
},
"/api/v1/events/query": {
items: [
{
event_id: "00000000-0000-7000-8000-000000000001",
agent_id: "agent-1",
check_id: "disk",
observed_at: now,
received_at: now,
status: "ok",
exit_code: 0,
duration_ms: 12,
},
],
next_cursor: null,
},
"/api/v1/notifiers/outbox": {
items: [
{
id: "00000000-0000-0000-0000-000000000002",
notifier: "debug",
state: "sent",
incident_id: "00000000-0000-0000-0000-000000000001",
event_type: "firing",
attempts: 1,
next_attempt_at: null,
last_error: null,
updated_at: now,
},
],
next_cursor: null,
},
};
const server = createServer((req, res) => {
const url = new URL(req.url ?? "/", `http://x`);
let body = fixtures[url.pathname];
if (url.pathname === "/api/v1/checks" && body) {
const agentId = url.searchParams.get("agent_id");
if (agentId) {
body = {
...body,
items: body.items.filter((item) => item.agent_id === agentId),
next_cursor: null,
};
}
}
res.setHeader("Content-Type", "application/json");
if (!body) {
res.statusCode = 404;
res.end(
JSON.stringify({ error: { code: "not_found", message: "not in fixtures", request_id: "mock" } }),
);
return;
}
res.end(JSON.stringify(body));
});
server.listen(PORT, "127.0.0.1", () => {
console.log(`mock server on ${PORT}`);
});