diagnostic-bundle.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import {
  2. closeSync,
  3. createReadStream,
  4. fstatSync,
  5. lstatSync,
  6. openSync,
  7. readSync,
  8. readdirSync,
  9. realpathSync,
  10. statSync,
  11. } from 'node:fs';
  12. import { isAbsolute, join, relative } from 'node:path';
  13. import { createInterface } from 'node:readline';
  14. import type { ObservabilityPrivacyClass, ObservabilityUploadDefault } from './types.js';
  15. export interface DiagnosticBundleLimits {
  16. maxFiles: number;
  17. maxBytes: number;
  18. }
  19. export interface DiagnosticArtifact {
  20. name: string;
  21. path?: string;
  22. content?: Buffer | string;
  23. bytes: number;
  24. source: string;
  25. privacy: ObservabilityPrivacyClass;
  26. uploadDefault: ObservabilityUploadDefault;
  27. }
  28. export interface DiagnosticSourceDescription {
  29. label: string;
  30. privacy: ObservabilityPrivacyClass;
  31. uploadDefault: ObservabilityUploadDefault;
  32. }
  33. export interface DiagnosticArtifactSource {
  34. id: string;
  35. describe(): DiagnosticSourceDescription;
  36. collect(input: DiagnosticArtifactCollectInput): Promise<DiagnosticArtifact[]>;
  37. }
  38. export interface DiagnosticArtifactCollectInput {
  39. sinceMs: number;
  40. nowMs: number;
  41. limits: DiagnosticBundleLimits;
  42. }
  43. export interface DiagnosticBundleManifestSource {
  44. id: string;
  45. label: string;
  46. privacy: ObservabilityPrivacyClass;
  47. uploadDefault: ObservabilityUploadDefault;
  48. fileCount: number;
  49. bytes: number;
  50. skipped?: string;
  51. }
  52. export interface DiagnosticBundleManifest {
  53. schemaVersion: 1;
  54. generatedAtMs: number;
  55. sinceMs: number;
  56. sources: DiagnosticBundleManifestSource[];
  57. artifacts: DiagnosticBundleManifestArtifact[];
  58. limits: DiagnosticBundleLimits;
  59. totalFiles: number;
  60. totalBytes: number;
  61. skippedArtifacts?: Array<{ name: string; reason: string }>;
  62. }
  63. export interface DiagnosticBundleManifestArtifact {
  64. name: string;
  65. source: string;
  66. bytes: number;
  67. privacy: ObservabilityPrivacyClass;
  68. uploadDefault: ObservabilityUploadDefault;
  69. }
  70. export interface DiagnosticBundleResult {
  71. artifacts: DiagnosticArtifact[];
  72. manifest: DiagnosticBundleManifest;
  73. }
  74. export interface FileDiagnosticArtifactSourceOptions {
  75. id: string;
  76. label: string;
  77. dir: string;
  78. match: (fileName: string, relativeName?: string) => boolean;
  79. prefix: string;
  80. recursive?: boolean;
  81. privacy?: ObservabilityPrivacyClass;
  82. uploadDefault?: ObservabilityUploadDefault;
  83. maxBytesPerFile?: number;
  84. errorContext?: ErrorContextConfig;
  85. }
  86. export interface ErrorContextConfig {
  87. contextLines: number;
  88. maxOutputBytes: number;
  89. fallbackRecentMs: number;
  90. fallbackTailBytes: number;
  91. errorRegex?: RegExp;
  92. }
  93. const DEFAULT_ERROR_LEVEL_REGEX = /^(?:ERROR|WARN|FATAL)(?:\s|$)/;
  94. /**
  95. * CSI escape sequences (SGR colors, cursor movement). Log files written
  96. * before the disk arm started stripping ANSI (see
  97. * `@mavis/shared/logging/structured-logger.ts`) carry colorized level
  98. * tokens like `\x1b[31mERROR\x1b[39m` that no plain-text `errorRegex` can
  99. * match; scanning the stripped line keeps those historical files eligible
  100. * for error-context extraction during their remaining retention window.
  101. */
  102. // eslint-disable-next-line no-control-regex -- matching the ESC byte is the point.
  103. const ANSI_CSI_PATTERN = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
  104. function stripAnsi(line: string): string {
  105. return line.includes('\u001b') ? line.replace(ANSI_CSI_PATTERN, '') : line;
  106. }
  107. export class FileDiagnosticArtifactSource implements DiagnosticArtifactSource {
  108. readonly id: string;
  109. private readonly label: string;
  110. private readonly dir: string;
  111. private readonly match: (fileName: string, relativeName?: string) => boolean;
  112. private readonly prefix: string;
  113. private readonly recursive: boolean;
  114. private readonly privacy: ObservabilityPrivacyClass;
  115. private readonly uploadDefault: ObservabilityUploadDefault;
  116. private readonly maxBytesPerFile: number | undefined;
  117. private readonly errorContext: ErrorContextConfig | undefined;
  118. constructor(options: FileDiagnosticArtifactSourceOptions) {
  119. this.id = options.id;
  120. this.label = options.label;
  121. this.dir = options.dir;
  122. this.match = options.match;
  123. this.prefix = options.prefix;
  124. this.recursive = options.recursive ?? false;
  125. this.privacy = options.privacy ?? 'sensitive';
  126. this.uploadDefault = options.uploadDefault ?? 'consent-required';
  127. this.maxBytesPerFile = options.maxBytesPerFile;
  128. this.errorContext = options.errorContext;
  129. }
  130. describe(): DiagnosticSourceDescription {
  131. return {
  132. label: this.label,
  133. privacy: this.privacy,
  134. uploadDefault: this.uploadDefault,
  135. };
  136. }
  137. async collect(input: DiagnosticArtifactCollectInput): Promise<DiagnosticArtifact[]> {
  138. let entries: Array<{ relativeName: string; absolutePath: string }>;
  139. let dirRealPath: string;
  140. try {
  141. dirRealPath = realpathSync(this.dir);
  142. entries = this.recursive
  143. ? listRecursiveFiles(this.dir, this.match)
  144. : readdirSync(this.dir)
  145. .filter((name) => this.match(name, name))
  146. .sort()
  147. .map((name) => ({ relativeName: name, absolutePath: join(this.dir, name) }));
  148. } catch {
  149. return [];
  150. }
  151. const artifacts: DiagnosticArtifact[] = [];
  152. for (const entry of entries) {
  153. const path = entry.absolutePath;
  154. let stat;
  155. try {
  156. stat = lstatSync(path);
  157. } catch {
  158. continue;
  159. }
  160. if (stat.isSymbolicLink()) continue;
  161. if (!stat.isFile() || stat.mtimeMs < input.sinceMs) continue;
  162. let realPath: string;
  163. try {
  164. realPath = realpathSync(path);
  165. } catch {
  166. continue;
  167. }
  168. if (!isPathInside(dirRealPath, realPath)) continue;
  169. if (this.errorContext) {
  170. let content: string | null;
  171. try {
  172. content = await extractErrorContext(path, stat.mtimeMs, input.nowMs, this.errorContext);
  173. } catch {
  174. continue;
  175. }
  176. if (!content) continue;
  177. artifacts.push(this.artifact(entry.relativeName, Buffer.from(content, 'utf-8')));
  178. continue;
  179. }
  180. if (this.maxBytesPerFile && stat.size > this.maxBytesPerFile) {
  181. try {
  182. artifacts.push(this.artifact(entry.relativeName, tailFile(path, this.maxBytesPerFile)));
  183. } catch {
  184. continue;
  185. }
  186. } else {
  187. artifacts.push({
  188. name: `${this.prefix}${entry.relativeName.replaceAll('\\', '/')}`,
  189. path,
  190. bytes: stat.size,
  191. source: this.id,
  192. privacy: this.privacy,
  193. uploadDefault: this.uploadDefault,
  194. });
  195. }
  196. }
  197. return artifacts;
  198. }
  199. private artifact(fileName: string, content: Buffer): DiagnosticArtifact {
  200. return {
  201. name: `${this.prefix}${fileName.replaceAll('\\', '/')}`,
  202. content,
  203. bytes: content.byteLength,
  204. source: this.id,
  205. privacy: this.privacy,
  206. uploadDefault: this.uploadDefault,
  207. };
  208. }
  209. }
  210. function listRecursiveFiles(
  211. root: string,
  212. match: (fileName: string, relativeName?: string) => boolean,
  213. ): Array<{ relativeName: string; absolutePath: string }> {
  214. const results: Array<{ relativeName: string; absolutePath: string }> = [];
  215. const visit = (dir: string, relativeDir: string): void => {
  216. for (const name of readdirSync(dir).sort()) {
  217. const absolutePath = join(dir, name);
  218. const relativeName = relativeDir ? `${relativeDir}/${name}` : name;
  219. let info;
  220. try {
  221. info = lstatSync(absolutePath);
  222. } catch {
  223. continue;
  224. }
  225. if (info.isSymbolicLink()) continue;
  226. if (info.isDirectory()) {
  227. visit(absolutePath, relativeName);
  228. continue;
  229. }
  230. if (!info.isFile() || !match(name, relativeName)) continue;
  231. results.push({ relativeName, absolutePath });
  232. }
  233. };
  234. const rootStat = statSync(root);
  235. if (!rootStat.isDirectory()) return [];
  236. visit(root, '');
  237. return results;
  238. }
  239. export class StaticDiagnosticArtifactSource implements DiagnosticArtifactSource {
  240. readonly id: string;
  241. private readonly label: string;
  242. private readonly artifacts: DiagnosticArtifact[];
  243. constructor(id: string, label: string, artifacts: DiagnosticArtifact[]) {
  244. this.id = id;
  245. this.label = label;
  246. this.artifacts = artifacts;
  247. }
  248. describe(): DiagnosticSourceDescription {
  249. const strongestPrivacy = this.artifacts.some((artifact) => artifact.privacy === 'sensitive')
  250. ? 'sensitive'
  251. : this.artifacts.some((artifact) => artifact.privacy === 'masked')
  252. ? 'masked'
  253. : 'safe';
  254. const uploadDefault = this.artifacts.some(
  255. (artifact) => artifact.uploadDefault === 'consent-required',
  256. )
  257. ? 'consent-required'
  258. : this.artifacts.some((artifact) => artifact.uploadDefault === 'exclude')
  259. ? 'exclude'
  260. : 'include';
  261. return { label: this.label, privacy: strongestPrivacy, uploadDefault };
  262. }
  263. async collect(): Promise<DiagnosticArtifact[]> {
  264. return this.artifacts;
  265. }
  266. }
  267. export async function collectDiagnosticBundle(input: {
  268. sources: DiagnosticArtifactSource[];
  269. sinceMs: number;
  270. nowMs?: number;
  271. limits?: Partial<DiagnosticBundleLimits>;
  272. }): Promise<DiagnosticBundleResult> {
  273. const limits = {
  274. maxFiles: input.limits?.maxFiles ?? 256,
  275. maxBytes: input.limits?.maxBytes ?? 512 * 1024 * 1024,
  276. };
  277. const nowMs = input.nowMs ?? Date.now();
  278. const artifacts: DiagnosticArtifact[] = [];
  279. const manifestSources: DiagnosticBundleManifestSource[] = [];
  280. let totalBytes = 0;
  281. const skippedArtifacts: Array<{ name: string; reason: string }> = [];
  282. for (const source of input.sources) {
  283. const description = source.describe();
  284. let collected: DiagnosticArtifact[] = [];
  285. let skipped: string | undefined;
  286. try {
  287. collected = await source.collect({ sinceMs: input.sinceMs, nowMs, limits });
  288. } catch (err) {
  289. skipped = err instanceof Error ? err.message : String(err);
  290. collected = [];
  291. }
  292. const accepted: DiagnosticArtifact[] = [];
  293. for (const artifact of collected) {
  294. if (artifacts.length + accepted.length + 1 > limits.maxFiles) {
  295. skipped = 'diagnostic_bundle_too_many_files';
  296. break;
  297. }
  298. if (totalBytes + artifact.bytes > limits.maxBytes) {
  299. skipped = 'diagnostic_bundle_too_large';
  300. skippedArtifacts.push({ name: artifact.name, reason: skipped });
  301. continue;
  302. }
  303. accepted.push(artifact);
  304. totalBytes += artifact.bytes;
  305. }
  306. artifacts.push(...accepted);
  307. manifestSources.push({
  308. id: source.id,
  309. label: description.label,
  310. privacy: description.privacy,
  311. uploadDefault: description.uploadDefault,
  312. fileCount: accepted.length,
  313. bytes: accepted.reduce((sum, artifact) => sum + artifact.bytes, 0),
  314. ...(skipped ? { skipped } : {}),
  315. });
  316. }
  317. return {
  318. artifacts,
  319. manifest: {
  320. schemaVersion: 1,
  321. generatedAtMs: nowMs,
  322. sinceMs: input.sinceMs,
  323. sources: manifestSources,
  324. artifacts: artifacts.map((artifact) => ({
  325. name: artifact.name,
  326. source: artifact.source,
  327. bytes: artifact.bytes,
  328. privacy: artifact.privacy,
  329. uploadDefault: artifact.uploadDefault,
  330. })),
  331. limits,
  332. totalFiles: artifacts.length,
  333. totalBytes,
  334. ...(skippedArtifacts.length > 0 ? { skippedArtifacts } : {}),
  335. },
  336. };
  337. }
  338. function isPathInside(root: string, child: string): boolean {
  339. const rel = relative(root, child);
  340. return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
  341. }
  342. function tailFile(path: string, maxBytes: number): Buffer {
  343. const fd = openSync(path, 'r');
  344. try {
  345. const { size } = fstatSync(fd);
  346. const readBytes = Math.min(size, maxBytes);
  347. const buffer = Buffer.alloc(readBytes);
  348. readSync(fd, buffer, 0, readBytes, Math.max(0, size - readBytes));
  349. if (size <= maxBytes) return buffer;
  350. const marker = Buffer.from('\n... [truncated to tail] ...\n', 'utf-8');
  351. return Buffer.concat([marker, buffer]);
  352. } finally {
  353. closeSync(fd);
  354. }
  355. }
  356. async function extractErrorContext(
  357. path: string,
  358. mtimeMs: number,
  359. nowMs: number,
  360. config: ErrorContextConfig,
  361. ): Promise<string | null> {
  362. const errorRegex = config.errorRegex ?? DEFAULT_ERROR_LEVEL_REGEX;
  363. const stream = createReadStream(path, { encoding: 'utf-8' });
  364. const rl = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
  365. const before: Array<{ index: number; line: string }> = [];
  366. const output: string[] = [];
  367. let bytes = 0;
  368. let lineIndex = 0;
  369. let lastEmittedIndex = -1;
  370. let afterUntil = -1;
  371. let hitCount = 0;
  372. let truncated = false;
  373. const emitLine = (index: number, line: string): boolean => {
  374. if (index <= lastEmittedIndex) return true;
  375. if (lastEmittedIndex >= 0 && index > lastEmittedIndex + 1) {
  376. output.push('... [context skipped] ...');
  377. }
  378. bytes += Buffer.byteLength(line, 'utf-8') + 1;
  379. if (bytes > config.maxOutputBytes) {
  380. output.push('... [truncated] ...');
  381. truncated = true;
  382. return false;
  383. }
  384. output.push(line);
  385. lastEmittedIndex = index;
  386. return true;
  387. };
  388. try {
  389. for await (const rawLine of rl) {
  390. // Match and emit the ANSI-stripped line: historical colorized files
  391. // stay scannable and the extracted context reads as plain text.
  392. const line = stripAnsi(rawLine);
  393. const isHit = errorRegex.test(line);
  394. if (isHit) {
  395. hitCount += 1;
  396. for (const entry of before) {
  397. if (!emitLine(entry.index, entry.line)) break;
  398. }
  399. if (!truncated) emitLine(lineIndex, line);
  400. afterUntil = Math.max(afterUntil, lineIndex + config.contextLines);
  401. } else if (lineIndex <= afterUntil) {
  402. emitLine(lineIndex, line);
  403. }
  404. if (truncated) break;
  405. before.push({ index: lineIndex, line });
  406. while (before.length > config.contextLines) before.shift();
  407. lineIndex += 1;
  408. }
  409. } finally {
  410. rl.close();
  411. stream.destroy();
  412. }
  413. if (hitCount === 0) {
  414. if (nowMs - mtimeMs > config.fallbackRecentMs) return null;
  415. return tailFile(path, config.fallbackTailBytes).toString('utf-8');
  416. }
  417. return output.join('\n');
  418. }