Skip to content

Commit 6676a65

Browse files
committed
feat(logging): 恢复日志事件目录生成器,新增增量更新回退事件 update.delta.fallback_selected
- scripts/logging/generate-log-events.mjs:从 rust/logging/events/ 生成 rust/crates/diagnostics/src/catalog_generated.rs,--check 只读比较;在未改动的 main 上逐字节一致。去掉已无消费者的 Swift 输出。 - update.delta.fallback_selected(WARN,字段 stage、error):桌面客户端的增量更新 在下载、应用或安装补丁失败、改用完整包时记录。 - README 的检查步骤与现状一致;类型化事件、生成器测试和用法门禁见 Lithe-IDEA#1802。
1 parent 2c1fed1 commit 6676a65

5 files changed

Lines changed: 224 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Lithe 的跨平台应用内核,以及插件契约、插件开发资料和官
1010
| [`rust/logging/`](rust/logging) | 日志事件目录 |
1111
| [`shared/plugins/`](shared/plugins) | 插件契约 `contract/v1/`、开发指南 `guides/`、参考 `reference/`、官方 SDK `sdk/{node,java,rust}` 和它们的端到端测试 |
1212
| [`scripts/rust-core/`](scripts/rust-core) | Rust Core 注释规范检查(模块文档、英文注释、`unsafe` 安全说明、导出项 Rustdoc) |
13+
| [`scripts/logging/`](scripts/logging) | 日志事件目录生成器,从 `rust/logging/events/` 生成 `rust/crates/diagnostics/src/catalog_generated.rs` |
1314

1415
**插件开发者**从 [`shared/plugins/README.md`](shared/plugins/README.md) 开始,不需要克隆 Lithe 应用仓库。
1516

@@ -18,6 +19,7 @@ Lithe 的跨平台应用内核,以及插件契约、插件开发资料和官
1819
```sh
1920
cargo test --manifest-path rust/Cargo.toml --workspace # Core 测试
2021
scripts/rust-core/verify-rust-core-comments.sh # 注释规范
22+
node scripts/logging/generate-log-events.mjs --check # 日志事件目录与生成表一致
2123
node shared/plugins/scripts/verify-docs.mjs # 契约 $id 与文档链接
2224
node shared/plugins/scripts/sdk-e2e.mjs # 三个 SDK 对当前 Core 的端到端测试
2325
```
@@ -40,6 +42,7 @@ Lithe's cross-platform application core, and the single source of the plugin con
4042
| [`rust/logging/`](rust/logging) | The logging event catalog |
4143
| [`shared/plugins/`](shared/plugins) | The plugin contract `contract/v1/`, guides `guides/`, reference `reference/`, the official SDKs `sdk/{node,java,rust}` and their end-to-end tests |
4244
| [`scripts/rust-core/`](scripts/rust-core) | The Rust Core comment rules check (module docs, English comments, `unsafe` safety sections, Rustdoc on exported items) |
45+
| [`scripts/logging/`](scripts/logging) | The logging event catalog generator, which turns `rust/logging/events/` into `rust/crates/diagnostics/src/catalog_generated.rs` |
4346

4447
**Plugin authors** start at [`shared/plugins/README.md`](shared/plugins/README.md) and never need to clone the Lithe application repository.
4548

‎rust/crates/diagnostics/src/catalog_generated.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,6 +2344,19 @@ pub static EVENTS: &[EventMetadata] = &[
23442344
rate: 60,
23452345
owner: "Lithe",
23462346
},
2347+
EventMetadata {
2348+
id: "update.delta.fallback_selected",
2349+
channel: "update",
2350+
level: LogLevel::Warn,
2351+
message: "Delta update {stage} failed, falling back to the full download",
2352+
fields: &[
2353+
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Error the delta step returned before the full download replaced it, keeping its stable code and domain", reason: None },
2354+
FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Delta step that failed before the full archive replaced it: download, apply or install", reason: None },
2355+
],
2356+
span: None,
2357+
rate: 60,
2358+
owner: "Lithe",
2359+
},
23472360
EventMetadata {
23482361
id: "update.download.interrupted",
23492362
channel: "update",

‎rust/logging/README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,16 @@ Swift 的事件值是**未经脱敏的内存输入**,不能自行序列化落
121121

122122
1. 先调查真实调用,选择根和 owner;没有实际来源不新增事件。
123123
2. 在对应 JSON 中声明稳定 ID、通道模板、英文事实、级别和字段;成对操作优先使用 span。检查隐私和动态段来源。
124-
3. 运行生成器,核对 Swift 参数和 Rust 字段表;不得手改生成文件。
124+
3. 运行生成器,核对 Rust 字段表;不得手改生成文件。
125125
4. 接入时使用类型化事件。不再有调用点的事件从目录删除并重新生成。
126126
5. 运行下列检查。生成结果稳定排序、使用 LF,不读取运行时 JSON。
127127

128128
```sh
129129
node scripts/logging/generate-log-events.mjs
130130
node scripts/logging/generate-log-events.mjs --check
131-
node --test --test-timeout=60000 scripts/logging/test-log-events.mjs
132-
node scripts/logging/verify-log-usage.mjs
133131
```
134132

135-
`--check` 只读比较,不修复漂移,有缺失或差异即以非零状态退出。生成器先完成全部目录校验和输出规划,再写第一个文件。Swift target 自动发现 `Logging/` 源目录,不需要在 `Package.swift` 中逐个列出。
133+
`--check` 只读比较,不修复漂移,有缺失或差异即以非零状态退出。生成器先完成全部目录校验和输出规划,再写第一个文件。它只输出 `rust/crates/diagnostics/src/catalog_generated.rs`;桌面客户端的类型化事件、生成器测试和第十二节的用法门禁尚未恢复,由 [Lithe-IDEA#1802](https://github.com/1lck/Lithe-IDEA/issues/1802) 跟踪。
136134

137135
## 十一、API 示例
138136

@@ -158,6 +156,8 @@ Rust 通过静态 `EVENTS`(按 ID 排序)和二分查找的 `event_by_id`
158156

159157
## 十二、用法门禁
160158

159+
本节描述的 `scripts/logging/verify-log-usage.mjs` 目前不在仓库中,恢复由 [Lithe-IDEA#1802](https://github.com/1lck/Lithe-IDEA/issues/1802) 跟踪;恢复前不要把它列进检查步骤。
160+
161161
`scripts/logging/verify-log-usage.mjs` 扫描 `macos/Sources`、`rust/crates/core/src`、`rust/crates/git-host/src`、`rust/crates/ide-host/src` 和 `rust/crates/remote/src`。排除 `rust/crates/remote/src/server/`、`rust/crates/remote/src/bin/` 和 `rust/crates/ide-host/src/bin/`:它们在远端主机或独立进程中运行,stderr 由宿主进程处理,以后单独迁移。
162162

163163
门禁只扫描生产代码:词法上遮蔽注释和字符串内容,排除 `Tests/`、`tests/`、`tests.rs`、文件名以 `_tests.rs` 结尾的 Rust 文件,以及明确标注 `#[cfg(test)]` 或 `#[cfg(all(test, …))]` 的项。它只检查列出的直接写法,不跨文件追踪别名或动态调用。规则分两类:

‎rust/logging/events/update.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,26 @@
22
"version": 1,
33
"root": "update",
44
"events": [
5+
{
6+
"id": "update.delta.fallback_selected",
7+
"channel": "update",
8+
"level": "warn",
9+
"message": "Delta update {stage} failed, falling back to the full download",
10+
"fields": {
11+
"stage": {
12+
"type": "token",
13+
"required": true,
14+
"description": "Delta step that failed before the full archive replaced it: download, apply or install"
15+
},
16+
"error": {
17+
"type": "error",
18+
"required": true,
19+
"description": "Error the delta step returned before the full download replaced it, keeping its stable code and domain"
20+
}
21+
},
22+
"rate": 60,
23+
"owner": "Lithe"
24+
},
525
{
626
"id": "update.download.interrupted",
727
"channel": "update",
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
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

Comments
 (0)