mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
- An issue is now one error code (or exception type) per service: one cause,
such as a rate-limit burst, hits many routes. Rows show the most frequent
route and "+N routes"; the issue page lists them with a count and a bar.
- The request header shows the viewer as a role ("Viewer: owner", "Viewer not
signed in") beside the owner chip, with a user link only for another user.
- List meta parts no longer leave a lone separator when they wrap.
- The issue page shows the 10 latest occurrences and a "Show all" button
instead of clipping the list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
205 lines
15 KiB
JavaScript
205 lines
15 KiB
JavaScript
const { expect } = require('chai');
|
||
const { Response, fetch } = globalThis;
|
||
require('ts-node/register/transpile-only');
|
||
const { buildIssues, deriveCause, recordKind, issueOptions, filterRows, issueId } = require('../src/server/admin-error-issues');
|
||
const { issueRecords, logOptions, investigateLogs } = require('../src/server/admin-log-investigation');
|
||
|
||
const NOW = Date.parse('2026-11-29T12:00:00Z');
|
||
const at = minutes => new Date(NOW - minutes * 60000).toISOString();
|
||
const rid = n => `aaaaaaaa-aaaa-4aaa-8aaa-${String(n).padStart(12, '0')}`;
|
||
const USER = '65f0c0de0000000000000001';
|
||
const window = { start: at(1440), end: at(0) };
|
||
const fault = extra => ({ timestamp: at(5), service: 'api', module: 'route', event: 'application_log', severity: 'error', errorCode: 'upstream_error', status: 502,
|
||
method: 'GET', route: '/api/repo/:repoId/file/:path', release: 'abcdef1', ...extra });
|
||
|
||
describe('admin error issues', () => {
|
||
describe('grouping', () => {
|
||
it('groups by code and service, and counts requests, repositories, users and viewers', () => {
|
||
const rows = [
|
||
fault({ requestId: rid(1), repoId: 'repo-one', viewer: 'visitor' }),
|
||
fault({ requestId: rid(2), repoId: 'repo-one', viewer: 'owner', userId: USER, timestamp: at(30) }),
|
||
fault({ requestId: rid(3), repoId: 'repo-two', viewer: 'visitor', timestamp: at(60) }),
|
||
fault({ requestId: rid(5), service: 'streamer' }),
|
||
fault({ requestId: rid(6), errorCode: undefined, errorType: 'TypeError', status: 500 }),
|
||
];
|
||
const { issues, summary } = buildIssues(rows, window);
|
||
expect(issues).to.have.length(3);
|
||
const file = issues.find(issue => issue.code === 'upstream_error' && issue.service === 'api');
|
||
expect(file).to.include({ count: 3, requests: 3, repoCount: 2, userCount: 1, title: 'GitHub returned an error', failingNow: true, routeCount: 1, route: '/api/repo/:repoId/file/:path' });
|
||
expect(file.repos[0]).to.include({ id: 'repo-one', count: 2 });
|
||
expect(file.viewers).to.deep.equal({ signedIn: 1, visitors: 2, notRecorded: 0 });
|
||
expect(file.occurrences.map(o => o.requestId)).to.deep.equal([rid(1), rid(2), rid(3)]);
|
||
expect(file.trend.reduce((a, b) => a + b, 0)).to.equal(3);
|
||
expect(issues.find(issue => issue.code === 'TypeError').title).to.equal('Code crashed: TypeError');
|
||
expect(summary).to.include({ issues: 3, failingNow: 3, failedRecords: 5, repositories: 2, users: 1 });
|
||
expect(issueId(rows[0])).to.equal(file.id);
|
||
});
|
||
|
||
it('keeps one cause across routes in one issue and lists its routes, most frequent first', () => {
|
||
const routes = ['/api/user/all_repositories', '/api/repo/:owner/:repo', '/api/repo/:owner/:repo/readme', '/api/gist/source/:id', '/api/pr/:owner/:repo/:id'];
|
||
const limited = Array.from({ length: 102 }, (_, i) => fault({ requestId: rid(i), errorCode: 'github_rate_limit_exceeded', status: 429, severity: 'warn', ms: 7,
|
||
route: routes[i < 28 ? 0 : i < 53 ? 1 : i < 78 ? 2 : i < 90 ? 3 : 4], timestamp: at(30 + i * 0.3) }));
|
||
const other = fault({ requestId: rid(500), errorCode: 'upstream_error', route: routes[0] });
|
||
const { issues } = buildIssues([...limited, other], window);
|
||
expect(issues).to.have.length(2);
|
||
const limit = issues.find(issue => issue.code === 'github_rate_limit_exceeded');
|
||
expect(limit).to.include({ count: 102, routeCount: 5, route: '/api/user/all_repositories', method: 'GET' });
|
||
expect(limit.routes.map(route => route.count)).to.deep.equal([28, 25, 25, 12, 12]);
|
||
expect(limit.id).to.equal(issueId({ errorCode: 'github_rate_limit_exceeded', service: 'api', route: '/anything/else' }));
|
||
expect(issues.find(issue => issue.code === 'upstream_error').id).to.not.equal(limit.id);
|
||
});
|
||
|
||
it('drops request envelopes already described by a more specific record, keeps lone edge 5xx', () => {
|
||
const rows = [
|
||
fault({ requestId: rid(1) }),
|
||
{ timestamp: at(5), service: 'nginx', event: 'edge_request', severity: 'info', status: 502, requestId: rid(1) },
|
||
{ timestamp: at(9), service: 'nginx', event: 'edge_request', severity: 'info', status: 504, requestId: rid(2) },
|
||
];
|
||
const { issues } = buildIssues(rows, window);
|
||
expect(issues.map(issue => issue.title).sort()).to.deep.equal(['Edge proxy returned 504', 'GitHub returned an error']);
|
||
});
|
||
|
||
it('marks an issue new in the newest release only when older releases appear in the window', () => {
|
||
const rows = [fault({ release: 'abcdef1', timestamp: at(100) }), fault({ errorCode: 'storage_write_size_mismatch', status: 500, release: 'bbbbbb2', timestamp: at(2) })];
|
||
const issues = buildIssues(rows, window).issues;
|
||
expect(issues.find(i => i.code === 'storage_write_size_mismatch').newInRelease).to.equal('bbbbbb2');
|
||
expect(issues.find(i => i.code === 'upstream_error').newInRelease).to.equal(null);
|
||
expect(buildIssues([fault({})], window).issues[0].newInRelease).to.equal(null);
|
||
});
|
||
});
|
||
|
||
describe('noise split', () => {
|
||
it('keeps slow and interrupted requests and expected 4xx out of the issues', () => {
|
||
expect(recordKind({ event: 'request_slow', severity: 'warn', status: 200 })).to.equal('slow');
|
||
expect(recordKind({ event: 'request_cancelled', severity: 'warn' })).to.equal('interrupted');
|
||
expect(recordKind({ event: 'request_completed', outcome: 'interrupted', status: 500 })).to.equal('interrupted');
|
||
expect(recordKind({ event: 'application_log', severity: 'warn', status: 404, errorCode: 'file_not_found' })).to.equal('expected');
|
||
expect(recordKind({ event: 'application_log', severity: 'warn', status: 400, errorCode: 'invalid_request' })).to.equal('expected');
|
||
expect(recordKind({ event: 'application_log', severity: 'info', errorCode: 'repository_expired' })).to.equal('expected');
|
||
expect(recordKind({ event: 'application_log', severity: 'warn', status: 429, errorCode: 'github_rate_limit_exceeded' })).to.equal('issue');
|
||
expect(recordKind({ event: 'external_request', severity: 'info', upstreamStatus: 502 })).to.equal('external');
|
||
expect(recordKind({ event: 'process_heartbeat', severity: 'info' })).to.equal('ignored');
|
||
const rows = [fault({}), fault({ event: 'request_slow', severity: 'warn', status: 200 }), fault({ event: 'request_cancelled', severity: 'warn' }),
|
||
fault({ errorCode: 'file_not_found', status: 404, severity: 'info' }), fault({ errorCode: 'file_not_found', status: 404, severity: 'warn' }), fault({ errorCode: 'invalid_request', status: 400, severity: 'warn' })];
|
||
const built = buildIssues(rows, window);
|
||
expect(built.issues).to.have.length(1);
|
||
expect(built.excluded).to.deep.equal({ slow: 1, interrupted: 1 });
|
||
expect(built.expected.count).to.equal(3);
|
||
expect(built.expected.groups[0]).to.include({ code: 'file_not_found', status: 404, count: 2 });
|
||
});
|
||
|
||
it('ignores records outside the window', () => {
|
||
expect(buildIssues([fault({ timestamp: at(2000) })], window).issues).to.have.length(0);
|
||
});
|
||
});
|
||
|
||
describe('cause derivation', () => {
|
||
it('names the failing GitHub endpoint from external_request records of the same requests', () => {
|
||
const rows = [fault({ requestId: rid(1) }), fault({ requestId: rid(2) })];
|
||
const call = n => ({ event: 'external_request', requestId: rid(n), upstreamHost: 'api.github.com', upstreamMethod: 'GET', upstreamEndpoint: '/repos/{owner}/{repo}/contents/*', upstreamStatus: 502 });
|
||
const cause = deriveCause(rows, [call(1), call(1), call(1), call(2), call(2), call(2), { ...call(9), upstreamStatus: 500 }]);
|
||
expect(cause).to.include({ source: 'github', label: 'GitHub', summary: 'GitHub answered 502 on GET /repos/{owner}/{repo}/contents/* in 2 of 2 failures.' });
|
||
expect(cause.detail).to.include('Retries (3 calls per request) also failed');
|
||
});
|
||
|
||
it('recognizes storage and connection failures of external calls', () => {
|
||
const cause = deriveCause([fault({ requestId: rid(1), errorCode: 'storage_write_size_mismatch' })], [{ event: 'external_request', requestId: rid(1), upstreamHost: 'storage', errorCode: 'ECONNRESET' }]);
|
||
expect(cause).to.include({ source: 'storage', summary: 'Storage failed with ECONNRESET in 1 of 1 failures.' });
|
||
});
|
||
|
||
it('reads fast 429s as the app answering from its remembered limit state', () => {
|
||
const rows = [5, 7, 9, 180].map((ms, i) => fault({ requestId: rid(i), errorCode: 'github_rate_limit_exceeded', status: 429, severity: 'warn', ms }));
|
||
const cause = deriveCause(rows);
|
||
expect(cause).to.include({ source: 'limit', summary: '3 of 4 requests returned 429 in under 20 ms.' });
|
||
expect(cause.detail).to.include('without calling GitHub');
|
||
expect(deriveCause(rows.map(row => ({ ...row, ms: 900 }))).summary).to.include('rate limit');
|
||
});
|
||
|
||
it('points at our code with the first application frame', () => {
|
||
const cause = deriveCause([fault({ errorCode: undefined, errorType: 'TypeError', errorStack: 'at ZipStream.entry (build/core/zipStream.js:212:31)\nat next (build/core/zipStream.js:188:12)', causeType: 'RangeError' })]);
|
||
expect(cause).to.include({ source: 'code', summary: 'TypeError thrown at zipStream.js:212.', detail: 'Caused by RangeError.' });
|
||
});
|
||
|
||
it('says plainly when nothing is known', () => {
|
||
const cause = deriveCause([{ timestamp: at(1), service: 'api', event: 'application_log', severity: 'error', status: 500, errorCode: 'server_error' }]);
|
||
expect(cause.source).to.equal('unknown');
|
||
expect(cause.summary).to.match(/^No cause recorded/);
|
||
expect(deriveCause([fault({ ms: 4800 }), fault({ ms: 500 })]).summary).to.include('waited 500 ms – 4.8 s');
|
||
});
|
||
});
|
||
|
||
describe('repoId and userId filters', () => {
|
||
it('validates the query and rejects anything else', () => {
|
||
const ok = issueOptions({ window: '6h', service: 'api', repoId: 'repo-one', userId: USER, source: 'history' }, NOW);
|
||
expect(ok).to.include({ window: '6h', repoId: 'repo-one', userId: USER, source: 'history', end: at(0) });
|
||
expect(issueOptions({}, NOW)).to.include({ window: '24h', source: 'auto' });
|
||
for (const query of [{ repoId: 'a" OR *' }, { repoId: 'x' }, { userId: 'alice' }, { userId: [USER] }, { window: '7d' }, { source: 'central' }, { q: '*' }, { service: 'api OR *' }]) {
|
||
expect(() => issueOptions(query), JSON.stringify(query)).to.throw();
|
||
}
|
||
expect(() => logOptions({ repoId: 'repo-one', userId: USER })).not.to.throw();
|
||
expect(() => logOptions({ repoId: 'a"b' })).to.throw();
|
||
});
|
||
|
||
it('filters rows by repository, user and service', () => {
|
||
const rows = [fault({ repoId: 'repo-one' }), fault({ repoId: 'repo-two', userId: USER }), fault({ repoId: 'repo-one', service: 'streamer' })];
|
||
expect(filterRows(rows, { repoId: 'repo-one', userId: '', service: '' })).to.have.length(2);
|
||
expect(filterRows(rows, { repoId: '', userId: USER, service: '' })).to.have.length(1);
|
||
expect(filterRows(rows, { repoId: 'repo-one', userId: '', service: 'api' })).to.have.length(1);
|
||
});
|
||
|
||
describe('central queries', () => {
|
||
let saved, originalFetch, queries;
|
||
beforeEach(() => { saved = process.env.ADMIN_LOG_URL; originalFetch = global.fetch; queries = []; process.env.ADMIN_LOG_URL = 'http://logging.test'; });
|
||
afterEach(() => { global.fetch = originalFetch; if (saved === undefined) delete process.env.ADMIN_LOG_URL; else process.env.ADMIN_LOG_URL = saved; });
|
||
|
||
it('adds validated repoId and userId terms, counts noise and keeps it out of the fault query', async () => {
|
||
global.fetch = async (url, options) => {
|
||
const query = options.body.get('query'); queries.push(query);
|
||
if (query.includes('stats by (event)')) return new Response('{"event":"request_slow","n":"12"}\n{"event":"request_cancelled","n":"3"}\n');
|
||
if (query.includes('event:external_request (')) return new Response(JSON.stringify({ _time: at(1), event: 'external_request', severity: 'info', service: 'api', requestId: rid(1), upstreamHost: 'api.github.com', upstreamStatus: '502', upstreamMethod: 'GET' }) + '\n');
|
||
if (query.includes('severity:info')) return new Response('');
|
||
return new Response(JSON.stringify({ _time: at(1), ...fault({ requestId: rid(1), repoId: 'repo-one', userId: USER, viewer: 'owner' }), status: '502' }) + '\n');
|
||
};
|
||
const result = await issueRecords({ window: '24h', start: at(1440), end: at(0), service: 'api', repoId: 'repo-one', userId: USER });
|
||
expect(result.state).to.equal('ready');
|
||
expect(result.noise).to.deep.equal({ slow: 12, interrupted: 3 });
|
||
expect(result.external[0]).to.include({ event: 'external_request', upstreamHost: 'api.github.com', upstreamStatus: 502 });
|
||
const faults = queries.find(q => q.includes('severity:error'));
|
||
expect(faults).to.include('service:api repoId:"repo-one" userId:"' + USER + '"').and.include('NOT (event:request_slow OR event:request_cancelled)');
|
||
expect(result.records[0]).to.include({ repoId: 'repo-one', userId: USER, viewer: 'owner' });
|
||
const investigation = await investigateLogs(logOptions({ repoId: 'repo-one' }));
|
||
expect(investigation.state).to.not.equal('misconfigured');
|
||
expect(queries.at(-1) + queries.at(-2) + queries.at(-3)).to.include('repoId:"repo-one"');
|
||
});
|
||
|
||
it('reports disabled central logs without backend calls', async () => {
|
||
delete process.env.ADMIN_LOG_URL;
|
||
global.fetch = async () => { throw new Error('no call expected'); };
|
||
expect((await issueRecords({ window: '1h', start: at(60), end: at(0), service: '', repoId: '', userId: '' })).state).to.equal('disabled');
|
||
});
|
||
});
|
||
|
||
it('serves issues only to admins and validates filters on the route', async () => {
|
||
const express = require('express');
|
||
const utils = require('../src/server/routes/route-utils');
|
||
const previous = utils.getUser, savedUrl = process.env.ADMIN_LOG_URL;
|
||
delete process.env.ADMIN_LOG_URL;
|
||
utils.getUser = async req => ({ id: 'fixture', model: { id: 'fixture' }, isAdmin: req.headers['x-admin'] === 'yes' });
|
||
const app = express(); app.use((req, res, next) => { req.isAuthenticated = () => req.headers['x-login'] === 'yes'; next(); });
|
||
app.use('/api/admin', require('../src/server/routes/admin').default);
|
||
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
|
||
const address = `http://127.0.0.1:${server.address().port}/api/admin/errors/issues`;
|
||
const admin = { headers: { 'x-login': 'yes', 'x-admin': 'yes' } };
|
||
try {
|
||
expect((await fetch(address)).status).to.equal(401);
|
||
expect((await fetch(address, { headers: { 'x-login': 'yes' } })).status).to.equal(401);
|
||
expect((await fetch(address + '?repoId=a%22%20OR%20*', admin)).status).to.equal(400);
|
||
expect((await fetch(address + '?userId=alice', admin)).status).to.equal(400);
|
||
} finally {
|
||
utils.getUser = previous; if (savedUrl !== undefined) process.env.ADMIN_LOG_URL = savedUrl;
|
||
await new Promise(resolve => server.close(resolve));
|
||
}
|
||
});
|
||
});
|
||
});
|