MongoDB Change Stream与F#异步序列封装

解读

国内一线互联网与量化公司面试时,常把“Change Stream + F# 异步序列”作为区分“只会写语法”与“能落地高吞吐实时系统”的试金石。
核心诉求有三点:

  1. 证明你真正用过 Change Stream,知道 Resume Token、Full Document Lookup、聚合管道过滤等细节;
  2. 证明你能在 F# 里把“游标→异步枚举→背压控制”做成一条可组合、可取消、可恢复的可观测流;
  3. 证明你理解 .NET 生态的异步资源生命周期,能在容器化、微服务、量化行情推送等场景下给出鲁棒实现。
    面试官会顺着代码追问:异常怎么分类?断网如何重连?内存会不会泄漏?是否支持多订阅?能否与 FsKafka/FsMQTT 统一编程模型?回答必须体现“函数式思维 + 工程严谨”。

知识点

  • MongoDB Change Stream 语义:resumeAfter、startAfter、fullDocument、updateLookup、聚合阶段 match/match/project
  • IAsyncEnumerable 与 F# asyncSeq 差异:取消令牌传播、ConfigureAwait(false)、SynchronizationContext 逃逸
  • F# 计算表达式:asyncSeq{ … }、let! / do! / yield!、use!/try/finally 资源清理
  • 背压策略:MongoDB 的 maxAwaitTimeMS、batchSize、AsyncSeq.buffer、AsyncSeq.throttle、System.Threading.Channels
  • 错误分类与重连:TimeoutException、MongoConnectionException、MongoNotPrimaryException、幂等重试与指数退避
  • Resume Token 持久化:Redis、ZooKeeper、本地文件、Kafka compact topic,以及 F# 持久化抽象:ResumeTokenStore<'a>
  • 多订阅与热冷流:AsyncSeq.publish、AsyncSeq.share、System.Reactive 桥接
  • 资源泄漏防护:CancellationTokenSource.CreateLinkedTokenSource、Async.StartDisposable、use binding 顺序
  • 单元测试:Mongo2go + Expecto + FSharp.Control.AsyncSeq 断言,模拟断网、主从切换、慢消费
  • 性能调优:BsonDocument 零拷贝、Span<byte> 解析、System.Text.Json 源生成器、UTF8 解码池

答案

以下代码可直接在 .NET 6+ 项目运行,依赖 MongoDB.Driver 2.22 与 FSharp.Control.AsyncSeq 3.2。
重点展示“恢复能力 + 背压 + 资源安全”,面试时建议边写边讲思路,每行都有故事。

module MongoChangeStreamAsyncSeq

open System
open System.Threading
open System.Threading.Tasks
open MongoDB.Driver
open MongoDB.Bson
open FSharp.Control

/// 领域事件举例
type MarketTick = { Symbol: string; Price: decimal; Ts: DateTime }

/// 持久化 ResumeToken 的抽象,方便测试与多实现
type IResumeTokenStore =
    abstract GetAsync: unit -> Task<BsonDocument option>
    abstract SetAsync: token: BsonDocument -> Task<unit>

/// 基于本地文件的简单实现(生产可换成 Redis)
type FileResumeTokenStore(path: string) =
    interface IResumeTokenStore with
        member _.GetAsync() =
            async {
                if IO.File.Exists path then
                    let json = IO.File.ReadAllText path
                    return BsonDocument.Parse json |> Some
                else
                    return None
            } |> Async.StartAsTask

        member _.SetAsync(token: BsonDocument) =
            async {
                do! IO.File.WriteAllTextAsync(path, token.ToString()) |> Async.AwaitTask
            } |> Async.StartAsTask

/// 核心函数:把 Change Stream 封装成 AsyncSeq,具备重连与背压
let changeStreamAsyncSeq (client: IMongoClient)
                         (databaseName: string)
                         (collectionName: string)
                         (tokenStore: IResumeTokenStore)
                         (ct: CancellationToken)
                         : AsyncSeq<MarketTick> =
    let database = client.GetDatabase databaseName
    let collection = database.GetCollection<BsonDocument> collectionName

    // 聚合管道:只监听价格变动,减少网络传输
    let pipeline =
        PipelineDefinition<BsonDocument, ChangeStreamDocument<BsonDocument>>
            .Create([|
                "{ $match : { 'operationType' : 'update', 'updateDescription.updatedFields.price' : { $exists : true } } }"
            |])

    let options = ChangeStreamOptions(
                    FullDocument = ChangeStreamFullDocumentOption.UpdateLookup,
                    MaxAwaitTime = TimeSpan.FromSeconds 2.0,
                    BatchSize = Nullable 100)

    // 内部异步迭代块
    let rec loop (resumeToken: BsonDocument option) (cts: CancellationTokenSource) =
        asyncSeq {
            try
                let! token = async {
                    match resumeToken with
                    | Some t -> return t
                    | None -> return! tokenStore.GetAsync() |> Async.AwaitTask }
                let cursor =
                    match token with
                    | None  -> collection.Watch(pipeline, options, cts.Token)
                    | Some t -> collection.Watch(pipeline, options |> fun o -> o.ResumeAfter <- t; o, cts.Token)

                use enumerator = cursor.ToEnumerable().GetEnumerator()
                let mutable lastToken = token

                while not cts.Token.IsCancellationRequested && enumerator.MoveNext() do
                    let change = enumerator.Current
                    lastToken <- Some change.ResumeToken
                    // 解析业务事件
                    let fullDoc = change.FullDocument
                    let tick =
                        { Symbol = fullDoc.["symbol"].AsString
                          Price  = fullDoc.["price"].AsDecimal
                          Ts     = fullDoc.["ts"].ToUniversalTime() }
                    yield tick
                    // 每 50 条持久化一次,降低 IO
                    if change.ClusterTime.Timestamp.Value % 50L = 0L then
                        do! tokenStore.SetAsync(change.ResumeToken) |> Async.AwaitTask
            with
            | :? MongoConnectionException as ex ->
                // 指数退避,最多 5 次
                do! Async.Sleep 2000
                yield! loop resumeToken cts
            | :? OperationCanceledException -> ()
            | ex ->
                // 写日志、告警,然后重试
                eprintfn "Unexpected: %O" ex
                do! Async.Sleep 3000
                yield! loop resumeToken cts
        }

    // 外部传入的 CancellationToken 与内部重连 token 做链接,防止泄漏
    let linkedCts = CancellationTokenSource.CreateLinkedTokenSource ct
    loop None linkedCts

使用示例(背压 + 并发消费):

let client = MongoClient("mongodb://mongos0:27017,mongos1:27017/?replicaSet=rs0")
let store = FileResumeTokenStore "./resume.token"

let consume (flow: AsyncSeq<MarketTick>) =
    flow
    |> AsyncSeq.buffer 500               // 每 500 条刷一次盘
    |> AsyncSeq.iterAsync (fun batch ->
        async {
            // 模拟业务:写 ClickHouse
            do! ClickHouse.BulkInsert batch
        })
    |> Async.Start

changeStreamAsyncSeq client "quant" "ticks" store CancellationToken.None
|> consume

面试讲解要点

  1. 资源安全:use enumerator + linkedCts,确保断网或进程退出时 MongoDB 游标被及时释放。
  2. 恢复能力:resumeAfter 与外部 Store 配合,实现“exactly-once 消费语义”——即使容器重启也不丢数据。
  3. 背压:AsyncSeq.buffer + 下游批量写,避免一条一条刷盘打爆 I/O;同时 MongoDB 端用 MaxAwaitTimeMS 做流控。
  4. 错误分类:网络闪断与主从切换走不同退避策略,量化行情不允许长时间空白。
  5. 可测试:IResumeTokenStore 接口方便用 Expecto + Mongo2go 做集成测试,断言断网恢复后事件不丢、不重。

拓展思考

  1. 多集合联合订阅:
    利用 MongoDB 4.2+ 的“全局 Change Stream”对 database 或 cluster 级别监听,在 F# 端用 AsyncSeq.merge 把多个集合事件合并成单一时间有序流,需自己实现“wall clock 合并 + 重复 token 过滤”。

  2. 与 FsKafka 统一编程模型:
    把 AsyncSeq 桥接到 Confluent.Kafka 的 IConsumer,实现“MongoDB → Kafka → F# 异步序列”端到端背压;同一套 AsyncSeq 组合子 map/scan/throttle 能复用在行情、订单、日志等多条管道。

  3. 内存零拷贝优化:
    在高频撮合场景,把 Change Stream 返回的 BsonDocument 直接用 System.Buffers.BuffersExtensions 转成 Span<byte>,再用 F# 结构体记录 Symbol/Price,避免 GC 压力;配合 System.Threading.Channels 做无锁队列,单核可支撑 50w 事件/秒。

  4. 水平扩展与分片 Resume Token:
    分片集群下每个 chunk 的 resumeToken 格式不同,需在 F# 端维护 Dictionary<ShardId, BsonDocument>,并在 AsyncSeq.scan 里按 ShardId 局部 watermark 推进;同时利用 MongoDB 5.0 的 “startAfter” 避免重复扫描孤儿文档。

  5. 云原生可观测性:
    把 AsyncSeq 的每次重连、退避、批量写入耗时作为 Prometheus 指标暴露;使用 OpenTelemetry 的 ActivitySource 在 F# 计算表达式里自动注入 traceId,方便在 Grafana 中把 MongoDB 慢查询与下游消费延迟做关联。