|
| 1 | +#!/usr/bin/env node |
| 2 | +// Build-time catalog compiler. Complete validation precedes every output write. |
| 3 | +import { readFile, readdir, mkdir, writeFile } from 'node:fs/promises'; |
| 4 | +import { realpathSync } from 'node:fs'; |
| 5 | +import path from 'node:path'; |
| 6 | +import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 7 | + |
| 8 | +export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); |
| 9 | +export const ROOTS = 'app editor perf lsp vcs run debug terminal remote agent update plugins'.split(' '); |
| 10 | +export const TYPES = 'int bool duration bytes id token version path error text'.split(' '); |
| 11 | +export const DEFAULT_RATE = 60; |
| 12 | +export const GENERIC_DESCRIPTIONS = Object.freeze([ |
| 13 | + 'Validated internal identifier', |
| 14 | + 'Controlled machine vocabulary', |
| 15 | + 'Structured failure', |
| 16 | + 'Path redacted before persistence', |
| 17 | + 'Monotonic elapsed time', |
| 18 | + 'Count or numeric result', |
| 19 | + 'Outcome flag', |
| 20 | + 'Byte count', |
| 21 | + 'Component version', |
| 22 | + 'Upstream diagnostic', |
| 23 | +]); |
| 24 | +const LEVELS = ['debug', 'info', 'warn', 'error']; |
| 25 | +const RESERVED = ['seq', 'event', 'op', 'msg', 'ts', 'level']; |
| 26 | +const segment = /^[a-z0-9][a-z0-9._-]{0,63}$/; |
| 27 | +const safeSegment = value => segment.test(value) && !value.endsWith('.') && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/.test(value); |
| 28 | +const fieldName = /^[a-z][a-z0-9_]{0,63}$/; |
| 29 | +const object = value => value !== null && typeof value === 'object' && !Array.isArray(value); |
| 30 | +const fail = message => { throw new Error(message); }; |
| 31 | +const nonempty = (value, where) => { if (typeof value !== 'string' || !value.trim()) fail(`${where}: expected nonempty string`); }; |
| 32 | +const keys = (value, allowed, where) => { |
| 33 | + if (!object(value)) fail(`${where}: expected object`); |
| 34 | + for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${where}: unknown property ${key}`); |
| 35 | +}; |
| 36 | +const sorted = entries => entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); |
| 37 | +const pascal = id => id.split(/[._]/).map(word => word[0].toUpperCase() + word.slice(1)).join(''); |
| 38 | +const camel = name => name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); |
| 39 | +const wireNames = (name, field) => field.type === 'duration' ? [`${name}_ms`] : field.type === 'error' ? [name, `${name}_code`, `${name}_domain`] : [name]; |
| 40 | + |
| 41 | +export function validateCatalog(catalogs) { |
| 42 | + const ids = new Set(); |
| 43 | + const names = new Set(); |
| 44 | + const events = []; |
| 45 | + const declarations = []; |
| 46 | + for (const catalog of catalogs) { |
| 47 | + keys(catalog, ['version', 'root', 'events'], 'catalog'); |
| 48 | + if (catalog.version !== 1 || !ROOTS.includes(catalog.root) || !Array.isArray(catalog.events)) fail('invalid catalog version/root/events'); |
| 49 | + for (const event of catalog.events) { |
| 50 | + keys(event, ['id', 'channel', 'level', 'message', 'fields', 'span', 'rate', 'owner'], catalog.root); |
| 51 | + if (typeof event.id !== 'string' || !/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9_]*){2,}$/.test(event.id) || event.id.split('.')[0] !== catalog.root) fail(`invalid event id: ${event.id}`); |
| 52 | + if (!LEVELS.includes(event.level)) fail(`${event.id}: invalid level`); |
| 53 | + nonempty(event.owner, `${event.id} owner`); |
| 54 | + nonempty(event.message, `${event.id} message`); |
| 55 | + if (!/^[\x20-\x7e]+$/.test(event.message)) fail(`${event.id}: message must be an English single-line template`); |
| 56 | + const rate = event.rate ?? DEFAULT_RATE; |
| 57 | + if (!Number.isSafeInteger(rate) || rate < 1 || rate > 60000) fail(`${event.id}: invalid rate`); |
| 58 | + if (!object(event.fields)) fail(`${event.id}: expected fields`); |
| 59 | + const encoded = new Set(RESERVED); |
| 60 | + // Typed host bindings derive camelCase parameters; reserve the names they add. |
| 61 | + const parameters = new Set(['operationID', ...(event.span ? ['clock', 'emit', 'state'] : [])]); |
| 62 | + for (const [name, field] of Object.entries(event.fields)) { |
| 63 | + if (!fieldName.test(name) || RESERVED.includes(name)) fail(`${event.id}: reserved or invalid field ${name}`); |
| 64 | + if (parameters.has(camel(name))) fail(`${event.id}: generated parameter collision ${name}`); |
| 65 | + parameters.add(camel(name)); |
| 66 | + keys(field, ['type', 'required', 'description', 'reason'], `${event.id}/${name}`); |
| 67 | + if (!TYPES.includes(field.type)) fail(`${event.id}/${name}: unknown type ${field.type}`); |
| 68 | + if (typeof field.required !== 'boolean') fail(`${event.id}/${name}: required must be boolean`); |
| 69 | + nonempty(field.description, `${event.id}/${name} description`); |
| 70 | + if (GENERIC_DESCRIPTIONS.includes(field.description.trim())) fail(`${event.id}/${name}: generic description must explain this event's field`); |
| 71 | + if ([...field.description.trim()].length < 16) fail(`${event.id}/${name}: description must contain at least 16 characters`); |
| 72 | + if (field.type === 'text') nonempty(field.reason, `${event.id}/${name}: text requires reason`); |
| 73 | + else if (field.reason !== undefined) fail(`${event.id}/${name}: reason is only for text`); |
| 74 | + if (field.type === 'duration' && name.endsWith('_ms')) fail(`${event.id}/${name}: duration name must not end in _ms`); |
| 75 | + for (const wire of wireNames(name, field)) { |
| 76 | + if (!fieldName.test(wire) || encoded.has(wire)) fail(`${event.id}: encoded field collision or invalid name ${wire}`); |
| 77 | + encoded.add(wire); |
| 78 | + } |
| 79 | + } |
| 80 | + if (typeof event.channel !== 'string') fail(`${event.id}: missing channel`); |
| 81 | + const parts = event.channel.split('/'); |
| 82 | + if (!ROOTS.includes(parts[0]) || parts[0] !== catalog.root) fail(`${event.id}: invalid channel root`); |
| 83 | + if (!(parts.length === 1 || (parts.length === 2 && parts[0] !== 'plugins') || (parts.length === 3 && parts[0] === 'plugins' && parts[2] === 'host'))) fail(`${event.id}: unsupported channel shape`); |
| 84 | + for (const part of parts.slice(1)) { |
| 85 | + const placeholder = /^\{([a-z][a-z0-9_]*)\}$/.exec(part); |
| 86 | + if (placeholder) { |
| 87 | + const field = event.fields[placeholder[1]]; |
| 88 | + if (field?.type !== 'id' || !field.required) fail(`${event.id}: channel placeholder must be a required id field`); |
| 89 | + } else if (!safeSegment(part)) fail(`${event.id}: invalid channel segment`); |
| 90 | + } |
| 91 | + if (parts[0] === 'plugins' && parts.length > 1 && event.channel !== 'plugins/{plugin}/host') fail(`${event.id}: plugin host channel must be plugins/{plugin}/host`); |
| 92 | + for (const match of event.message.matchAll(/\{([^{}]+)\}/g)) { |
| 93 | + if (!Object.hasOwn(event.fields, match[1])) fail(`${event.id}: message references undeclared field ${match[1]}`); |
| 94 | + if (!event.fields[match[1]].required) fail(`${event.id}: message references optional field ${match[1]}`); |
| 95 | + } |
| 96 | + if (/[{}]/.test(event.message.replace(/\{[^{}]+\}/g, ''))) fail(`${event.id}: malformed message template`); |
| 97 | + if (event.span !== undefined) { |
| 98 | + keys(event.span, ['failureLevel'], `${event.id} span`); |
| 99 | + if (!LEVELS.includes(event.span.failureLevel)) fail(`${event.id}: invalid span failureLevel`); |
| 100 | + if (['duration', 'error'].some(name => Object.hasOwn(event.fields, name)) || ['duration_ms', 'error', 'error_code', 'error_domain'].some(name => encoded.has(name))) fail(`${event.id}: span automatic fields collide`); |
| 101 | + } else if (!/(?:started|finished|failed|changed|skipped|missing|received|selected|superseded|hit|inspected|sampled|measured|rejected|updated|forwarded|removed|cleaned|cancelled|initialized|limited|applied|waiting|stalled|timed_out|resolved|logged|shown|interrupted|traced|performed)$/.test(event.id.split('.').at(-1))) fail(`${event.id}: expected outcome name in past tense`); |
| 102 | + declarations.push({ ...event, rate }); |
| 103 | + const variants = event.span ? ['started', 'finished', 'failed'] : [null]; |
| 104 | + for (const phase of variants) { |
| 105 | + const fields = { ...event.fields }; |
| 106 | + if (phase && phase !== 'started') fields.duration = { type: 'duration', required: true, description: `Monotonic time from ${event.id}.started to ${event.id}.${phase}, encoded in milliseconds` }; |
| 107 | + if (phase === 'failed') fields.error = { type: 'error', required: true, description: `Failure that ended the ${event.id} operation, retaining its error code and domain without unredacted private details` }; |
| 108 | + const expanded = { ...event, id: phase ? `${event.id}.${phase}` : event.id, |
| 109 | + fields: Object.fromEntries(sorted(Object.entries(fields))), rate, span: phase, |
| 110 | + message: phase ? `${event.message} ${phase}` : event.message, |
| 111 | + level: phase === 'started' ? 'debug' : phase === 'failed' ? event.span.failureLevel : event.level }; |
| 112 | + const name = pascal(expanded.id); |
| 113 | + if (ids.has(expanded.id)) fail(`duplicate id: ${expanded.id}`); |
| 114 | + if (names.has(name)) fail(`generated name collision: ${name}`); |
| 115 | + ids.add(expanded.id); names.add(name); events.push(expanded); |
| 116 | + } |
| 117 | + if (event.span) { |
| 118 | + const name = `${pascal(event.id)}Span`; |
| 119 | + if (names.has(name)) fail(`generated name collision: ${name}`); |
| 120 | + names.add(name); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + return { events: events.sort((a, b) => a.id < b.id ? -1 : 1), declarations: declarations.sort((a, b) => a.id < b.id ? -1 : 1) }; |
| 125 | +} |
| 126 | + |
| 127 | +export async function loadCatalog(root = ROOT) { |
| 128 | + const directory = path.join(root, 'rust/logging/events'); |
| 129 | + const files = (await readdir(directory)).sort(); |
| 130 | + if (JSON.stringify(files) !== JSON.stringify(ROOTS.map(root => `${root}.json`).sort())) fail('expected exactly one catalog file per fixed channel root'); |
| 131 | + const catalogs = await Promise.all(files.map(async file => { |
| 132 | + const catalog = JSON.parse(await readFile(path.join(directory, file), 'utf8')); |
| 133 | + if (catalog.root !== file.slice(0, -5)) fail(`${file}: root differs from filename`); |
| 134 | + return catalog; |
| 135 | + })); |
| 136 | + return validateCatalog(catalogs); |
| 137 | +} |
| 138 | + |
| 139 | +const quote = JSON.stringify; |
| 140 | +function rustEvents(events) { |
| 141 | + const variant = type => pascal(type); |
| 142 | + return `//! Generated event metadata; edit rust/logging/events/*.json instead.\n// Automatically generated by scripts/logging/generate-log-events.mjs. DO NOT EDIT.\n\nuse super::{EventMetadata, FieldMetadata, FieldType, LogLevel, SpanPhase};\n\n/// Sorted, immutable metadata for every expanded catalog event.\n#[rustfmt::skip]\npub static EVENTS: &[EventMetadata] = &[\n${events.map(event => ` EventMetadata { |
| 143 | + id: ${quote(event.id)}, |
| 144 | + channel: ${quote(event.channel)}, |
| 145 | + level: LogLevel::${variant(event.level)}, |
| 146 | + message: ${quote(event.message)}, |
| 147 | + fields: &[ |
| 148 | +${Object.entries(event.fields).map(([name, field]) => ` FieldMetadata { name: ${quote(name)}, field_type: FieldType::${variant(field.type)}, required: ${field.required}, description: ${quote(field.description)}, reason: ${field.reason ? `Some(${quote(field.reason)})` : 'None'} },`).join('\n')} |
| 149 | + ], |
| 150 | + span: ${event.span ? `Some(SpanPhase::${variant(event.span)})` : 'None'}, |
| 151 | + rate: ${event.rate}, |
| 152 | + owner: ${quote(event.owner)}, |
| 153 | + },`).join('\n')}\n];\n`; |
| 154 | +} |
| 155 | +export async function planGeneration(root = ROOT) { |
| 156 | + const contract = await loadCatalog(root); |
| 157 | + const outputs = new Map([ |
| 158 | + ['rust/crates/diagnostics/src/catalog_generated.rs', rustEvents(contract.events)], |
| 159 | + ]); |
| 160 | + return { contract, outputs }; |
| 161 | +} |
| 162 | +export async function generate(root = ROOT, check = false) { |
| 163 | + const { contract, outputs } = await planGeneration(root); |
| 164 | + const stale = []; |
| 165 | + for (const [relative, expected] of outputs) { |
| 166 | + let actual; |
| 167 | + try { actual = await readFile(path.join(root, relative), 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; } |
| 168 | + if (actual === expected) continue; |
| 169 | + stale.push(relative); |
| 170 | + if (!check) { |
| 171 | + await mkdir(path.dirname(path.join(root, relative)), { recursive: true }); |
| 172 | + await writeFile(path.join(root, relative), expected); |
| 173 | + } |
| 174 | + } |
| 175 | + if (check && stale.length) fail(`generated logging files drifted; run node scripts/logging/generate-log-events.mjs:\n${stale.join('\n')}`); |
| 176 | + return contract; |
| 177 | +} |
| 178 | +async function main() { |
| 179 | + const args = process.argv.slice(2); |
| 180 | + if (args.length > 1 || args.some(arg => arg !== '--check')) fail('usage: node scripts/logging/generate-log-events.mjs [--check]'); |
| 181 | + const { events } = await generate(ROOT, args[0] === '--check'); |
| 182 | + console.log(`${events.length} log events: ${ROOTS.map(root => `${root}=${events.filter(e => e.id.startsWith(root + '.')).length}`).join(', ')}`); |
| 183 | +} |
| 184 | +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(path.resolve(process.argv[1]))).href) main().catch(error => { console.error(error.message); process.exitCode = 1; }); |
0 commit comments