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

zat.dev/zlay

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

0
0
327 lines · 13.1 KB Raw History
const std = @import("std");
const Io = std.Io;
pub const Maintenance = enum { idle, progress, waiting };

pub fn Owner(comptime Context: type, comptime Item: type, comptime apply: fn (*Context, []const Item) anyerror!void) type {
    return OwnerWithPolicy(Context, Item, apply, null);
}

pub fn OwnerWithPolicy(comptime Context: type, comptime Item: type, comptime apply: fn (*Context, []const Item) anyerror!void, comptime may_delay: ?*const fn (*Context, Item) bool) type {
    return OwnerWithMaintenance(Context, Item, apply, may_delay, null);
}

pub fn OwnerWithMaintenance(comptime Context: type, comptime Item: type, comptime apply: fn (*Context, []const Item) anyerror!void, comptime may_delay: ?*const fn (*Context, Item) bool, comptime maintain: ?*const fn (*Context) Maintenance) type {
    return struct {
        const Self = @This();
        pub const capacity = 1024;
        pub const Request = struct {
            item: Item,
            done: Io.Event = .unset,
            outcome: anyerror!void = {},
            queued_at: i96 = 0,
            completed_at: i96 = 0,
        };
        context: *Context,
        io: Io,
        max_batch: usize,
        queue_limit: usize = capacity,
        delay_ns: i96,
        mutex: Io.Mutex = .init,
        changed: Io.Condition = .init,
        queue: [capacity]*Request = undefined,
        head: usize = 0,
        count: usize = 0,
        outstanding: usize = 0,
        closing: bool = false,
        thread: ?std.Thread = null,
        batches: usize = 0,
        high_water: usize = 0,
        wake_generation: if (maintain != null) u64 else void = if (maintain != null) 0 else {},

        pub fn start(self: *Self) !void {
            if (self.closing) return error.Closed;
            if (self.thread != null) return error.AlreadyStarted;
            if (self.max_batch == 0 or self.max_batch > 64 or self.delay_ns < 0 or self.queue_limit == 0 or self.queue_limit > capacity) return error.InvalidBatchPolicy;
            self.thread = try std.Thread.spawn(.{}, run, .{self});
        }

        pub fn submit(self: *Self, request: *Request) !void {
            self.mutex.lockUncancelable(self.io);
            defer self.mutex.unlock(self.io);
            if (self.closing) return error.Closed;
            if (self.thread == null) return error.NotStarted;
            if (self.outstanding == self.queue_limit) return error.QueueFull;
            request.queued_at = Io.Clock.awake.now(self.io).nanoseconds;
            self.queue[(self.head + self.count) % capacity] = request;
            self.count += 1;
            self.outstanding += 1;
            self.high_water = @max(self.high_water, self.outstanding);
            self.changed.signal(self.io);
        }

        pub fn close(self: *Self) void {
            self.mutex.lockUncancelable(self.io);
            self.closing = true;
            self.changed.broadcast(self.io);
            self.mutex.unlock(self.io);
            if (self.thread) |thread| thread.join();
            self.thread = null;
        }

        pub fn wakeMaintenance(self: *Self) void {
            if (maintain != null) {
                self.mutex.lockUncancelable(self.io);
                self.wake_generation +%= 1;
                self.changed.signal(self.io);
                self.mutex.unlock(self.io);
            }
        }

        fn run(self: *Self) void {
            var requests: [64]*Request = undefined;
            var items: [64]Item = undefined;
            while (true) {
                self.mutex.lockUncancelable(self.io);
                while (self.count == 0) {
                    if (maintain) |work| {
                        const generation = self.wake_generation;
                        self.mutex.unlock(self.io);
                        const progress = work(self.context);
                        self.mutex.lockUncancelable(self.io);
                        if (self.count != 0 or progress == .progress or self.wake_generation != generation) continue;
                        if (progress == .waiting) {
                            self.changed.waitUncancelable(self.io, &self.mutex);
                            continue;
                        }
                    }
                    if (self.closing) break;
                    self.changed.waitUncancelable(self.io, &self.mutex);
                }
                if (self.count == 0) {
                    self.mutex.unlock(self.io);
                    return;
                }
                const first = self.queue[self.head];
                self.mutex.unlock(self.io);
                const delay = if (may_delay) |predicate| predicate(self.context, first.item) else true;
                self.mutex.lockUncancelable(self.io);
                const deadline = self.queue[self.head].queued_at + self.delay_ns;
                while (delay and !self.closing and self.count < @min(self.max_batch, self.queue_limit) and Io.Clock.awake.now(self.io).nanoseconds < deadline) {
                    self.changed.waitTimeout(self.io, &self.mutex, .{ .deadline = .{
                        .raw = .{ .nanoseconds = deadline },
                        .clock = .awake,
                    } }) catch {};
                }
                const count = @min(self.count, self.max_batch);
                for (0..count) |i| {
                    requests[i] = self.queue[(self.head + i) % capacity];
                    items[i] = requests[i].item;
                }
                self.head = (self.head + count) % capacity;
                self.count -= count;
                self.mutex.unlock(self.io);
                const outcome = apply(self.context, items[0..count]);
                const completed = Io.Clock.awake.now(self.io).nanoseconds;
                self.batches += 1;
                self.mutex.lockUncancelable(self.io);
                for (requests[0..count]) |request| {
                    request.outcome = outcome;
                    request.completed_at = completed;
                    request.done.set(self.io);
                }
                self.outstanding -= count;
                self.mutex.unlock(self.io);
                if (maintain) |work| _ = work(self.context);
            }
        }
    };
}

test "owner acknowledges applied work before maintenance and drains idle work on close" {
    const t = std.testing;
    const Context = struct {
        io: Io,
        entered: Io.Event = .unset,
        release: Io.Event = .unset,
        remaining: usize = 0,
        applied: usize = 0,

        fn apply(self: *@This(), items: []const usize) !void {
            if (self.applied == 0) self.remaining = 3;
            for (items) |item| self.applied += item;
        }

        fn maintain(self: *@This()) Maintenance {
            if (self.remaining == 0) return .idle;
            if (self.remaining == 3) {
                self.entered.set(self.io);
                self.release.waitUncancelable(self.io);
            }
            self.remaining -= 1;
            return .progress;
        }
    };
    const Batch = OwnerWithMaintenance(Context, usize, Context.apply, null, Context.maintain);
    var context: Context = .{ .io = t.io };
    var owner: Batch = .{ .context = &context, .io = t.io, .max_batch = 1, .queue_limit = 1, .delay_ns = 0 };
    try owner.start();
    defer owner.close();
    var first: Batch.Request = .{ .item = 1 };
    try owner.submit(&first);
    first.done.waitUncancelable(t.io);
    try first.outcome;
    context.entered.waitUncancelable(t.io);
    var second: Batch.Request = .{ .item = 2 };
    defer context.release.set(t.io);
    try owner.submit(&second);
    try t.expect(!second.done.isSet());
    context.release.set(t.io);
    owner.close();
    try t.expect(second.done.isSet());
    try second.outcome;
    try t.expectEqual(@as(usize, 3), context.applied);
    try t.expectEqual(@as(usize, 0), context.remaining);
}

test "owner observes a completion notification delivered before its wait" {
    const t = std.testing;
    const Context = struct {
        stage: usize = 0,
        wake: ?struct { context: *anyopaque, call: *const fn (*anyopaque) void } = null,

        fn apply(self: *@This(), _: []const usize) !void {
            self.stage = 1;
        }

        fn maintain(self: *@This()) Maintenance {
            switch (self.stage) {
                0 => return .idle,
                1 => {
                    self.stage = 2;
                    return .progress;
                },
                2 => {
                    self.stage = 3;
                    const wake = self.wake.?;
                    wake.call(wake.context);
                    return .waiting;
                },
                else => {
                    self.stage = 4;
                    return .idle;
                },
            }
        }
    };
    const Batch = OwnerWithMaintenance(Context, usize, Context.apply, null, Context.maintain);
    const Wake = struct {
        fn notify(context: *anyopaque) void {
            const owner: *Batch = @ptrCast(@alignCast(context));
            owner.wakeMaintenance();
        }
    };
    var context: Context = .{};
    var owner: Batch = .{ .context = &context, .io = t.io, .max_batch = 1, .delay_ns = 0 };
    context.wake = .{ .context = &owner, .call = Wake.notify };
    try owner.start();
    defer owner.close();
    var request: Batch.Request = .{ .item = 1 };
    try owner.submit(&request);
    request.done.waitUncancelable(t.io);
    owner.close();
    try request.outcome;
    try t.expectEqual(@as(usize, 4), context.stage);
}

test "owner serves queued requests while maintenance waits for IO" {
    const t = std.testing;
    const Context = struct {
        io: Io,
        waiting: Io.Event = .unset,
        ready: std.atomic.Value(bool) = .init(false),
        applied: usize = 0,

        fn apply(self: *@This(), items: []const usize) !void {
            for (items) |item| self.applied += item;
        }

        fn maintain(self: *@This()) Maintenance {
            if (self.ready.load(.acquire)) return .idle;
            self.waiting.set(self.io);
            return .waiting;
        }
    };
    const Batch = OwnerWithMaintenance(Context, usize, Context.apply, null, Context.maintain);
    var context: Context = .{ .io = t.io };
    var owner: Batch = .{ .context = &context, .io = t.io, .max_batch = 1, .delay_ns = 0 };
    try owner.start();
    defer {
        context.ready.store(true, .release);
        owner.wakeMaintenance();
        owner.close();
    }
    context.waiting.waitUncancelable(t.io);
    var first: Batch.Request = .{ .item = 1 };
    var second: Batch.Request = .{ .item = 2 };
    for ([_]*Batch.Request{ &first, &second }) |request| {
        try owner.submit(request);
        request.done.waitUncancelable(t.io);
        try request.outcome;
    }
    try t.expect(!context.ready.load(.acquire));
    context.ready.store(true, .release);
    owner.wakeMaintenance();
    owner.close();
    try t.expectEqual(@as(usize, 3), context.applied);
}

test "bounded owner drains accepted work, propagates errors and persists batches" {
    const index = @import("index.zig");
    const t = std.testing;
    const Batch = Owner(index.CollectionIndex, index.CollectionIndex.Pair, index.CollectionIndex.addPairs);
    var dir = t.tmpDir(.{});
    defer dir.cleanup();
    const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
    defer t.allocator.free(path);
    {
        var ci = try index.CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        var owner: Batch = .{ .context = &ci, .io = t.io, .max_batch = 64, .delay_ns = 1_000_000 };
        try owner.start();
        var owner_open = true;
        defer if (owner_open) owner.close();
        ci.mutex.lockUncancelable(t.io);
        var locked = true;
        defer if (locked) ci.mutex.unlock(t.io);
        var requests: [Batch.capacity]Batch.Request = undefined;
        for (&requests) |*request| {
            request.* = .{ .item = .{ .did = "did:plc:alice", .collection = "app.bsky.feed.post" } };
            try owner.submit(request);
        }
        var rejected: Batch.Request = .{ .item = .{ .did = "did:plc:bob", .collection = "app.bsky.feed.post" } };
        try t.expectError(error.QueueFull, owner.submit(&rejected));
        ci.mutex.unlock(t.io);
        locked = false;
        owner.close();
        owner_open = false;
        for (&requests) |*request| {
            try t.expect(request.done.isSet());
            try request.outcome;
        }
        try t.expectError(error.Closed, owner.submit(&rejected));
        var failing: Batch = .{ .context = &ci, .io = t.io, .max_batch = 64, .delay_ns = 1_000_000 };
        var invalid: Batch.Request = .{ .item = .{ .did = "invalid\x00did", .collection = "app.bsky.feed.post" } };
        try t.expectError(error.NotStarted, failing.submit(&invalid));
        try failing.start();
        try failing.submit(&invalid);
        failing.close();
        try t.expectError(error.InvalidIndexKey, invalid.outcome);
        try t.expect(!ci.hasCollections("did:plc:bob"));
    }
    {
        var ci = try index.CollectionIndex.open(t.allocator, t.io, path);
        defer ci.deinit();
        try t.expect(ci.hasCollections("did:plc:alice"));
        try t.expect(!ci.hasCollections("did:plc:bob"));
    }
}