项目概述
本项目实现一个面向 metrics collection 的完整系统,核心要解决的问题是 scraping metrics from many endpoints on a schedule and exposing them for querying without losing samples。整体由 Scrape scheduler、Target manager、Sample parser、Downsampler、Query store 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a target that stalls and blocks the scrape loop, delaying samples for every other target in the same batch 作为第一类需求先行处理,而非事后再补。
架构与关键决策
数据模型为 a time-indexed store of samples keyed by metric name and label set, filled by periodic scrapes of target exposition endpoints。Scrape scheduler 定义其余阶段共同依赖的数据形状并在边界处校验输入;Target manager 承载 metrics collection 的正确性逻辑;Sample parser 专门处理 a target that stalls and blocks the scrape loop, delaying samples for every other target in the same batch,在失败路径上给出明确的拒绝、重试或降级策略;Downsampler 提供可观测性,每次操作输出带关联 id 的结构化事件;Query store 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。
实施与测试
按五个阶段依次实现 Scrape scheduler、Target manager、Sample parser、Downsampler、Query store,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 metrics collection 场景:先验证正常路径,再刻意触发 a target that stalls and blocks the scrape loop, delaying samples for every other target in the same batch 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。
限制与后续
- 单区域设计,多区域复制超出范围。
- Scrape scheduler 默认进程内,未水平共享。
- 无鉴权层,假定部署在强制身份的边缘之后。
代码示例
# setup for metrics-aggregator-pull
pnpm init
pnpm add fastify undici prom-client
pnpm add -D typescript tsx vitest
metrics_aggregator_pull/
├── src/index.ts
├── src/scrape-scheduler.ts
├── src/target-manager.ts
├── tests/metrics_aggregator_pull.test.ts
└── package.json
// Scrape scheduler: metrics collection core
export function scrapescheduler(input: ScrapeschedulerInput): ScrapeschedulerResult {
// Build the scrape scheduler that anchors metrics collection and defines the core data shape.
return processScrapescheduler(input);
}
// Target manager — handles metrics collection Add the target manager so
export class Targetmanager {
constructor(private opts: TargetmanagerOptions) {}
async run(ctx: Context): Promise<TargetmanagerOutput> {
return this.execute(ctx);
}
}
// Sample parser: metrics collection stage
export const sampleparser = (next: Next) => async (req: Request) => {
const out = await transform(req);
return next(out);
};
// Downsampler for metrics collection
export async function downsampler(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
let acc = init();
for await (const c of stream) acc = merge(acc, c);
return acc;
}
// Query store: metrics collection finalization
export function querystore(state: State): Result {
validate(state);
return finalize(state);
}
# run the metrics collection test suite
pnpm vitest run