mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
feat(admin): errors page built around issues, linked to repositories and users
The admin Errors page now shows one list of issues: records grouped by error code (or exception type), service and route, each with a plain-language title, a likely cause, its impact (failures, repositories, users), a trend and when it was last seen. Expected 4xx answers sit in a collapsed group; slow and interrupted requests are left out and counted, with a link to Performance. - GET /api/admin/errors/issues groups server-side (admin-error-issues.ts). It reads central logs when they answer and the Redis history otherwise, accepts validated repoId/userId/service/window filters and resolves repository owners and user names when the database is connected. - The cause is derived from external_request records of the same requests (#990 field names), fast 429s, storage and network codes, and the first application stack frame; otherwise it says nothing is known. - Issue page (?issue=) with cause, affected repositories and owners, who hit it, failures over time and occurrences. Request view (&occurrence=) with a waterfall from the existing correlation lookup and Request, Exception and All fields tabs; missing data shows as "not recorded". - Repositories (search = one repoId) and user admin pages list their issues, with a "failing now" banner. - The source switch, export, clear history, telemetry and 24-hour counters move to a collapsed "Settings and diagnostics" section. - Synthetic fixtures shared by dev-mock and preview-errors; old errors-page CSS removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c281841f91
commit
2abd6beaa9
21 files changed
+2053
-2323
No files matched your search
+25
-28
@@ -905,32 +905,13 @@ const metricsPoints = (queue, range) => {
|
||||
});
|
||||
};
|
||||
|
||||
// ---- Errors (logger ring entries: { ts, level, module, message, raw })
|
||||
|
||||
const errorEntries = [
|
||||
[0.02, "error", "streamer", "anonymous error", { name: "AnonymousError", message: "file_not_found", httpStatus: 500, detail: "dl-benchmark-2026", url: "/api/repo/dl-benchmark-2026/file/data/train/part-00031.parquet", cause: { name: "Error", message: "ENOENT: no such file or directory, open '/data/repos/dl-benchmark-2026/data/train/part-00031.parquet'", stack: "Error: ENOENT: no such file or directory, open '/data/repos/dl-benchmark-2026/data/train/part-00031.parquet'\n at async open (node:internal/fs/promises:639:25)\n at async FileSystem.read (/app/build/core/storage/FileSystem.js:58:22)\n at async AnonymizedFile.content (/app/build/core/AnonymizedFile.js:301:24)" } }],
|
||||
[0.05, "warn", "github", "GitHub API rate limit low", { name: "HttpError", message: "API rate limit exceeded for installation ID 41234567.", status: 403, url: "https://api.github.com/repos/bob-lab/graph-mining/git/trees/c40da900ab12?recursive=1", method: "GET" }],
|
||||
[0.1, "error", "download", "anonymous error", { name: "AnonymousError", message: "repository_too_big", httpStatus: 500, detail: JSON.stringify({ repoId: "dl-benchmark-2026", size: 12241827840, limit: 8589934592, fullName: "alice-research/dl-benchmark" }) }],
|
||||
[0.3, "error", "streamer", "anonymous error", { name: "AnonymousError", message: "file_not_found", httpStatus: 500, detail: "dl-benchmark-2026", url: "/api/repo/dl-benchmark-2026/file/data/train/part-00032.parquet" }],
|
||||
[0.4, "error", "api", "unhandled error", { name: "TypeError", message: "Cannot read properties of undefined (reading 'repositoryName')", stack: "TypeError: Cannot read properties of undefined (reading 'repositoryName')\n at Repository.toJSON (/app/build/core/Repository.js:1127:38)\n at JSON.stringify (<anonymous>)\n at ServerResponse.json (/app/node_modules/express/lib/response.js:263:14)\n at /app/build/server/routes/admin.js:912:17\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)" }],
|
||||
[0.8, "warn", "api", "anonymous error", { name: "AnonymousError", message: "invalid_terms_format", httpStatus: 400, url: "/api/repo/new-paper/", method: "POST", detail: "Terms must be an array of non-empty strings; received a single string of 2,048 characters containing newlines, which usually means the terms were pasted into the wrong field." }],
|
||||
[1.5, "error", "streamer", "anonymous error", { name: "AnonymousError", message: "file_not_found", httpStatus: 500, detail: "dl-benchmark-2026", url: "/api/repo/dl-benchmark-2026/file/README.md" }],
|
||||
[2, "error", "queue", "job failed", { name: "AnonymousError", message: "branch_not_found", httpStatus: 404, detail: "b4751b8e-6139-4a94-84f8-646106435809" }],
|
||||
[3.4, "warn", "mongo", "slow query", { name: "MongoServerSelectionError", message: "Server selection timed out after 30000 ms", code: "ETIMEDOUT" }],
|
||||
[5, "error", "storage", "s3 put failed", { name: "S3ServiceException", message: "SlowDown: Please reduce your request rate.", status: 503, url: "https://s3.eu-west-1.amazonaws.com/anon-cache/repos/graph-mining-A91B/src/main.py" }],
|
||||
[6, "warn", "github", "GitHub API rate limit low", { name: "HttpError", message: "API rate limit exceeded for installation ID 41234567.", status: 403, url: "https://api.github.com/repos/bob-lab/fuzz-harness", method: "GET" }],
|
||||
[9, "error", "api", "anonymous error", { name: "AnonymousError", message: "repository_expired", httpStatus: 410, detail: "JarSift", url: "/api/repo/JarSift/files" }],
|
||||
[14, "warn", "streamer", "client aborted", { name: "Error", message: "aborted", code: "ECONNRESET", url: "/api/repo/runtime-repair-experiments-very-long-identifier-for-the-icse-artifact-track-2ff4/zip" }],
|
||||
[20, "error", "api", "unhandled error", { name: "RangeError", message: "Maximum call stack size exceeded", stack: "RangeError: Maximum call stack size exceeded\n at anonymizeContent (/app/build/core/anonymize-utils.js:88:18)\n at anonymizeContent (/app/build/core/anonymize-utils.js:102:16)\n at anonymizeContent (/app/build/core/anonymize-utils.js:102:16)\n at anonymizeContent (/app/build/core/anonymize-utils.js:102:16)" }],
|
||||
[23, "warn", "conference", "billing webhook", { message: "Stripe webhook signature mismatch for event evt_1Q2w3E4r5T6y7U8i (conference ICSE26-AE)" }],
|
||||
[23.5, "error", "streamer", "anonymous error", { name: "AnonymousError", message: "file_not_found", httpStatus: 500, detail: "graph-mining-A91B", url: "/api/repo/graph-mining-A91B/file/docs/very/deeply/nested/folder/structure/that/keeps/going/and/going/index.html" }],
|
||||
].map(([hoursAgo, level, module, message, detail]) => ({
|
||||
ts: new Date(Date.now() - hoursAgo * HOUR).toISOString(),
|
||||
level,
|
||||
module,
|
||||
message,
|
||||
raw: [message, detail],
|
||||
}));
|
||||
// ---- Errors: synthetic records grouped by the real buildIssues() (scripts/fixtures/error-issues.js).
|
||||
// Cookie mock_errors=empty|offline|loading|history simulates the other states.
|
||||
const errorFixtures = require("./fixtures/error-issues");
|
||||
const errorFixture = errorFixtures.errorFixture({ repos: ["anonymous_github-C72C", "dl-benchmark-2026", "graph-mining-A91B", "smart-contract-audit"], users: [oid(1), oid(2)],
|
||||
owners: { "anonymous_github-C72C": oid(1), "dl-benchmark-2026": oid(2), "graph-mining-A91B": oid(3), "smart-contract-audit": oid(2) } });
|
||||
const errorEntries = errorFixtures.historyEntries(errorFixture);
|
||||
const errorScenario = (req) => (/(?:^|;\s*)mock_errors=(\w+)/.exec(req.headers.cookie || "") || [])[1] || "";
|
||||
const errorStats = (() => {
|
||||
const hourNow = Math.floor(Date.now() / HOUR) * HOUR;
|
||||
const buckets = Array.from({ length: 24 }, (_, i) => {
|
||||
@@ -996,6 +977,7 @@ app.get("/api/admin/repos", (req, res) => {
|
||||
rows = u ? rows.filter((r) => r.owner === u._id) : [];
|
||||
}
|
||||
if (req.query.conference) rows = rows.filter((r) => r.conference === req.query.conference);
|
||||
if (req.query.search) rows = rows.filter((r) => [r.repoId, r.source.repositoryName, r.conference].some((v) => String(v || "").toLowerCase().includes(String(req.query.search).toLowerCase())));
|
||||
res.json(page(req, rows, true));
|
||||
});
|
||||
app.get("/api/admin/repos/:repoId/github", (req, res) => {
|
||||
@@ -1017,12 +999,12 @@ app.get("/api/admin/users", (req, res) => {
|
||||
res.json(page(req, rows, false));
|
||||
});
|
||||
app.get("/api/admin/users/:username/repos", (req, res) => {
|
||||
const u = adminUsers.find((x) => x.username === req.params.username);
|
||||
const u = adminUsers.find((x) => x.username === req.params.username || x._id === req.params.username);
|
||||
if (!u) return res.status(404).json({ error: "user_not_found" });
|
||||
res.json(adminRepos.filter((r) => r.owner === u._id).map(repoView));
|
||||
});
|
||||
app.get("/api/admin/users/:username", (req, res) => {
|
||||
const u = adminUsers.find((x) => x.username === req.params.username);
|
||||
const u = adminUsers.find((x) => x.username === req.params.username || x._id === req.params.username);
|
||||
if (!u) return res.status(404).json({ error: "user_not_found" });
|
||||
res.json(Object.assign({}, u, { repositories: githubRepos(u) }));
|
||||
});
|
||||
@@ -1162,6 +1144,21 @@ app.get("/api/admin/emails", (req, res) => {
|
||||
res.json({ entries, nextCursor: rows.length > 50 ? `${last.createdAt}|${last._id}` : null });
|
||||
} catch { res.status(400).json({ error: "Invalid email history filters." }); }
|
||||
});
|
||||
app.use("/api/admin/errors", async (req, res, next) => {
|
||||
const scenario = errorScenario(req);
|
||||
if (scenario === "loading") await new Promise((resolve) => global.setTimeout(resolve, 20000));
|
||||
if (scenario === "offline") return res.status(503).json({ error: "Simulated outage" });
|
||||
next();
|
||||
});
|
||||
app.get("/api/admin/errors/issues", (req, res) => {
|
||||
const names = { repos: {}, users: {} };
|
||||
for (const u of adminUsers) names.users[u._id] = u.username;
|
||||
for (const r of adminRepos) names.repos[r.repoId] = { ownerId: r.owner, owner: names.users[r.owner], source: r.source.repositoryName, status: r.status };
|
||||
res.json(errorFixtures.issuesResponse(errorFixture, req.query, { scenario: errorScenario(req), names }));
|
||||
});
|
||||
app.get("/api/admin/errors/correlation", (req, res) => res.json(errorFixtures.correlationResponse(errorFixture, req.query)));
|
||||
app.get("/api/admin/errors/investigation", (req, res) => res.json({ state: "ready", window: req.query.window || "1h", groups: [], telemetry: { missing: [], streamers: 4, queues: 3, partial: false,
|
||||
instances: [{ service: "api", instance: "synthetic-api", last: new Date().toISOString(), dropped: 0 }, { service: "streamer", instance: "synthetic-streamer-1", last: new Date().toISOString(), dropped: 2 }], collector: { state: "reachable", dropped: 0 } } }));
|
||||
app.get("/api/admin/errors", (req, res) => {
|
||||
const offset = Math.max(0, parseInt(req.query.offset, 10) || 0);
|
||||
const limit = Math.min(5000, Math.max(1, parseInt(req.query.limit, 10) || 250));
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// Synthetic admin Errors fixtures, shared by scripts/dev-mock.js and
|
||||
// scripts/preview-errors.js. Generated records only: no production data.
|
||||
// The records have the shape the admin API returns after its projection
|
||||
// (src/server/admin-log-investigation.ts), so the mocks can group them with the
|
||||
// real buildIssues() and answer GET /api/admin/errors/issues like the server.
|
||||
require("ts-node/register/transpile-only");
|
||||
const { buildIssues, filterRows } = require("../../src/server/admin-error-issues");
|
||||
|
||||
const MIN = 60 * 1000;
|
||||
const uuid = (n) => `aaaaaaaa-aaaa-4aaa-8aaa-${String(n).padStart(12, "0")}`;
|
||||
const pick = (list, i) => list[i % list.length];
|
||||
|
||||
/**
|
||||
* @param {object} ids repository IDs and user _ids to attach, so admin links resolve in the mock
|
||||
* @param {number} now reference time (ms)
|
||||
*/
|
||||
function errorFixture({ repos, users, owners = {}, release = "4b2c1e9a7d", previous = "9e1d0a2c55", now = Date.now() }) {
|
||||
const at = (minutesAgo) => new Date(now - minutesAgo * MIN).toISOString();
|
||||
const records = [], external = [], traces = {};
|
||||
let n = 1;
|
||||
const add = (row, trace = []) => { records.push(row); if (row.requestId) traces[row.requestId] = [...trace, row]; return row; };
|
||||
|
||||
// 1. GitHub 502 incident on the file route: failing now, with external_request records (#990).
|
||||
for (let i = 0; i < 46; i++) {
|
||||
const requestId = uuid(n++);
|
||||
const minutesAgo = i < 30 ? i * 2.3 : 75 + i * 4;
|
||||
const repoId = pick(repos.slice(0, 4), i % 7 === 0 ? 3 : i % 3);
|
||||
const signedIn = i % 6 === 0;
|
||||
const end = now - minutesAgo * MIN;
|
||||
const ts = (ms) => new Date(end - 2412 + ms).toISOString();
|
||||
const calls = [0, 1, 2].map((attempt) => ({ timestamp: ts(40 + attempt * 760 + 620), service: "api", module: "external-request", event: "external_request", severity: "info",
|
||||
requestId, upstreamHost: "api.github.com", upstreamMethod: "GET", upstreamEndpoint: "/repos/{owner}/{repo}/contents/*", upstreamStatus: 502, ms: 600 + attempt * 50, release }));
|
||||
external.push(...calls);
|
||||
const base = { service: "api", module: "route", method: "GET", route: "/api/repo/:repoId/file/:path", repoId, requestId, release: i < 30 ? release : previous,
|
||||
requestPath: `/api/repo/${repoId}/file/${pick(["src/model.py", "README.md", "data/cfg.yaml", "eval.py"], i)}`,
|
||||
...(signedIn && owners[repoId] ? { viewer: "owner", userId: owners[repoId] } : { viewer: "visitor" }) };
|
||||
add({ ...base, timestamp: ts(2405), event: "application_log", severity: "error", errorCode: "upstream_error", errorType: "AnonymousError", status: 502 }, [
|
||||
{ timestamp: ts(2412), service: "nginx", module: "proxy", event: "edge_request", severity: "info", status: 502, ms: 2412, requestId, method: "GET", route: base.route, release: "unknown" },
|
||||
...calls,
|
||||
{ ...base, timestamp: ts(2410), event: "request_completed", severity: "info", status: 502, ms: 2398 },
|
||||
]);
|
||||
}
|
||||
|
||||
// 2. A 429 burst: answered from the app's remembered limit state in a few ms. Route names
|
||||
// the GitHub owner, so no repository ID is kept: the "not recorded" state.
|
||||
for (let i = 0; i < 34; i++) {
|
||||
add({ timestamp: at(380 + i * 0.6), service: "api", module: "route", event: "application_log", severity: "warn", errorCode: "github_rate_limit_exceeded",
|
||||
status: 429, method: "GET", route: "/api/repo/:owner/:repo", requestId: uuid(n++), ms: i % 11 === 0 ? 180 : 5 + (i % 9), release: previous });
|
||||
}
|
||||
|
||||
// 3. An internal TypeError with a stack, first seen in the newest release.
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const requestId = uuid(n++);
|
||||
add({ timestamp: at(8 + i * 17), service: "streamer", module: "zip-stream", event: "application_log", severity: "error", errorType: "TypeError",
|
||||
errorStack: "at ZipStream.entry (build/core/zipStream.js:212:31)\nat ZipStream.next (build/core/zipStream.js:188:12)\nat process.processTicksAndRejections (node:internal/process/task_queues:95:5)",
|
||||
causeType: "RangeError", causeStack: "at Archive.readEntry (build/core/archive-entry.js:44:9)",
|
||||
status: 500, method: "GET", route: "/api/repo/:repoId/zip", repoId: repos[1], requestId, requestPath: `/api/repo/${repos[1]}/zip`,
|
||||
viewer: "visitor", ms: 840 + i * 12, release });
|
||||
}
|
||||
|
||||
// 4. Storage failures with a storage external call.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const requestId = uuid(n++);
|
||||
external.push({ timestamp: at(120 + i * 30), service: "streamer", module: "external-request", event: "external_request", severity: "info", requestId,
|
||||
upstreamHost: "storage", upstreamMethod: "PUT", errorCode: "ECONNRESET", ms: 4100, release: previous });
|
||||
add({ timestamp: at(120 + i * 30), service: "streamer", module: "s3", event: "application_log", severity: "error", errorCode: "storage_write_size_mismatch",
|
||||
status: 500, method: "GET", route: "/api/repo/:repoId/file/:path", repoId: pick([repos[2], repos[0]], i), requestId, viewer: "visitor", ms: 4180, release: previous });
|
||||
}
|
||||
|
||||
// 5. Background job failures carry a job ID, repository and owner.
|
||||
for (let i = 0; i < 4; i++) {
|
||||
add({ timestamp: at(200 + i * 45), service: "worker", module: "queue", event: "job_failed", severity: "error", errorCode: "unable_to_download",
|
||||
queue: "download", jobId: uuid(n++), repoId: repos[3], userId: users[1], attempt: i + 1, ms: 30000, release: previous });
|
||||
}
|
||||
|
||||
// 6. An error with nothing else recorded: no route, no request ID, no stack.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
add({ timestamp: at(900 + i * 40), service: "api", module: "application", event: "application_log", severity: "error", status: 500, errorCode: "server_error", release: "unknown" });
|
||||
}
|
||||
|
||||
// 7. Expected 4xx: visitors asking for something gone or invalid.
|
||||
for (let i = 0; i < 48; i++) {
|
||||
const [code, status] = pick([["file_not_found", 404], ["repository_expired", 410], ["invalid_request", 400], ["repo_not_found", 404]], i);
|
||||
add({ timestamp: at(5 + i * 21), service: "api", module: "route", event: "application_log", severity: i % 3 ? "info" : "warn", errorCode: code, status,
|
||||
method: "GET", route: "/api/repo/:repoId/file/:path", repoId: pick(repos, i), requestId: uuid(n++), viewer: "visitor", release });
|
||||
}
|
||||
|
||||
// 8. Slow and interrupted requests: performance, not errors.
|
||||
for (let i = 0; i < 37; i++) {
|
||||
add({ timestamp: at(3 + i * 30), service: i % 2 ? "streamer" : "api", module: "requests", event: i % 4 ? "request_slow" : "request_cancelled", severity: "warn",
|
||||
status: 200, outcome: i % 4 ? "completed" : "interrupted", method: "GET", route: "/api/repo/:repoId/zip", requestId: uuid(n++), ms: 12000 + i * 100, release });
|
||||
}
|
||||
return { records, external, traces };
|
||||
}
|
||||
|
||||
const WINDOWS = { "15m": 15, "1h": 60, "6h": 360, "24h": 1440 };
|
||||
/** The /api/admin/errors/issues answer for a synthetic scenario. */
|
||||
function issuesResponse(fixture, query, { scenario = "", names = { repos: {}, users: {} }, now = Date.now() } = {}) {
|
||||
const window = WINDOWS[query.window] ? query.window : "24h";
|
||||
const start = new Date(now - WINDOWS[window] * MIN).toISOString(), end = new Date(now).toISOString();
|
||||
const history = query.source === "history" || scenario === "history";
|
||||
const rows = scenario === "empty" ? [] : filterRows(fixture.records, { service: query.service || "", repoId: query.repoId || "", userId: query.userId || "" });
|
||||
const built = buildIssues(history ? rows.filter((row) => row.severity !== "info") : rows, { start, end, external: history ? [] : fixture.external });
|
||||
return { source: history ? "history" : "central", state: rows.length ? "ready" : "empty", centralState: history ? (query.source === "history" ? "skipped" : "disabled") : "ready",
|
||||
grafanaUrl: history ? null : "https://grafana.example.test/d/synthetic", window, start, end,
|
||||
filters: { service: query.service || "", repoId: query.repoId || "", userId: query.userId || "" }, captured: rows.length, redisCollecting: true, ...built, names };
|
||||
}
|
||||
|
||||
/** The /api/admin/errors/correlation answer: every record with the request ID, in time order. */
|
||||
function correlationResponse(fixture, query) {
|
||||
const events = (fixture.traces[query.id] || []).slice().sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp));
|
||||
return { state: events.length ? "ready" : "empty", source: "victorialogs", events, limit: 200, grafanaUrl: "https://grafana.example.test/d/synthetic?var-request_id=" + query.id };
|
||||
}
|
||||
|
||||
/** Legacy Redis entries ({ ts, level, module, message, raw }) for export and the 24-hour counters. */
|
||||
function historyEntries(fixture) {
|
||||
return fixture.records.filter((row) => row.severity !== "info").map((row) => ({ ts: row.timestamp, level: row.severity, module: row.module,
|
||||
message: row.errorCode || row.errorType || row.event, raw: [row] }));
|
||||
}
|
||||
|
||||
module.exports = { errorFixture, issuesResponse, correlationResponse, historyEntries };
|
||||
+26
-30
@@ -1,41 +1,37 @@
|
||||
// Local synthetic fixtures only. No production proxy or credentials.
|
||||
// Run: node scripts/preview-errors.js, then /admin/errors?scenario=disabled|offline|empty|stale
|
||||
// Run: PORT=4173 node scripts/preview-errors.js, then open /admin/errors.
|
||||
// Add ?scenario=empty|offline|loading|history to any page to see the other states.
|
||||
const express = require('express');
|
||||
const fs = require('node:fs');
|
||||
const { setTimeout } = require('node:timers');
|
||||
const path = require('node:path');
|
||||
const { errorFixture, issuesResponse, correlationResponse, historyEntries } = require('./fixtures/error-issues');
|
||||
const app = express();
|
||||
let historyCleared = false;
|
||||
const root = path.resolve(__dirname, '../public');
|
||||
const id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
const port = Number(process.env.PORT) || 4173;
|
||||
const oid = n => '65f0c0de' + String(n).padStart(16, '0');
|
||||
const repos = ['neurips-2026-a91f', 'icse27-replication', 'anon-7c2e0b', 'eval-harness-3d1c'];
|
||||
const users = [oid(1), oid(2)];
|
||||
const names = { users: { [oid(1)]: 'alice-l', [oid(2)]: 'tmorris' }, repos: {} };
|
||||
repos.forEach((repoId, i) => { names.repos[repoId] = { ownerId: users[i % 2], owner: names.users[users[i % 2]], source: ['acme-lab/diffusion-bench', 'tmorris/flaky-tests', 'acme-lab/eval-harness', 'tmorris/eval'][i], status: 'ready' }; });
|
||||
const fixture = errorFixture({ repos, users, owners: Object.fromEntries(repos.map((repoId, i) => [repoId, users[i % 2]])) });
|
||||
let historyCleared = false;
|
||||
app.use('/api', async (req, res) => {
|
||||
const scenario = new URL(req.headers.referer || 'http://localhost').searchParams.get('scenario');
|
||||
if (scenario === 'loading') await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
const now = new Date().toISOString(), start = new Date(Date.now()-3600000).toISOString();
|
||||
if (req.path === '/user') return res.json({username:'Synthetic preview',isAdmin:true,status:'ready'});
|
||||
if (req.path === '/user/default') return res.json({options:{},terms:[]});
|
||||
if (req.path === '/admin/emails/summary') return res.json({total:2,counts:{accepted:1,rejected:1,unknown:0,sending:0},chartDays:7,series:[{date:now.slice(0,10),accepted:1,rejected:1,unknown:0,sending:0}]});
|
||||
if (req.path === '/admin/emails') return res.json({entries:[{_id:'synthetic-attempt',recipient:'fixture@example.test',kind:'repository-expiration',state:'rejected',createdAt:now,httpStatus:503}],nextCursor:null});
|
||||
if (req.path === '/admin/billing/summary') return res.json({period:'30d',bucket:'day',subscriptions:{active:3,monthly:2,annual:1,cancelling:0,mrr:{eur:1400}},sales:{count:4,revenue:{eur:3000}},allTime:{count:9,revenue:{eur:5000}},reversals:{refunds:0,disputes:0,amount:{}},plans:[],series:[{date:now,subscription:1,repository:2,conference:1}],revenue:{available:true,missingSales:0},webhooks:{pending:0,failed:0}});
|
||||
if (req.path === '/admin/billing/grants') return res.json({results:[],total:0,stateCounts:{active:0,expired:0,revoked:0},statuses:[]});
|
||||
const scenario = new URL(req.headers.referer || 'http://localhost').searchParams.get('scenario') || '';
|
||||
if (scenario === 'loading') await new Promise(resolve => setTimeout(resolve, 20000));
|
||||
const now = new Date().toISOString();
|
||||
if (req.path === '/user') return res.json({ username: 'Synthetic preview', isAdmin: true, status: 'ready' });
|
||||
if (req.path === '/user/default') return res.json({ options: {}, terms: [] });
|
||||
if (scenario === 'offline' && req.path.startsWith('/admin/errors')) return res.status(503).json({});
|
||||
let samples = [
|
||||
{service:'worker',module:'queue',event:'job_failed',errorCode:'upstream_error',severity:'error',status:502,jobId:id,requestId:id},
|
||||
{service:'nginx',module:'proxy',event:'edge_request',severity:'info',status:504,requestId:id},
|
||||
{service:'streamer',module:'download',event:'request_aborted',severity:'warn',requestId:id},
|
||||
{service:'api',module:'route',event:'request_failed',errorCode:'repository_unavailable',severity:'error',status:503,requestId:id},
|
||||
];
|
||||
if (scenario === 'diagnostics') samples = [{service:'api',module:'route',event:'application_log',severity:'error',httpStatus:500,requestId:id,method:'GET',route:'/api/repo/:repoId/file/:path',repoId:'demo-123',requestPath:'/api/repo/demo-123/file/docs/reproduce%20issue.md',errorType:'TypeError',errorStack:'at printError (build/server/routes/route-utils.js:200:7)\nat <anonymous> (build/server/routes/repository-public.js:312:11)',causeType:'RangeError',causeStack:'at <anonymous> (build/core/repository.js:410:9)'},{service:'api',module:'requests',event:'request_completed',severity:'info',status:500,requestId:id,method:'GET',route:'/api/repo/:repoId/file/:path',ms:283}];
|
||||
if (scenario === 'occurrences') samples = Array.from({length:50}, (_,i) => ({service:'api',module:'route',event:'application_log',severity:'error',httpStatus:500,requestId:id,...(i%2?{method:'GET',route:'/api/repo/:repoId/file/:path'}:{})}));
|
||||
if (scenario === 'many') samples = Array.from({length:50}, (_,i) => ({...samples[i%4],errorCode:'synthetic_event_'+(i+1)}));
|
||||
if (req.path === '/admin/errors/investigation') return res.json({state:scenario === 'unreachable' ? 'unreachable' : scenario === 'disabled' ? 'disabled' : scenario === 'empty' ? 'empty':'ready',window:req.query.window||'1h',start,end:scenario==='stale'?start:now,captured:['disabled','unreachable','empty'].includes(scenario)?0:samples.reduce((sum,_,i)=>sum+[18,9,5,2][i%4],0),groups:['disabled','unreachable','empty'].includes(scenario)?[]:samples.map((sample,i)=>({fingerprint:String(i),sample:{...sample,release:'abcdef1234567'},count:[18,9,5,2][i%4],first:start,last:now})),telemetry:{missing:[],instances:[{service:'api',instance:'synthetic-api',last:now,dropped:0}],collector:{state:'reachable',dropped:0}}});
|
||||
if (req.path === '/admin/errors/correlation') return res.json({state:'ready',start,end:now,events:samples.map(sample=>({...sample,timestamp:now}))});
|
||||
if (req.path === '/admin/errors/stats') return res.json({available:true,last24h:34,prev24h:20,severity:{error:29,warn:5,info:0},unique:{error:3,warn:1,info:0},buckets:[],dropped:0});
|
||||
if (req.path === '/admin/errors' && req.method === 'DELETE') historyCleared = true;
|
||||
if (req.path === '/admin/errors') return res.json({available:true,redisCollecting:true,total:historyCleared?0:samples.length,max:1000,entries:historyCleared?[]:samples.map((sample,i)=>({ts:scenario==='occurrences'?new Date(Date.now()-i*11000).toISOString():now,level:sample.severity,module:sample.module,message:sample.errorCode||sample.errorType||sample.event,count:i+1,raw:[sample]}))});
|
||||
if (req.path === '/admin/errors/issues') return res.json(issuesResponse(fixture, req.query, { scenario, names }));
|
||||
if (req.path === '/admin/errors/correlation') return res.json(correlationResponse(fixture, req.query));
|
||||
if (req.path === '/admin/errors/investigation') return res.json({ state: 'ready', window: req.query.window || '1h', groups: [], telemetry: { missing: [], instances: [{ service: 'api', instance: 'synthetic-api', last: now, dropped: 0 }], collector: { state: 'reachable', dropped: 0 } } });
|
||||
if (req.path === '/admin/errors/stats') return res.json({ available: true, last24h: 34, prev24h: 20, severity: { error: 29, warn: 5, info: 0 }, unique: { error: 3, warn: 1, info: 0 }, buckets: [], dropped: 0 });
|
||||
if (req.path === '/admin/errors' && req.method === 'DELETE') { historyCleared = true; return res.json({ ok: true }); }
|
||||
if (req.path === '/admin/errors') { const entries = historyCleared ? [] : historyEntries(fixture); return res.json({ available: true, redisCollecting: true, total: entries.length, max: 5000, entries }); }
|
||||
return res.json([]);
|
||||
});
|
||||
app.use((req,res,next)=>{ req.url=req.url.replace(/\.[a-f0-9]{10}\.min\./,'.min.'); next(); });
|
||||
app.use(express.static(root,{index:false}));
|
||||
app.get('/{*path}', (req,res)=>res.type('html').send(fs.readFileSync(path.join(root,'index.html'),'utf8').replace(/__([A-Z]+)_JS__/g,(_,name)=>`${name.toLowerCase()}.min.js`).replace('__ALL_CSS__','all.min.css').replace('<body ', '<body data-synthetic-preview="true" ').replace('<div id="app"', '<div style="padding:6px 16px;background:#fff3cd;color:#493800;text-align:center;font:13px sans-serif">Synthetic preview · generated fixtures only · no production connection</div><div id="app"')));
|
||||
app.listen(4173,'0.0.0.0',()=>console.log('Synthetic Errors preview: http://localhost:4173/admin/errors'));
|
||||
app.use((req, res, next) => { req.url = req.url.replace(/\.[a-f0-9]{10}\.min\./, '.min.'); next(); });
|
||||
app.use(express.static(root, { index: false }));
|
||||
app.get('/{*path}', (req, res) => res.type('html').send(fs.readFileSync(path.join(root, 'index.html'), 'utf8').replace(/__([A-Z]+)_JS__/g, (_, name) => `${name.toLowerCase()}.min.js`).replace('__ALL_CSS__', 'all.min.css').replace('<body ', '<body data-synthetic-preview="true" ').replace('<div id="app"', '<div style="padding:6px 16px;background:#fff3cd;color:#493800;text-align:center;font:13px sans-serif">Synthetic preview · generated fixtures only · no production connection</div><div id="app"')));
|
||||
app.listen(port, '127.0.0.1', () => console.log(`Synthetic Errors preview: http://localhost:${port}/admin/errors`));
|
||||
@@ -7,7 +7,8 @@ const { execFileSync } = require('node:child_process');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const assert = require('node:assert/strict');
|
||||
const { investigateLogs, logOptions } = require('../src/server/admin-log-investigation');
|
||||
const { investigateLogs, logOptions, issueRecords } = require('../src/server/admin-log-investigation');
|
||||
const { buildIssues } = require('../src/server/admin-error-issues');
|
||||
const name = 'admin-logs-test-' + randomUUID().slice(0,8);
|
||||
const image = fs.readFileSync('deploy/logging/compose.yml','utf8').match(/image: (victoriametrics\/victoria-logs:[^\s]+)/)[1];
|
||||
const docker = (...args) => execFileSync('docker', args, {encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();
|
||||
@@ -32,6 +33,18 @@ const sleep = ms => new Promise(resolve=>setTimeout(resolve,ms));
|
||||
const timeline=await investigateLogs(logOptions({kind:'jobId',id:jobId},true),true);
|
||||
assert.equal(timeline.state,'ready'); assert.deepEqual([...new Set(timeline.events.map(row=>row.service))].sort(),['api','streamer','worker']);
|
||||
console.log('PASS real filtered grouping, privacy projection and job→request cross-service correlation');
|
||||
// Issue list queries: identity filter, failed external calls and the slow/interrupted counts are valid LogsQL.
|
||||
const issueId=randomUUID(), now=Date.now();
|
||||
const issueRows=[{timestamp:new Date(now-3000).toISOString(),severity:'error',service:'api',event:'application_log',module:'route',errorCode:'upstream_error',status:502,release:'fedcba9',requestId:issueId,repoId:'issue-repo',route:'/api/repo/:repoId/file/:path'},
|
||||
{timestamp:new Date(now-3100).toISOString(),severity:'info',service:'api',event:'external_request',module:'external-request',requestId:issueId,upstreamHost:'api.github.com',upstreamStatus:502,ms:600,release:'fedcba9'},
|
||||
{timestamp:new Date(now-3200).toISOString(),severity:'warn',service:'api',event:'request_slow',module:'requests',status:200,requestId:randomUUID(),repoId:'issue-repo',release:'fedcba9'},
|
||||
{timestamp:new Date(now-3300).toISOString(),severity:'info',service:'api',event:'application_log',module:'route',errorCode:'file_not_found',status:404,repoId:'issue-repo',release:'fedcba9'}];
|
||||
assert((await fetch(process.env.ADMIN_LOG_URL+'/insert/jsonline?_time_field=timestamp',{method:'POST',body:issueRows.map(JSON.stringify).join('\n'),headers:{'Content-Type':'application/stream+json'}})).ok); await sleep(2000);
|
||||
const issueSource=await issueRecords({window:'1h',start:new Date(now-3600000).toISOString(),end:new Date().toISOString(),service:'',repoId:'issue-repo',userId:''});
|
||||
assert.equal(issueSource.state,'ready'); assert.deepEqual(issueSource.noise,{slow:1,interrupted:0}); assert.equal(issueSource.external.length,1);
|
||||
const issueList=buildIssues(issueSource.records,{start:issueSource.start,end:issueSource.end,external:issueSource.external});
|
||||
assert.equal(issueList.issues.length,1); assert.equal(issueList.issues[0].cause.source,'github'); assert.equal(issueList.expected.count,1);
|
||||
console.log('PASS issue list: repoId filter, external calls, expected responses and noise counts');
|
||||
// Run the deployed collector program in its pinned Vector image, then ingest
|
||||
// its real output alongside historical absent/explicit-unknown releases.
|
||||
const vectorImage = fs.readFileSync('deploy/logging/compose.yml','utf8').match(/image: (timberio\/vector:[^\s]+)/)[1];
|
||||
|
||||
Reference in new issue
Block a user