Files
anonymous_github/scripts/generate-log-diagnostics.js
T
Thomas DurieuxandClaude Opus 5.5 3f8812c99e fix(logging): give raw GitHub failures an error code, log missing branches as warnings
Overnight, GitHub refusals reached the logs as bare HTTPError/UnknownError
with no code: a ZIP whose archive request was refused became a cut
connection and a 502 zip_not_available, a 401 while checking a file
became an uncoded 401, and an Octokit 403 on /options answered
internal_error.

- codeUpstreamError maps got/Octokit replies to repo_not_accessible,
  github_rate_limit_exceeded, github_unavailable or upstream_error;
  handleError applies it, the streamer file route uses the file-level
  mapping, and programming errors pass through unchanged.
- A ZIP that fails before any byte answers with the code, so the API
  relays it; 4xx archive refusals log at warn.
- branch_not_found (owner deleted the branch) logs at warn.
- Octokit's HttpError is an allowlisted error type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:52:23 +00:00

70 lines
5.2 KiB
JavaScript

// Generate finite diagnostic allowlists from repository code, never runtime input.
const fs = require('fs'), path = require('path'), ts = require('typescript');
const files = {};
// Error codes the code base throws or relays, so the logger and the collector
// keep them as errorCode instead of dropping them as arbitrary strings.
const codePattern = /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/;
const errorFactories = new Set(['AnonymousError','billingError','appError']);
const thrownCodes = new Set();
function codeLiterals(node) {
if (!node) return;
if (ts.isStringLiteralLike(node)) { if (codePattern.test(node.text)) thrownCodes.add(node.text); }
else if (ts.isConditionalExpression(node)) { codeLiterals(node.whenTrue); codeLiterals(node.whenFalse); }
else if (ts.isBinaryExpression(node) && [ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(node.operatorToken.kind)) { codeLiterals(node.left); codeLiterals(node.right); }
else if (ts.isParenthesizedExpression(node)) codeLiterals(node.expression);
}
function scan(dir) {
for (const entry of fs.readdirSync(dir, {withFileTypes:true})) {
const file = path.join(dir,entry.name);
if(entry.isDirectory()) scan(file);
else if(file.endsWith('.ts') && !file.endsWith('.d.ts') && !file.endsWith('log-diagnostic-schema.ts')) {
const source=ts.createSourceFile(file,fs.readFileSync(file,'utf8'),ts.ScriptTarget.Latest,true);
const names=new Set(['<anonymous>']);
function visit(node) {
if ((ts.isFunctionDeclaration(node)||ts.isMethodDeclaration(node)||ts.isFunctionExpression(node)) && node.name && ts.isIdentifier(node.name)) names.add(node.name.text);
if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&(ts.isArrowFunction(node.initializer)||ts.isFunctionExpression(node.initializer))) names.add(node.name.text);
// new AnonymousError("code"), billingError("code"), appError("code")
if((ts.isNewExpression(node)||ts.isCallExpression(node))&&ts.isIdentifier(node.expression)&&errorFactories.has(node.expression.text)&&node.arguments?.length) codeLiterals(node.arguments[0]);
// Codes picked into a variable first: errCode = "streamer_unreachable"
if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&/^(errCode|code)$/.test(node.name.text)) codeLiterals(node.initializer);
if(ts.isBinaryExpression(node)&&node.operatorToken.kind===ts.SyntaxKind.EqualsToken&&ts.isIdentifier(node.left)&&/^(errCode|code)$/.test(node.left.text)) codeLiterals(node.right);
ts.forEachChild(node,visit);
}
visit(source);
files[file]=[...names].sort();
files[file.replace(/^src\//,'build/').replace(/\.ts$/,'.js')]=files[file];
}
}
}
scan('src');
const types=['Error','TypeError','RangeError','ReferenceError','SyntaxError','URIError','EvalError','AggregateError','AnonymousError','HTTPError','HttpError','RequestError','MongoServerError','MongoNetworkError','MongoServerSelectionError','ValidationError','TimeoutError','AbortError','UnknownError'];
const vrl=fs.readFileSync('deploy/logging/sanitize.vrl','utf8');
const routes=JSON.parse(vrl.match(/if includes\((\[.*?\]), record.route\)/)[1]);
const codes=[...thrownCodes].sort();
fs.writeFileSync('src/core/log-diagnostic-schema.ts','// Generated by scripts/generate-log-diagnostics.js; do not edit.\nexport const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = '+JSON.stringify(files,null,2)+';\nexport const LOG_ERROR_TYPES = '+JSON.stringify(types)+';\nexport const LOG_ROUTES = '+JSON.stringify(routes)+';\nexport const LOG_THROWN_ERROR_CODES = '+JSON.stringify(codes)+';\n');
// The collector keeps reviewed codes too (system errnos, worker codes); only add.
const codeList=/(if includes\()(\[.*?\])(, record\.errorCode\))/;
const collectorCodes=JSON.parse(vrl.match(codeList)[2]);
const mergedCodes=[...collectorCodes,...codes.filter(code=>!collectorCodes.includes(code))];
const block=`# BEGIN GENERATED DIAGNOSTICS
source_functions = ${JSON.stringify(files)}
for_each(["errorType", "causeType"]) -> |_index, key| {
value = get(record, [key]) ?? null
if includes(${JSON.stringify(types)}, value) { out = set!(out, [key], value) }
}
for_each(["errorStack", "causeStack"]) -> |_index, key| {
value = get(record, [key]) ?? null
if is_string(value) && length(string!(value)) <= 1024 {
frames = []
for_each(split(string!(value), "\\n", limit: 9)) -> |index, frame| {
parts, err = parse_regex(frame, r'^at (?P<function>[A-Za-z_$][A-Za-z0-9_$]*|<anonymous>) \\((?P<file>(?:src|build)/[A-Za-z0-9_./-]+\\.(?:ts|js)):(?P<line>[1-9][0-9]{0,5}):(?P<column>[1-9][0-9]{0,4})\\)$')
allowed = array(get(source_functions, [to_string(parts.file)]) ?? null) ?? []
if index < 8 && err == null && includes(array!(allowed), parts.function) { frames = push(frames, frame) }
}
if length(frames) > 0 { out = set!(out, [key], join!(frames, "\\n")) }
}
}
# END GENERATED DIAGNOSTICS`;
const clean=vrl.replace(/# BEGIN GENERATED DIAGNOSTICS[\s\S]*?# END GENERATED DIAGNOSTICS\n?/,'').replace(codeList,(_,start,_list,end)=>start+JSON.stringify(mergedCodes).replace(/","/g,'", "')+end);
fs.writeFileSync('deploy/logging/sanitize.vrl',clean.replace('out._msg = out.event',()=>block+'\nout._msg = out.event'));