//! capture — a stoppable firehose reader for bootstrap live capture //! //! zat v0.3.16's shouldStop handler hook made this a thin wrapper: raw //! frames flow to the consumer like the steady-state path, and the //! cooperative stop flag ends subscribe cleanly at the merge cutover //! (checked per frame and per reconnect; pair requestStop with //! future.cancel to unblock an idle read). zat tracks the reconnect //! cursor internally via peekSeq. const std = @import("std"); const zat = @import("zat"); const ingest = @import("../ingest.zig"); const Io = std.Io; const Allocator = std.mem.Allocator; const log = std.log.scoped(.stream); pub const Capture = struct { allocator: Allocator, io: Io, /// ws(s):// host URL, path fixed to subscribeRepos like zat's client upstream: []const u8, consumer: *ingest.Consumer, stop: std.atomic.Value(bool) = .init(false), connected: std.atomic.Value(bool) = .init(false), finished: std.atomic.Value(bool) = .init(false), /// initial cursor (shared relay cursor); zat advances it per frame last_seq: ?i64 = null, pub fn requestStop(self: *Capture) void { self.stop.store(true, .release); } /// blocks until requestStop; zat handles reconnect with backoff pub fn run(self: *Capture) void { defer self.finished.store(true, .release); var client = zat.FirehoseClient.init(self.io, self.allocator, .{ .hosts = &.{self.upstream}, .cursor = self.last_seq, .max_message_size = 2 * 1024 * 1024, }); defer client.deinit(); client.subscribe(self) catch |err| { if (!self.stop.load(.acquire)) log.warn("bootstrap capture ended: {s}", .{@errorName(err)}); }; } pub fn onConnect(self: *Capture, _: []const u8) void { self.connected.store(true, .release); } /// Backfill must not begin until the live socket is attached. Otherwise a /// repository can mutate after getRepo is served but before capture's /// websocket handshake, permanently losing those intermediate commits. pub fn waitConnected(self: *Capture) !void { while (!self.connected.load(.acquire)) { if (self.finished.load(.acquire)) return error.LiveCaptureEndedBeforeConnect; try self.io.sleep(.fromMilliseconds(10), .awake); } } pub fn onRawFrame(self: *Capture, data: []const u8) !void { try self.consumer.onRawFrame(data); } pub fn shouldStop(self: *Capture) bool { return self.stop.load(.acquire) or self.consumer.shouldStop(); } /// A capture which ends before an explicit stop invalidates bootstrap. /// Prefer the pipeline's original fatal cause when one exists. pub fn unexpectedFailure(self: *Capture) ?anyerror { if (!self.finished.load(.acquire) or self.stop.load(.acquire)) return null; return self.consumer.fatalError() orelse error.LiveCaptureEnded; } pub fn onError(self: *Capture, err: anyerror) void { if (!self.stop.load(.acquire)) log.warn("bootstrap capture: {s}, reconnecting", .{@errorName(err)}); } };