1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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"));
}
}