← 中文资源

简体中文版本

构建流窗口聚合器

构建流窗口聚合器:完整覆盖 stream processing,含 Event ingest、Window manager 与测试的端到端实现。

阅读英文原文

项目概述

本项目实现一个面向 stream processing 的完整系统,核心要解决的问题是 computing tumbling and sliding window aggregates over an unbounded event stream with bounded memory。整体由 Event ingest、Window manager、Aggregate function、Late event handler、Watermark tracker 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a late event that arrives after its window closed and must either update a closed result or be dropped to a side output 作为第一类需求先行处理,而非事后再补。

架构与关键决策

数据模型为 a set of windows each holding a partial aggregate, closed by a watermark that advances with observed event timestamps。Event ingest 定义其余阶段共同依赖的数据形状并在边界处校验输入;Window manager 承载 stream processing 的正确性逻辑;Aggregate function 专门处理 a late event that arrives after its window closed and must either update a closed result or be dropped to a side output,在失败路径上给出明确的拒绝、重试或降级策略;Late event handler 提供可观测性,每次操作输出带关联 id 的结构化事件;Watermark tracker 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。

实施与测试

按五个阶段依次实现 Event ingest、Window manager、Aggregate function、Late event handler、Watermark tracker,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 stream processing 场景:先验证正常路径,再刻意触发 a late event that arrives after its window closed and must either update a closed result or be dropped to a side output 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。

限制与后续

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

代码示例

# setup for stream-window-aggregator
pnpm init
pnpm add fastify redis
pnpm add -D typescript tsx vitest
stream_window_aggregator/
├── src/index.ts
├── src/event-ingest.ts
├── src/window-manager.ts
├── tests/stream_window_aggregator.test.ts
└── package.json
// Event ingest: stream processing core
export function eventingest(input: EventingestInput): EventingestResult {
  // Build the event ingest that anchors stream processing and defines the core data shape.
  return processEventingest(input);
}
// Window manager — handles stream processing Add the window manager so
export class Windowmanager {
  constructor(private opts: WindowmanagerOptions) {}
  async run(ctx: Context): Promise<WindowmanagerOutput> {
    return this.execute(ctx);
  }
}
// Aggregate function: stream processing stage
export const aggregatefunction = (next: Next) => async (req: Request) => {
  const out = await transform(req);
  return next(out);
};
// Late event handler for stream processing
export async function lateeventhandler(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
  let acc = init();
  for await (const c of stream) acc = merge(acc, c);
  return acc;
}
// Watermark tracker: stream processing finalization
export function watermarktracker(state: State): Result {
  validate(state);
  return finalize(state);
}
# run the stream processing test suite
pnpm vitest run