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

zat.dev/zlay

atproto relay in zig · mirror of https://tangled.org/zat.dev/zlay

0
0
114 lines · 5.1 KB Raw History
const std = @import("std");
const index = @import("internal/collection_index/index.zig");
const collection = "app.bsky.feed.post";
fn did(buf: []u8, n: usize) []const u8 {
    return std.fmt.bufPrint(buf, "did:plc:{d:0>24}", .{n}) catch unreachable;
}
pub fn main(init: std.process.Init) !void {
    const args = try init.minimal.args.toSlice(init.arena.allocator());
    if (args.len != 5) return error.ExpectedPathModeBatchAcknowledged;
    const batch = try std.fmt.parseInt(usize, args[3], 10);
    const acknowledged = try std.fmt.parseInt(usize, args[4], 10);
    if (batch == 0 or batch > 64) return error.InvalidBatch;
    var ci = try index.CollectionIndex.open(init.gpa, init.io, args[1]);
    defer ci.deinit();
    var out = std.Io.File.stdout().writer(init.io, &.{});
    if (std.mem.eql(u8, args[2], "group-write")) {
        try ci.enableBatching(.{ .max_batch = 16, .queue_limit = 64, .delay_ns = 1_000_000 });
        var n: usize = 0;
        while (n < 2_000_000) {
            var workers: [16]RecoveryWriter = undefined;
            var threads: [16]std.Thread = undefined;
            var started: usize = 0;
            {
                defer for (threads[0..started]) |thread| thread.join();
                for (&workers, &threads, 0..) |*worker, *thread, i| {
                    worker.* = .{ .ci = &ci, .first = n + i * batch, .count = batch };
                    thread.* = try std.Thread.spawn(.{}, RecoveryWriter.run, .{worker});
                    started += 1;
                }
            }
            for (workers) |worker| try worker.outcome;
            n += 16 * batch;
            try out.interface.print("{d}\n", .{n});
        }
        return;
    }
    if (std.mem.eql(u8, args[2], "group-verify")) {
        if (acknowledged % (16 * batch) != 0) return error.InvalidAcknowledgement;
        const limit = acknowledged + 32 * batch;
        const seen = try init.gpa.alloc(bool, limit);
        defer init.gpa.free(seen);
        @memset(seen, false);
        var bytes: [4096]u8 = undefined;
        var spans: [100]index.Span = undefined;
        var cursor_buf: [64]u8 = undefined;
        var cursor: ?[]const u8 = null;
        var total: usize = 0;
        while (true) {
            const page = try ci.listReposByCollection(collection, 100, cursor, &bytes, &spans);
            for (0..page.count) |i| {
                const id = page.getDid(i);
                if (!std.mem.startsWith(u8, id, "did:plc:")) return error.UnexpectedDid;
                const ordinal = try std.fmt.parseInt(usize, id[8..], 10);
                if (ordinal >= limit or seen[ordinal] or !try ci.hasCollectionsChecked(id)) return error.LostOrTornBatch;
                seen[ordinal] = true;
                total += 1;
            }
            const last = page.last_did orelse break;
            @memcpy(cursor_buf[0..last.len], last);
            cursor = cursor_buf[0..last.len];
        }
        for (seen[0..acknowledged]) |present| if (!present) return error.LostAcknowledgedPair;
        for (0..32) |i| {
            const group = seen[acknowledged + i * batch ..][0..batch];
            for (group) |present| if (present != group[0]) return error.TornPageRequest;
        }
        try out.interface.print("{d},{d},{d}\n", .{ batch, acknowledged, total });
        return;
    }
    if (std.mem.eql(u8, args[2], "write")) {
        var n: usize = 0;
        while (n < 2_000_000) {
            var keys: [64][64]u8 = undefined;
            var ids: [64][]const u8 = undefined;
            for (0..batch) |i| ids[i] = did(&keys[i], n + i);
            try ci.addCollectionPage(ids[0..batch], collection);
            n += batch;
            try out.interface.print("{d}\n", .{n});
        }
    } else if (std.mem.eql(u8, args[2], "verify")) {
        var n: usize = 0;
        var bytes: [4096]u8 = undefined;
        var spans: [100]index.Span = undefined;
        var cursor_buf: [64]u8 = undefined;
        var cursor: ?[]const u8 = null;
        var expected: [64]u8 = undefined;
        while (true) {
            const page = try ci.listReposByCollection(collection, 100, cursor, &bytes, &spans);
            for (0..page.count) |i| {
                const want = did(&expected, n);
                if (!std.mem.eql(u8, page.getDid(i), want) or !ci.hasCollections(want)) return error.LostOrTornBatch;
                n += 1;
            }
            const last = page.last_did orelse break;
            @memcpy(cursor_buf[0..last.len], last);
            cursor = cursor_buf[0..last.len];
        }
        if (n < acknowledged or n > acknowledged + 2 * batch or n % batch != 0) return error.AcknowledgementMismatch;
        try out.interface.print("{d},{d},{d}\n", .{ batch, acknowledged, n });
    } else return error.InvalidMode;
}

const RecoveryWriter = struct {
    ci: *index.CollectionIndex,
    first: usize,
    count: usize,
    outcome: anyerror!void = {},
    fn run(self: *@This()) void {
        var keys: [64][64]u8 = undefined;
        var ids: [64][]const u8 = undefined;
        for (0..self.count) |i| ids[i] = did(&keys[i], self.first + i);
        self.outcome = self.ci.addCollectionPage(ids[0..self.count], collection);
    }
};