~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
195 lines · 6.9 KB Raw History
//! One bounded getRepo network/CAR attempt.
//!
//! Upstream's attempt deadline covers the redirected response stream and
//! LoadCompleteFromCAR, but not handler emission or durable writes. Keeping
//! those boundaries here prevents a syntactically complete but structurally
//! partial CAR from escaping the timeout/retry policy.

const std = @import("std");
const zat = @import("zat");
const fetched_car = @import("fetched_car.zig");
const repos = @import("repos.zig");
const segment = @import("../../storage/segment.zig");

const Io = std.Io;
const Allocator = std.mem.Allocator;

fn prepareOwned(parse_allocator: Allocator, source: []const u8) !repos.PreparedRepo {
    const owned_car = try parse_allocator.dupe(u8, source);
    return repos.prepareRepo(parse_allocator, owned_car);
}

pub const Prepared = struct {
    fetched: fetched_car.FetchedCar,
    repo: repos.PreparedRepo,

    pub fn deinit(self: *Prepared, io: Io) void {
        self.fetched.deinit(io);
        self.* = undefined;
    }
};

pub const Outcome = union(enum) {
    ok: Prepared,
    rate_limited: ?u64,
    not_found,
    unavailable,
    transient,
    permanent,

    fn deinit(self: *Outcome, io: Io) void {
        switch (self.*) {
            .ok => |*prepared| prepared.deinit(io),
            else => {},
        }
    }
};

pub fn fetch(
    allocator: Allocator,
    parse_allocator: Allocator,
    io: Io,
    scratch_dir: []const u8,
    relay_http: []const u8,
    did: []const u8,
    final_host: *fetched_car.FinalHost,
) !Outcome {
    const Task = struct {
        allocator: Allocator,
        parse_allocator: Allocator,
        io: Io,
        scratch_dir: []const u8,
        relay_http: []const u8,
        did: []const u8,
        final_host: *fetched_car.FinalHost,
        progress: *fetched_car.TransferProgress,
        done: Io.Event = .unset,
        result: ?(anyerror!Outcome) = null,

        fn run(self: *@This()) void {
            self.result = self.runAttempt();
            self.done.set(self.io);
        }

        fn runAttempt(self: *@This()) !Outcome {
            var outcome = try fetched_car.fetchOnceTracked(
                self.allocator,
                self.io,
                self.scratch_dir,
                self.relay_http,
                self.did,
                self.final_host,
                self.progress,
            );
            return switch (outcome) {
                .ok => |*fetched| blk: {
                    errdefer fetched.deinit(self.io);
                    // Upstream's LoadCompleteFromCAR owns the loaded repository
                    // through handler emission. Do the same here: scratch stays
                    // the network/download shape, while the bounded parse
                    // allocator owns every byte the lazy MST and record rows can
                    // reference. Carrying borrowed mmap slices into concurrent
                    // archive appends made an unmap/lifetime error a segfault.
                    //
                    // That ownership is what `prepareOwned`'s dupe provides, per
                    // worker. This used to also run under a single process-wide
                    // mutex, which was not required by the ownership rule above
                    // and serialized every worker's parse behind one core:
                    // upstream parses concurrently across all backfill workers
                    // and holds no such lock. It capped whole-network backfill
                    // at ~4 repos/s against upstream's documented ~16 hours.
                    const prepared = try prepareOwned(self.parse_allocator, fetched.bytes);
                    fetched.unmap(self.io);
                    break :blk .{ .ok = .{ .fetched = fetched.*, .repo = prepared } };
                },
                .rate_limited => |delay| .{ .rate_limited = delay },
                .not_found => .not_found,
                .unavailable => .unavailable,
                .transient => .transient,
                .permanent => .permanent,
            };
        }
    };

    var progress: fetched_car.TransferProgress = .{};
    var task: Task = .{
        .allocator = allocator,
        .parse_allocator = parse_allocator,
        .io = io,
        .scratch_dir = scratch_dir,
        .relay_http = relay_http,
        .did = did,
        .final_host = final_host,
        .progress = &progress,
    };
    var future = try io.concurrent(Task.run, .{&task});
    fetched_car.waitForTransfer(io, &task.done, &future, &progress) catch |wait_err| {
        // cancel() has joined the attempt. If CPU-bound preparation crossed
        // the deadline before observing cancellation, reclaim the completed
        // outcome here.
        if (task.result) |attempt| if (attempt) |value| {
            var owned = value;
            owned.deinit(io);
        } else |_| {};
        return wait_err;
    };
    _ = future.await(io);
    return try task.result.?;
}

test "prepared repo emission owns the CAR after its source is destroyed" {
    const testing = std.testing;
    var prepared_arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer prepared_arena.deinit();
    const prepared_alloc = prepared_arena.allocator();
    var prepared: repos.PreparedRepo = undefined;

    {
        var source_arena = std.heap.ArenaAllocator.init(testing.allocator);
        defer source_arena.deinit();
        const source = source_arena.allocator();
        const payload = try source.dupe(u8, "source-backed opaque record");
        const record_cid = try zat.cbor.Cid.forDagCbor(source, payload);
        var tree = zat.mst.Mst.init(source);
        try tree.put("app.bsky.feed.post/3k2abcdefghij", record_cid);
        const data_cid = try tree.rootCid();
        const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(29));
        const did = try keypair.did(source);
        const signed = try zat.signCommit(source, .{
            .did = did,
            .rev = "3k2abcdefghij",
            .data = data_cid,
        }, &keypair);
        var blocks: std.ArrayList(zat.car.Block) = .empty;
        try blocks.append(source, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
        try tree.collectBlocks(&blocks);
        try blocks.append(source, .{ .cid_raw = record_cid.raw, .data = payload });
        const car_bytes = try zat.car.writeAlloc(source, .{
            .roots = &.{signed.cid},
            .blocks = blocks.items,
        });
        prepared = try prepareOwned(prepared_alloc, car_bytes);
    }

    var drops: repos.DropCounts = .{};
    const Sink = struct {
        rows: usize = 0,

        fn emit(self: *@This(), event: segment.Event) anyerror!void {
            try std.testing.expectEqualStrings("source-backed opaque record", event.payload);
            self.rows += 1;
        }
    };
    var sink: Sink = .{};
    _ = try repos.emitPrepared(
        prepared_alloc,
        &prepared,
        "",
        1,
        .create,
        &drops,
        &sink,
        Sink.emit,
    );
    try testing.expectEqual(@as(usize, 1), sink.rows);
}