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

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
73 lines · 2.9 KB Raw History
//! walk an entire repo in one request: com.atproto.sync.getRepo returns the
//! whole repo as a CAR (every record + the MST that indexes them), which you
//! walk locally.
//!
//! run: zig build example-walk-a-repo

const std = @import("std");
const zat = @import("zat");

/// a running tally of records per collection, built as we walk. keys stay in
/// first-seen order, which — since the MST yields them sorted — is by collection.
const Tally = struct {
    allocator: std.mem.Allocator,
    counts: std.StringArrayHashMapUnmanaged(u64) = .empty,

    fn onEntry(ctx: *anyopaque, entry: zat.mst.WalkEntry) anyerror!void {
        const self: *Tally = @ptrCast(@alignCast(ctx));
        // MST keys are "collection/rkey"; the collection is everything before the slash.
        const slash = std.mem.indexOfScalar(u8, entry.key, '/') orelse return;
        const gop = try self.counts.getOrPut(self.allocator, entry.key[0..slash]);
        if (!gop.found_existing) gop.value_ptr.* = 0;
        gop.value_ptr.* += 1;
    }
};

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const allocator = init.gpa;

    const did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz"; // atproto.com

    // find the account's PDS (see the "resolve an identity" recipe for this chain)
    var did_resolver = zat.DidResolver.init(io, allocator);
    defer did_resolver.deinit();
    var doc = try did_resolver.resolve(zat.Did.parse(did).?);
    defer doc.deinit();
    const endpoint = doc.pdsEndpoint() orelse return error.NoPdsEndpoint;

    // one GET pulls the entire repo as a CAR file
    const url = try std.fmt.allocPrint(
        allocator,
        "{s}/xrpc/com.atproto.sync.getRepo?did={s}",
        .{ endpoint, did },
    );
    defer allocator.free(url);
    var transport = zat.HttpTransport.initWithUserAgent(io, allocator, "myapp/1.0 (+https://example.com)");
    defer transport.deinit();
    var res = try transport.fetch(.{ .url = url });
    defer res.deinit(allocator);

    // decoding the CAR + walking the MST is transient — arena it, free at once
    var arena_state = std.heap.ArenaAllocator.init(allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();

    // decode the signed commit, then load the MST it points at from the CAR blocks
    const loaded = try zat.loadCommitFromCAR(arena, res.body);
    const root = loaded.commit.data_cid; // MST root CID
    var mst = try zat.mst.Mst.loadFromBlocks(arena, loaded.repo_car, root);

    // walk every record the MST indexes, tallying by collection
    var tally = Tally{ .allocator = arena };
    try mst.walk(.{ .ctx = &tally, .entryFn = Tally.onEntry });

    var total: u64 = 0;
    var it = tally.counts.iterator();
    while (it.next()) |kv| {
        std.debug.print("{d:>6}  {s}\n", .{ kv.value_ptr.*, kv.key_ptr.* });
        total += kv.value_ptr.*;
    }
    const n = tally.counts.count();
    std.debug.print("{d:>6}  records across {d} collections\n", .{ total, n });
}