|
| 1 | +import { readFileSync } from 'node:fs'; |
| 2 | +import pc from 'picocolors'; |
| 3 | +import { type ErrChainNode, formatErrorNodeInline } from './log-file.ts'; |
| 4 | + |
| 5 | +/** How many trailing records the tail block shows. */ |
| 6 | +export const LOG_TAIL_LIMIT = 20; |
| 7 | +/** How many error records the error block shows. */ |
| 8 | +export const LOG_ERROR_LIMIT = 5; |
| 9 | + |
| 10 | +const FIELD_VALUE_MAX = 80; |
| 11 | +const LINE_MAX = 160; |
| 12 | +const MSG_COLUMN_MAX = 28; |
| 13 | +const ELAPSED_WIDTH = 7; |
| 14 | +const LEVEL_WIDTH = 5; |
| 15 | +/** Width of `' ' + elapsed + ' '`, used to indent the error sub-lines. */ |
| 16 | +const DETAIL_INDENT = ' '.repeat(2 + ELAPSED_WIDTH + 2); |
| 17 | + |
| 18 | +/** |
| 19 | + * `runDeploy` writes this record last, and its `err` field is the very message |
| 20 | + * printed above the summary. Keeping it out of the error block avoids echoing |
| 21 | + * the same text twice; it still shows up as one line in the tail. |
| 22 | + */ |
| 23 | +const TERMINAL_ERROR_MSG = 'deploy_end'; |
| 24 | + |
| 25 | +const RESERVED_KEYS = new Set(['ts', 'elapsedMs', 'lvl', 'msg', 'err']); |
| 26 | + |
| 27 | +/** |
| 28 | + * The trace was a file the user opened by hand; the summary publishes it to |
| 29 | + * whatever reads stderr, which in CI is a stored, often public, log. |
| 30 | + * |
| 31 | + * Scrubbing here covers only credentials this code emits itself — a presigned |
| 32 | + * URL it built, an auth header it set, a field it named. Scrubbing user data is |
| 33 | + * left to the CI platform, which owns the secrets and masks them before the log |
| 34 | + * is written. GitHub Actions does this for everything under `secrets.*`. Void |
| 35 | + * does not guess at credential-shaped names or at credentials embedded in |
| 36 | + * values the user supplied. |
| 37 | + */ |
| 38 | +/** Query parameters whose value must never reach a CI log. */ |
| 39 | +const SIGNED_QUERY_RE = |
| 40 | + /([?&](?:X-Amz-[A-Za-z0-9-]+|[Ss]ignature|sig|token|access_token|key)=)[^&\s]+/g; |
| 41 | +const BEARER_RE = /\b(Bearer\s+)\S+/g; |
| 42 | +/** |
| 43 | + * Field keys whose value is masked whole, whatever it looks like. `auth` is |
| 44 | + * deliberately absent — it matches metadata keys such as `authMethod` far more |
| 45 | + * often than credentials. |
| 46 | + */ |
| 47 | +const SECRET_KEY_RE = |
| 48 | + /token|secret|password|passwd|credential|cookie|signature|api[-_]?key|private[-_]?key/i; |
| 49 | + |
| 50 | +type LogRecord = { |
| 51 | + elapsedMs?: number; |
| 52 | + lvl?: string; |
| 53 | + msg?: string; |
| 54 | + err?: ErrChainNode | string; |
| 55 | + [key: string]: unknown; |
| 56 | +}; |
| 57 | + |
| 58 | +function redact(text: string): string { |
| 59 | + return text.replace(SIGNED_QUERY_RE, '$1[redacted]').replace(BEARER_RE, '$1[redacted]'); |
| 60 | +} |
| 61 | + |
| 62 | +function truncate(text: string, max: number): string { |
| 63 | + return text.length <= max ? text : `${text.slice(0, max)}...`; |
| 64 | +} |
| 65 | + |
| 66 | +/** Collapse every run of whitespace so one record always renders as one line. */ |
| 67 | +function oneLine(text: string): string { |
| 68 | + return text.replace(/\s+/g, ' ').trim(); |
| 69 | +} |
| 70 | + |
| 71 | +function stringifyValue(value: unknown): string { |
| 72 | + if (typeof value === 'string') { |
| 73 | + return value; |
| 74 | + } |
| 75 | + if (value === null || typeof value === 'number' || typeof value === 'boolean') { |
| 76 | + return String(value); |
| 77 | + } |
| 78 | + try { |
| 79 | + return JSON.stringify(value) ?? String(value); |
| 80 | + } catch { |
| 81 | + return String(value); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +/** Render one `key=value` pair, collapsed, redacted, and length-capped. */ |
| 86 | +function formatField(key: string, value: unknown): string { |
| 87 | + if (SECRET_KEY_RE.test(key)) { |
| 88 | + return `${key}=[redacted]`; |
| 89 | + } |
| 90 | + return `${key}=${truncate(redact(oneLine(stringifyValue(value))), FIELD_VALUE_MAX)}`; |
| 91 | +} |
| 92 | + |
| 93 | +function fieldPairs(record: LogRecord): Array<string> { |
| 94 | + const pairs: Array<string> = []; |
| 95 | + for (const [key, value] of Object.entries(record)) { |
| 96 | + if (RESERVED_KEYS.has(key) || value === undefined) { |
| 97 | + continue; |
| 98 | + } |
| 99 | + pairs.push(formatField(key, value)); |
| 100 | + } |
| 101 | + if (record.err !== undefined) { |
| 102 | + pairs.push( |
| 103 | + `err=${truncate(redact(oneLine(formatErrorNodeInline(record.err))), FIELD_VALUE_MAX)}`, |
| 104 | + ); |
| 105 | + } |
| 106 | + return pairs; |
| 107 | +} |
| 108 | + |
| 109 | +function formatElapsed(elapsedMs: unknown): string { |
| 110 | + const ms = typeof elapsedMs === 'number' && Number.isFinite(elapsedMs) ? elapsedMs : 0; |
| 111 | + return `${(ms / 1000).toFixed(1)}s`.padStart(ELAPSED_WIDTH); |
| 112 | +} |
| 113 | + |
| 114 | +function colorLevel(level: string, padded: string): string { |
| 115 | + if (level === 'error') { |
| 116 | + return pc.red(padded); |
| 117 | + } |
| 118 | + if (level === 'warn') { |
| 119 | + return pc.yellow(padded); |
| 120 | + } |
| 121 | + // `info` and `debug` are context, not signal — dim them so the red and |
| 122 | + // yellow rows stand out in a wall of CI output. |
| 123 | + return pc.dim(padded); |
| 124 | +} |
| 125 | + |
| 126 | +function parseRecords(lines: Array<string>): Array<LogRecord> { |
| 127 | + const records: Array<LogRecord> = []; |
| 128 | + for (const raw of lines) { |
| 129 | + const trimmed = raw.trim(); |
| 130 | + if (!trimmed) { |
| 131 | + continue; |
| 132 | + } |
| 133 | + try { |
| 134 | + const parsed: unknown = JSON.parse(trimmed); |
| 135 | + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { |
| 136 | + records.push(parsed as LogRecord); |
| 137 | + } |
| 138 | + } catch { |
| 139 | + // A partially flushed or corrupt line must not hide the rest of the log. |
| 140 | + } |
| 141 | + } |
| 142 | + return records; |
| 143 | +} |
| 144 | + |
| 145 | +/** One aligned line: ` 8.9s error deploy_server_error message=...`. */ |
| 146 | +function formatTailLine(record: LogRecord, msgWidth: number): string { |
| 147 | + const level = typeof record.lvl === 'string' ? record.lvl : 'info'; |
| 148 | + const msg = typeof record.msg === 'string' ? record.msg : ''; |
| 149 | + const elapsed = formatElapsed(record.elapsedMs); |
| 150 | + const paddedLevel = level.padEnd(LEVEL_WIDTH); |
| 151 | + const paddedMsg = msg.padEnd(msgWidth); |
| 152 | + const head = ` ${elapsed} ${paddedLevel} ${paddedMsg}`; |
| 153 | + const fields = fieldPairs(record).join(' '); |
| 154 | + if (!fields) { |
| 155 | + return ` ${elapsed} ${colorLevel(level, paddedLevel)} ${msg}`; |
| 156 | + } |
| 157 | + const budget = Math.max(20, LINE_MAX - head.length); |
| 158 | + return ` ${elapsed} ${colorLevel(level, paddedLevel)} ${paddedMsg} ${truncate(fields, budget)}`; |
| 159 | +} |
| 160 | + |
| 161 | +/** An error entry: a headline, then one indented line per field. */ |
| 162 | +function formatErrorEntry(record: LogRecord): Array<string> { |
| 163 | + const msg = typeof record.msg === 'string' ? record.msg : 'error'; |
| 164 | + const lines = [` ${formatElapsed(record.elapsedMs)} ${pc.red(msg)}`]; |
| 165 | + for (const pair of fieldPairs(record)) { |
| 166 | + lines.push(`${DETAIL_INDENT}${pair}`); |
| 167 | + } |
| 168 | + return lines; |
| 169 | +} |
| 170 | + |
| 171 | +/** |
| 172 | + * Turn raw JSONL lines into the block appended to a failed deploy's error |
| 173 | + * message. Returns `null` when there is nothing worth printing. |
| 174 | + * |
| 175 | + * The block has two parts: every `error` record with its flattened cause |
| 176 | + * chain, then the last `LOG_TAIL_LIMIT` records for timeline context. |
| 177 | + */ |
| 178 | +export function formatDeployLogSummary(lines: Array<string>): string | null { |
| 179 | + const records = parseRecords(lines); |
| 180 | + if (records.length === 0) { |
| 181 | + return null; |
| 182 | + } |
| 183 | + |
| 184 | + const blocks: Array<string> = []; |
| 185 | + |
| 186 | + const errors = records.filter((r) => r.lvl === 'error' && r.msg !== TERMINAL_ERROR_MSG); |
| 187 | + if (errors.length > 0) { |
| 188 | + const shown = errors.slice(0, LOG_ERROR_LIMIT); |
| 189 | + const errorLines = shown.flatMap((record) => formatErrorEntry(record)); |
| 190 | + if (errors.length > shown.length) { |
| 191 | + errorLines.push(`${DETAIL_INDENT}(+${errors.length - shown.length} more)`); |
| 192 | + } |
| 193 | + blocks.push([pc.bold('Errors'), ...errorLines].join('\n')); |
| 194 | + } |
| 195 | + |
| 196 | + const tail = records.slice(-LOG_TAIL_LIMIT); |
| 197 | + const msgWidth = Math.min( |
| 198 | + MSG_COLUMN_MAX, |
| 199 | + tail.reduce((max, r) => Math.max(max, typeof r.msg === 'string' ? r.msg.length : 0), 0), |
| 200 | + ); |
| 201 | + const heading = |
| 202 | + records.length > tail.length |
| 203 | + ? `Last ${LOG_TAIL_LIMIT} of ${records.length} entries` |
| 204 | + : `Log (${records.length} ${records.length === 1 ? 'entry' : 'entries'})`; |
| 205 | + blocks.push( |
| 206 | + [pc.bold(heading), ...tail.map((record) => formatTailLine(record, msgWidth))].join('\n'), |
| 207 | + ); |
| 208 | + |
| 209 | + return `\n${blocks.join('\n\n')}`; |
| 210 | +} |
| 211 | + |
| 212 | +/** |
| 213 | + * Read a deploy JSONL log and format its summary. Returns `null` for a missing |
| 214 | + * path or any read failure — a postmortem aid must never mask the real error. |
| 215 | + */ |
| 216 | +export function buildDeployLogSummary(path: string | null | undefined): string | null { |
| 217 | + if (!path) { |
| 218 | + return null; |
| 219 | + } |
| 220 | + let text: string; |
| 221 | + try { |
| 222 | + text = readFileSync(path, 'utf-8'); |
| 223 | + } catch { |
| 224 | + return null; |
| 225 | + } |
| 226 | + return formatDeployLogSummary(text.split('\n')); |
| 227 | +} |
0 commit comments