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

zat.dev/zlay

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

0
0
124 lines · 4.6 KB Raw History
const std = @import("std");
const Io = std.Io;

pub const Receipt = struct {
    io: Io = undefined,
    seq: ?u64 = null,
    mutex: Io.Mutex = .init,
    condition: Io.Condition = .init,
    result: ?bool = null,
    retry_needed: ?*std.atomic.Value(bool) = null,

    pub fn complete(self: *Receipt, success: bool) void {
        self.mutex.lockUncancelable(self.io);
        defer self.mutex.unlock(self.io);
        self.result = success;
        if (!success) {
            if (self.retry_needed) |retry| retry.store(true, .release);
        }
        self.condition.signal(self.io);
    }

    fn read(self: *Receipt, wait: bool) ?bool {
        self.mutex.lockUncancelable(self.io);
        defer self.mutex.unlock(self.io);
        while (wait and self.result == null) self.condition.waitUncancelable(self.io, &self.mutex);
        return self.result;
    }
};

pub const Progress = struct {
    const capacity = 256;
    receipts: [capacity]Receipt = @splat(.{}),
    head: usize = 0,
    count: usize = 0,
    failed: bool = false,
    retry_needed: std.atomic.Value(bool) = .{ .raw = false },

    pub fn reserve(self: *Progress, io: Io, seq: ?u64, cursor: *?u64) !*Receipt {
        try self.drain(cursor, false);
        if (self.count == capacity) {
            _ = self.receipts[self.head].read(true);
            try self.drain(cursor, false);
        }
        const receipt = &self.receipts[(self.head + self.count) % capacity];
        receipt.* = .{ .io = io, .seq = seq, .retry_needed = &self.retry_needed };
        self.count += 1;
        return receipt;
    }

    pub fn drain(self: *Progress, cursor: *?u64, wait: bool) !void {
        while (self.count > 0) {
            const receipt = &self.receipts[self.head];
            const success = receipt.read(wait) orelse break;
            if (!success) self.failed = true;
            if (!self.failed) {
                if (receipt.seq) |seq| cursor.* = seq;
            }
            self.head = (self.head + 1) % capacity;
            self.count -= 1;
        }
        if (self.failed) return error.FrameProcessingFailed;
    }

    pub fn reset(self: *Progress) void {
        std.debug.assert(self.count == 0);
        self.failed = false;
        self.retry_needed.store(false, .release);
    }
};

test "cursor follows completion order rather than worker order" {
    var progress: Progress = .{};
    var cursor: ?u64 = 10;
    const first = try progress.reserve(std.testing.io, 11, &cursor);
    const second = try progress.reserve(std.testing.io, 14, &cursor);
    second.complete(true);
    try progress.drain(&cursor, false);
    try std.testing.expectEqual(@as(?u64, 10), cursor);
    first.complete(true);
    try progress.drain(&cursor, false);
    try std.testing.expectEqual(@as(?u64, 14), cursor);
}

test "failed frame blocks cursor advancement across later successes" {
    var progress: Progress = .{};
    var cursor: ?u64 = 10;
    const first = try progress.reserve(std.testing.io, 11, &cursor);
    const second = try progress.reserve(std.testing.io, 12, &cursor);
    const third = try progress.reserve(std.testing.io, 13, &cursor);
    first.complete(true);
    second.complete(false);
    third.complete(true);
    try std.testing.expectError(error.FrameProcessingFailed, progress.drain(&cursor, true));
    try std.testing.expectEqual(@as(?u64, 11), cursor);
    try std.testing.expectEqual(@as(usize, 0), progress.count);
    try std.testing.expectError(error.FrameProcessingFailed, progress.reserve(std.testing.io, 14, &cursor));
}

test "receipt drain waits for a worker before releasing its storage" {
    var progress: Progress = .{};
    var cursor: ?u64 = null;
    const receipt = try progress.reserve(std.testing.io, 1, &cursor);
    const worker = try std.Thread.spawn(.{}, Receipt.complete, .{ receipt, true });
    defer worker.join();
    try progress.drain(&cursor, true);
    try std.testing.expectEqual(@as(?u64, 1), cursor);
}

test "canceled zio reader waits for native worker completion" {
    if (comptime !@import("backend_config").use_zio) return error.SkipZigTest;
    const runtime = try @import("zio").Runtime.init(std.testing.allocator, .{ .executors = .exact(2) });
    defer runtime.deinit();
    var receipt: Receipt = .{ .io = runtime.io() };
    var reader = try runtime.io().concurrent(Receipt.read, .{ &receipt, true });
    const Worker = struct {
        fn run(target: *Receipt) void {
            std.testing.io.sleep(Io.Duration.fromMilliseconds(20), .awake) catch {};
            target.complete(true);
        }
    };
    const worker = try std.Thread.spawn(.{}, Worker.run, .{&receipt});
    defer worker.join();
    try std.testing.expectEqual(@as(?bool, true), reader.cancel(runtime.io()));
}