← 中文资源

简体中文版本

构建数据差异 CLI

构建数据差异 CLI:完整覆盖 data comparison,含 Snapshot reader、Key indexer 与测试的端到端实现。

阅读英文原文

项目概述

本项目实现一个面向 data comparison 的完整系统,核心要解决的问题是 computing the rows that differ between two snapshots of a dataset and emitting a patch。整体由 Snapshot reader、Key indexer、Row comparator、Patch emitter、Summary reporter 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a floating-point field that differs by rounding noise and produces a huge, meaningless change set 作为第一类需求先行处理,而非事后再补。

架构与关键决策

数据模型为 two keyed row sets compared by primary key, classifying each row as added, removed, or changed with a field-level diff。Snapshot reader 定义其余阶段共同依赖的数据形状并在边界处校验输入;Key indexer 承载 data comparison 的正确性逻辑;Row comparator 专门处理 a floating-point field that differs by rounding noise and produces a huge, meaningless change set,在失败路径上给出明确的拒绝、重试或降级策略;Patch emitter 提供可观测性,每次操作输出带关联 id 的结构化事件;Summary reporter 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。

实施与测试

按五个阶段依次实现 Snapshot reader、Key indexer、Row comparator、Patch emitter、Summary reporter,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 data comparison 场景:先验证正常路径,再刻意触发 a floating-point field that differs by rounding noise and produces a huge, meaningless change set 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。

限制与后续

  • 单区域设计,多区域复制超出范围。
  • Snapshot reader 默认进程内,未水平共享。
  • 无鉴权层,假定部署在强制身份的边缘之后。

代码示例

# setup for data-diff-cli
pnpm init
pnpm add commander csv-parse
pnpm add -D typescript tsx vitest
data_diff_cli/
├── src/index.ts
├── src/snapshot-reader.ts
├── src/key-indexer.ts
├── tests/data_diff_cli.test.ts
└── package.json
// Snapshot reader: data comparison core
export function snapshotreader(input: SnapshotreaderInput): SnapshotreaderResult {
  // Build the snapshot reader that anchors data comparison and defines the core data shape.
  return processSnapshotreader(input);
}
// Key indexer — handles data comparison Add the key indexer so
export class Keyindexer {
  constructor(private opts: KeyindexerOptions) {}
  async run(ctx: Context): Promise<KeyindexerOutput> {
    return this.execute(ctx);
  }
}
// Row comparator: data comparison stage
export const rowcomparator = (next: Next) => async (req: Request) => {
  const out = await transform(req);
  return next(out);
};
// Patch emitter for data comparison
export async function patchemitter(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
  let acc = init();
  for await (const c of stream) acc = merge(acc, c);
  return acc;
}
// Summary reporter: data comparison finalization
export function summaryreporter(state: State): Result {
  validate(state);
  return finalize(state);
}
# run the data comparison test suite
pnpm vitest run