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

zat.dev/zlay

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

0
0
144 lines · 6.5 KB Raw History
const std = @import("std");
const index = @import("internal/collection_index/index.zig");
extern "c" fn raise(signal: c_int) c_int;
fn mix(input: u64) u64 {
    var n = input +% 0x9e3779b97f4a7c15;
    n = (n ^ (n >> 30)) *% 0xbf58476d1ce4e5b9;
    n = (n ^ (n >> 27)) *% 0x94d049bb133111eb;
    return n ^ (n >> 31);
}
fn did(out: *[32]u8, n: usize) []const u8 {
    @memcpy(out[0..8], "did:plc:");
    const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
    const bits: u128 = (@as(u128, mix(n)) << 64) | mix(n + 0x12345678);
    for (0..24) |i| out[8 + i] = alphabet[@as(u5, @truncate(bits >> @as(u7, @intCast(i * 5))))];
    return out;
}
fn collection(out: []u8, n: usize) []const u8 {
    if (n == 0) return "app.bsky.feed.post";
    return std.fmt.bufPrint(out, "dev.offline.collection{d:0>2}", .{n}) catch unreachable;
}
fn wanted(n: usize, total: usize, deleted: bool) bool {
    return n < total and (!deleted or n % 1000 != 0);
}
pub fn main(init: std.process.Init) !void {
    const args = try init.minimal.args.toSlice(init.arena.allocator());
    if (args.len != 6) return error.ExpectedPathPhaseStartEndDeleted;
    const begin = try std.fmt.parseInt(usize, args[3], 10);
    const end = try std.fmt.parseInt(usize, args[4], 10);
    const deleted = std.mem.eql(u8, args[5], "1");
    var ci = try index.CollectionIndex.open(std.heap.c_allocator, init.io, args[1]);
    defer ci.deinit();
    const encoding = init.environ_map.get("ZKV_TABLE_ENCODING") orelse "legacy";
    if (comptime @hasField(@TypeOf(ci.db.options), "table_encoding")) {
        ci.db.options.table_encoding = std.meta.stringToEnum(@TypeOf(ci.db.options.table_encoding), encoding) orelse return error.InvalidEncoding;
    } else if (!std.mem.eql(u8, encoding, "legacy")) return error.UnsupportedEncoding;
    const started = std.Io.Clock.awake.now(init.io);
    const phase = args[2];
    if (std.mem.eql(u8, phase, "pages")) {
        const samples = try std.heap.c_allocator.alloc(i64, 10000);
        defer std.heap.c_allocator.free(samples);
        var digest = std.hash.Wyhash.init(0);
        var rows: usize = 0;
        for (samples, 0..) |*sample, i| {
            var key: [32]u8 = undefined;
            var buffer: [4096]u8 = undefined;
            var spans: [100]index.Span = undefined;
            const cursor = did(&key, mix(i + 17) % end);
            const before = std.Io.Clock.awake.now(init.io);
            const page = try ci.listReposByCollection("app.bsky.feed.post", 100, cursor, &buffer, &spans);
            sample.* = @intCast(before.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds());
            for (0..page.count) |j| digest.update(page.getDid(j));
            rows += page.count;
        }
        const elapsed = started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds();
        std.mem.sort(i64, samples, {}, std.sort.asc(i64));
        std.debug.print("pages,{d},{d},{d},{d},{d},{d}\n", .{ rows, elapsed, samples[5000], samples[9500], samples[9900], digest.final() });
        return;
    }
    var operations: usize = 0;
    if (std.mem.eql(u8, phase, "add") or std.mem.eql(u8, phase, "duplicate") or std.mem.eql(u8, phase, "crash-add")) {
        var at = begin;
        while (at < end) {
            const count: usize = @min(4096, end - at);
            var keys: [4096][32]u8 = undefined;
            var ids: [4096][]const u8 = undefined;
            for (0..count) |j| ids[j] = did(&keys[j], at + j);
            try ci.addCollectionPage(ids[0..count], "app.bsky.feed.post");
            for (1..32) |c| {
                var selected: [4096][]const u8 = undefined;
                var len: usize = 0;
                for (0..count) |j| if ((at + j) % 31 + 1 == c) {
                    selected[len] = ids[j];
                    len += 1;
                };
                var name: [64]u8 = undefined;
                if (len > 0) try ci.addCollectionPage(selected[0..len], collection(&name, c));
            }
            operations += count * 2;
            at += count;
        }
    } else if (std.mem.eql(u8, phase, "delete") or std.mem.eql(u8, phase, "refill")) {
        for (begin..end) |n| if (n % 1000 == 0) {
            var key: [32]u8 = undefined;
            const id = did(&key, n);
            if (std.mem.eql(u8, phase, "delete")) {
                try ci.removeAll(id);
            } else {
                try ci.addCollection(id, "app.bsky.feed.post");
                var name: [64]u8 = undefined;
                try ci.addCollection(id, collection(&name, n % 31 + 1));
            }
            operations += 1;
        };
    } else if (std.mem.eql(u8, phase, "settle")) {
        try ci.db.flush();
        while (try ci.db.compact()) {}
        try ci.db.collect();
    } else if (std.mem.eql(u8, phase, "verify")) {
        var counts: [32]u64 = @splat(0);
        var sums: [32]u64 = @splat(0);
        for (0..end) |n| {
            var key: [32]u8 = undefined;
            const id = did(&key, n);
            const live = wanted(n, end, deleted);
            if (ci.hasCollections(id) != live) return error.BadReverseMembership;
            if (live) {
                const h = std.hash.Wyhash.hash(0, id);
                counts[0] += 1;
                counts[n % 31 + 1] += 1;
                sums[0] +%= h;
                sums[n % 31 + 1] +%= h;
            }
        }
        for (0..32) |c| {
            var count: u64 = 0;
            var sum: u64 = 0;
            var name: [64]u8 = undefined;
            var cursor_bytes: [32]u8 = undefined;
            var cursor: ?[]const u8 = null;
            while (true) {
                var buffer: [4096]u8 = undefined;
                var spans: [100]index.Span = undefined;
                const page = try ci.listReposByCollection(collection(&name, c), 100, cursor, &buffer, &spans);
                for (0..page.count) |i| {
                    const id = page.getDid(i);
                    sum +%= std.hash.Wyhash.hash(0, id);
                    count += 1;
                }
                const last = page.last_did orelse break;
                if (last.len != 32) return error.InvalidDid;
                @memcpy(&cursor_bytes, last);
                cursor = &cursor_bytes;
            }
            if (count != counts[c] or sum != sums[c]) return error.IncorrectForwardMembership;
            operations += count;
        }
    } else return error.InvalidPhase;
    const elapsed = started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds();
    std.debug.print("space,{s},{d},{d}\n", .{ phase, operations, elapsed });
    if (std.mem.eql(u8, phase, "crash-add")) {
        _ = raise(9);
        return error.CrashSignalFailed;
    }
}