任务
按 parentId 建立子节点索引,没有父节点的作为根;累加子节点数,找出时长最大的根,父节点缺失者记为孤儿。
契约
- 输入:JSON 对象:{ spans: [{ id, parentId?, name, durationMs }] }
- 输出:JSON 对象:{ roots, slowestRoot, orphanIds }
样例
- 输入
{"spans":[{"id":"r1","name":"GET /checkout","durationMs":120},{"id":"c1","parentId":"r1","name":"db query","durationMs":80},{"id":"r2","name":"GET /health","durationMs":3}]}-> 期望{"roots":[{"id":"r1","name":"GET /checkout","childCount":1,"durationMs":120},{"id":"r2","name":"GET /health","childCount":0,"durationMs":3}],"slowestRoot":"GET /checkout","orphanIds":[]}。两个根 Span、一个子节点,且没有孤儿。 - 输入
{"spans":[{"id":"r1","name":"worker job","durationMs":50},{"id":"orphan","parentId":"missing","name":"publish","durationMs":10}]}-> 期望{"roots":[{"id":"r1","name":"worker job","childCount":0,"durationMs":50}],"slowestRoot":"worker job","orphanIds":["orphan"]}。引用了不存在父节点的 Span 会被报告,而不是被静默丢弃。
参考实现
function solve({ spans }) {
const byId = new Map(spans.map((s) => [s.id, s]));
const childCount = new Map();
for (const span of spans) {
if (!span.parentId) continue;
childCount.set(span.parentId, (childCount.get(span.parentId) ?? 0) + 1);
}
const roots = spans
.filter((s) => !s.parentId)
.map((s) => ({ id: s.id, name: s.name, childCount: childCount.get(s.id) ?? 0, durationMs: s.durationMs }))
.sort((a, b) => b.durationMs - a.durationMs || a.id.localeCompare(b.id));
const orphanIds = spans
.filter((s) => s.parentId && !byId.has(s.parentId))
.map((s) => s.id)
.sort();
return { roots, slowestRoot: roots.length ? roots[0].name : null, orphanIds };
}
为什么有效
追踪后端存的是扁平的 Span 行。在客户端重建树,才能推断出哪个入口吸收了延迟。
没有父节点的是根;父节点不存在的子节点是孤儿,而不是根。