const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const queue_mod = @import("bounded_queue.zig"); pub const Shedding = queue_mod.Shedding; pub const Counters = struct { accepted: u64, dropped: u64, processed: u64, canceled: u64, queued: usize, }; pub fn Pool(comptime Item: type, comptime Ctx: type) type { return struct { const Self = @This(); const Queue = queue_mod.BoundedQueue(Item); pub const ProcessFn = *const fn (*Ctx, Io, Item) Io.Cancelable!void; pub const DropFn = *const fn (*Ctx, Item) void; pub const Options = struct { queue_capacity: usize, workers: usize, ctx: *Ctx, process: ProcessFn, on_drop: ?DropFn = null, shedding: Shedding = .drop_newest, }; pub const InitError = Allocator.Error || error{InvalidCapacity}; allocator: Allocator, buffer: []Item, queue: Queue, group: Io.Group = .init, ctx: *Ctx, process_fn: ProcessFn, on_drop_fn: ?DropFn, shedding: Shedding, worker_count: usize, state: enum { ready, running, stopped } = .ready, accepted: std.atomic.Value(u64) align(std.atomic.cache_line) = .init(0), dropped: std.atomic.Value(u64) = .init(0), processed: std.atomic.Value(u64) align(std.atomic.cache_line) = .init(0), canceled: std.atomic.Value(u64) = .init(0), pub fn init(allocator: Allocator, opts: Options) InitError!Self { if (opts.queue_capacity == 0) return error.InvalidCapacity; const buffer = try allocator.alloc(Item, opts.queue_capacity); return .{ .allocator = allocator, .buffer = buffer, .queue = Queue.init(buffer), .ctx = opts.ctx, .process_fn = opts.process, .on_drop_fn = opts.on_drop, .shedding = opts.shedding, .worker_count = opts.workers, }; } pub fn deinit(self: *Self, io: Io) void { self.cancel(io); self.allocator.free(self.buffer); self.* = undefined; } pub fn start(self: *Self, io: Io) (Io.ConcurrentError || error{ AlreadyStarted, Closed, NoWorkers })!void { switch (self.state) { .running => return error.AlreadyStarted, .stopped => return error.Closed, .ready => {}, } if (self.worker_count == 0) return error.NoWorkers; self.state = .running; errdefer self.cancel(io); for (0..self.worker_count) |_| { try self.group.concurrent(io, workerLoop, .{ self, io }); } } pub fn put(self: *Self, io: Io, item: Item) (error{Closed} || Io.Cancelable)!void { self.queue.put(io, item) catch |err| switch (err) { error.Closed => return error.Closed, error.Canceled => return error.Canceled, }; _ = self.accepted.fetchAdd(1, .monotonic); } pub fn offer(self: *Self, io: Io, item: Item) bool { const result = self.queue.offer(io, item, self.shedding) catch |err| switch (err) { error.Closed => return self.drop(item), }; return self.finishPush(result); } pub fn shutdown(self: *Self, io: Io) Io.Cancelable!void { self.queue.close(io); defer { self.state = .stopped; self.dropRemaining(io); } try self.group.await(io); } pub fn cancel(self: *Self, io: Io) void { self.queue.abort(io); self.group.cancel(io); self.state = .stopped; self.dropRemaining(io); } pub fn counters(self: *Self, io: Io) Counters { return .{ .accepted = self.accepted.load(.monotonic), .dropped = self.dropped.load(.monotonic), .processed = self.processed.load(.monotonic), .canceled = self.canceled.load(.monotonic), .queued = self.queue.count(io), }; } pub fn droppedCount(self: *const Self) u64 { return self.dropped.load(.monotonic); } pub fn capacity(self: *const Self) usize { return self.queue.capacity(); } fn workerLoop(self: *Self, io: Io) void { while (true) { const item = self.queue.pop(io) catch return; self.process_fn(self.ctx, io, item) catch { _ = self.canceled.fetchAdd(1, .monotonic); return; }; _ = self.processed.fetchAdd(1, .monotonic); } } fn finishPush(self: *Self, result: queue_mod.PushResult(Item)) bool { switch (result.status) { .accepted => { _ = self.accepted.fetchAdd(1, .monotonic); return true; }, .dropped_oldest => { _ = self.accepted.fetchAdd(1, .monotonic); if (result.dropped) |item| _ = self.drop(item); return true; }, .dropped_newest => { if (result.dropped) |item| _ = self.drop(item); return false; }, } } fn drop(self: *Self, item: Item) bool { _ = self.dropped.fetchAdd(1, .monotonic); if (self.on_drop_fn) |on_drop| on_drop(self.ctx, item); return false; } fn dropRemaining(self: *Self, io: Io) void { while (self.queue.take(io)) |item| { _ = self.drop(item); } } }; } const TestCtx = struct { sum: std.atomic.Value(u64) = .init(0), dropped_sum: std.atomic.Value(u64) = .init(0), fn process(self: *TestCtx, _: Io, item: u64) Io.Cancelable!void { _ = self.sum.fetchAdd(item, .monotonic); } fn onDrop(self: *TestCtx, item: u64) void { _ = self.dropped_sum.fetchAdd(item, .monotonic); } }; test "offer tracks drop_newest" { const testing = std.testing; const io = testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 2, .workers = 0, .ctx = &ctx, .process = TestCtx.process, .on_drop = TestCtx.onDrop, .shedding = .drop_newest, }); defer pool.deinit(io); try testing.expect(pool.offer(io, 1)); try testing.expect(pool.offer(io, 2)); try testing.expect(!pool.offer(io, 3)); const c = pool.counters(io); try testing.expectEqual(@as(u64, 2), c.accepted); try testing.expectEqual(@as(u64, 1), c.dropped); try testing.expectEqual(@as(usize, 2), c.queued); try testing.expectEqual(@as(u64, 3), ctx.dropped_sum.load(.monotonic)); } test "offer drop_oldest accepts new item and drops queued head" { const testing = std.testing; const io = testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 2, .workers = 0, .ctx = &ctx, .process = TestCtx.process, .on_drop = TestCtx.onDrop, .shedding = .drop_oldest, }); defer pool.deinit(io); try testing.expect(pool.offer(io, 1)); try testing.expect(pool.offer(io, 2)); try testing.expect(pool.offer(io, 3)); const c = pool.counters(io); try testing.expectEqual(@as(u64, 3), c.accepted); try testing.expectEqual(@as(u64, 1), c.dropped); try testing.expectEqual(@as(usize, 2), c.queued); try testing.expectEqual(@as(u64, 1), ctx.dropped_sum.load(.monotonic)); } test "workers process submitted items" { const testing = std.testing; const io = testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 8, .workers = 2, .ctx = &ctx, .process = TestCtx.process, }); defer pool.deinit(io); try pool.start(io); for (1..6) |i| try pool.put(io, i); try pool.shutdown(io); const c = pool.counters(io); try testing.expectEqual(@as(u64, 5), c.accepted); try testing.expectEqual(@as(u64, 5), c.processed); try testing.expectEqual(@as(u64, 15), ctx.sum.load(.monotonic)); } test "offer honors drop_oldest policy" { const testing = std.testing; const io = testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 2, .workers = 0, .ctx = &ctx, .process = TestCtx.process, .on_drop = TestCtx.onDrop, .shedding = .drop_oldest, }); defer pool.deinit(io); try testing.expect(pool.offer(io, 1)); try testing.expect(pool.offer(io, 2)); try testing.expect(pool.offer(io, 3)); const c = pool.counters(io); try testing.expectEqual(@as(u64, 3), c.accepted); try testing.expectEqual(@as(u64, 1), c.dropped); try testing.expectEqual(@as(u64, 1), ctx.dropped_sum.load(.monotonic)); } test "put returns Closed without dropping caller-owned item" { const testing = std.testing; const io = testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 2, .workers = 0, .ctx = &ctx, .process = TestCtx.process, .on_drop = TestCtx.onDrop, }); defer pool.deinit(io); try pool.shutdown(io); try testing.expectError(error.Closed, pool.put(io, 1)); try testing.expectEqual(@as(u64, 0), pool.droppedCount()); try testing.expectEqual(@as(u64, 0), ctx.dropped_sum.load(.monotonic)); } test "start leaves no workers running when a spawn fails" { const testing = std.testing; var threaded = Io.Threaded.init(testing.allocator, .{ .concurrent_limit = .limited(1) }); defer threaded.deinit(); const io = threaded.io(); var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(testing.allocator, .{ .queue_capacity = 2, .workers = 2, .ctx = &ctx, .process = TestCtx.process, }); defer pool.deinit(io); defer pool.cancel(io); try testing.expectError(error.ConcurrencyUnavailable, pool.start(io)); try testing.expectEqual(@as(?*anyopaque, null), pool.group.token.load(.acquire)); try testing.expectEqual(.stopped, pool.state); } const CancelCtx = struct { entered: Io.Event = .unset, calls: usize = 0, freed: usize = 0, fn process(self: *@This(), io: Io, item: *u32) Io.Cancelable!void { defer { std.testing.allocator.destroy(item); self.freed += 1; } self.calls += 1; self.entered.set(io); try io.sleep(.fromSeconds(30), .awake); } fn drop(self: *@This(), item: *u32) void { std.testing.allocator.destroy(item); self.freed += 1; } }; fn cancelTestPool(ctx: *CancelCtx, io: Io) !Pool(*u32, CancelCtx) { var pool = try Pool(*u32, CancelCtx).init(std.testing.allocator, .{ .queue_capacity = 4, .workers = 1, .ctx = ctx, .process = CancelCtx.process, .on_drop = CancelCtx.drop, }); errdefer pool.deinit(io); for (0..4) |_| { const item = try std.testing.allocator.create(u32); errdefer std.testing.allocator.destroy(item); try pool.put(io, item); } return pool; } test "cancel joins active callback and drops queued ownership exactly once" { const io = std.testing.io; var ctx: CancelCtx = .{}; var pool = try cancelTestPool(&ctx, io); defer pool.deinit(io); try pool.start(io); try ctx.entered.wait(io); pool.cancel(io); pool.cancel(io); const c = pool.counters(io); try std.testing.expectEqual(@as(usize, 1), ctx.calls); try std.testing.expectEqual(@as(usize, 4), ctx.freed); try std.testing.expectEqual(@as(u64, 0), c.processed); try std.testing.expectEqual(@as(u64, 1), c.canceled); try std.testing.expectEqual(@as(u64, 3), c.dropped); try std.testing.expectEqual(@as(usize, 0), c.queued); try std.testing.expectError(error.Closed, pool.start(io)); } test "deinit joins workers before freeing the queue" { const io = std.testing.io; var ctx: CancelCtx = .{}; var pool = try cancelTestPool(&ctx, io); try pool.start(io); try ctx.entered.wait(io); pool.deinit(io); try std.testing.expectEqual(@as(usize, 4), ctx.freed); try std.testing.expectEqual(@as(usize, 1), ctx.calls); } test "shutdown propagates parent cancellation after releasing ownership" { const io = std.testing.io; var ctx: CancelCtx = .{}; var pool = try cancelTestPool(&ctx, io); defer pool.deinit(io); try pool.start(io); try ctx.entered.wait(io); const Helper = struct { fn shutdown(p: *Pool(*u32, CancelCtx), task_io: Io) Io.Cancelable!void { try p.shutdown(task_io); } }; var future = try io.concurrent(Helper.shutdown, .{ &pool, io }); try std.testing.expectError(error.Canceled, future.cancel(io)); try std.testing.expectEqual(@as(usize, 4), ctx.freed); try std.testing.expectEqual(@as(u64, 1), pool.counters(io).canceled); } test "cancel stops dequeuing even when a callback swallows cancellation" { const Ctx = struct { entered: Io.Event = .unset, calls: usize = 0, fn process(self: *@This(), io: Io, _: u32) Io.Cancelable!void { self.calls += 1; self.entered.set(io); io.sleep(.fromSeconds(30), .awake) catch return; } }; const io = std.testing.io; var ctx: Ctx = .{}; var pool = try Pool(u32, Ctx).init(std.testing.allocator, .{ .queue_capacity = 4, .workers = 1, .ctx = &ctx, .process = Ctx.process, }); defer pool.deinit(io); for (0..4) |i| try pool.put(io, @intCast(i)); try pool.start(io); try ctx.entered.wait(io); pool.cancel(io); try std.testing.expectEqual(@as(usize, 1), ctx.calls); try std.testing.expectEqual(@as(u64, 3), pool.counters(io).dropped); } test "zero workers cannot start and closed pools cannot restart" { const io = std.testing.io; var ctx: TestCtx = .{}; var pool = try Pool(u64, TestCtx).init(std.testing.allocator, .{ .queue_capacity = 1, .workers = 0, .ctx = &ctx, .process = TestCtx.process, }); defer pool.deinit(io); try std.testing.expectError(error.NoWorkers, pool.start(io)); try pool.shutdown(io); try std.testing.expectError(error.Closed, pool.start(io)); } test "multiple producers drain exactly once with async concurrency disabled" { const io_options: Io.Threaded.InitOptions = .{ .async_limit = .limited(0), .concurrent_limit = .limited(8) }; var threaded = Io.Threaded.init(std.testing.allocator, io_options); defer threaded.deinit(); const io = threaded.io(); const Seen = struct { counts: [4000]std.atomic.Value(u32) = @splat(.init(0)), fn process(self: *@This(), _: Io, item: u64) Io.Cancelable!void { _ = self.counts[item].fetchAdd(1, .monotonic); } }; var ctx: Seen = .{}; var pool = try Pool(u64, Seen).init(std.testing.allocator, .{ .queue_capacity = 3, .workers = 2, .ctx = &ctx, .process = Seen.process, }); defer pool.deinit(io); try pool.start(io); try std.testing.expectError(error.AlreadyStarted, pool.start(io)); const Helper = struct { fn produce(p: *Pool(u64, Seen), task_io: Io, producer: usize) Io.Cancelable!void { for (0..1000) |i| p.put(task_io, producer * 1000 + i) catch |err| switch (err) { error.Canceled => return error.Canceled, error.Closed => unreachable, }; } }; var producers: Io.Group = .init; defer producers.cancel(io); for (0..4) |producer| try producers.concurrent(io, Helper.produce, .{ &pool, io, producer }); try producers.await(io); try pool.shutdown(io); try std.testing.expectEqual(@as(u64, 4000), pool.counters(io).processed); for (&ctx.counts) |*count| try std.testing.expectEqual(@as(u32, 1), count.load(.monotonic)); } test "start failure drops prequeued ownership and closes admission" { var threaded = Io.Threaded.init(std.testing.allocator, .{ .concurrent_limit = .limited(0) }); defer threaded.deinit(); const io = threaded.io(); var ctx: CancelCtx = .{}; var pool = try cancelTestPool(&ctx, io); defer pool.deinit(io); try std.testing.expectError(error.ConcurrencyUnavailable, pool.start(io)); try std.testing.expectEqual(@as(usize, 4), ctx.freed); try std.testing.expectEqual(@as(u64, 4), pool.counters(io).dropped); try std.testing.expectError(error.Closed, pool.start(io)); } test "drop callback may inspect pool counters without locking itself out" { const Ctx = struct { pool: ?*Pool(u32, @This()) = null, io: Io, drops: usize = 0, fn process(_: *@This(), _: Io, _: u32) Io.Cancelable!void {} fn drop(self: *@This(), _: u32) void { _ = self.pool.?.counters(self.io); self.drops += 1; } }; const io = std.testing.io; var ctx: Ctx = .{ .io = io }; var pool = try Pool(u32, Ctx).init(std.testing.allocator, .{ .queue_capacity = 1, .workers = 1, .ctx = &ctx, .process = Ctx.process, .on_drop = Ctx.drop, }); defer pool.deinit(io); ctx.pool = &pool; try std.testing.expect(pool.offer(io, 1)); try std.testing.expect(!pool.offer(io, 2)); pool.cancel(io); try std.testing.expectEqual(@as(usize, 2), ctx.drops); }