Skip to content

Commit c55d757

Browse files
committed
Add cleanup scheduler for index
1 parent 0556a2e commit c55d757

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

src/Index.zig

+37
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
const std = @import("std");
2+
const log = std.log.scoped(.index);
3+
4+
const zul = @import("zul");
25

36
const InMemoryIndex = @import("InMemoryIndex.zig");
47

@@ -17,24 +20,56 @@ allocator: std.mem.Allocator,
1720
stage: InMemoryIndex,
1821
segments: Segments,
1922

23+
scheduler: zul.Scheduler(Task, *Self),
24+
last_cleanup_at: i64 = 0,
25+
cleanup_interval: i64 = 1000,
26+
27+
const Task = union(enum) {
28+
cleanup: void,
29+
30+
pub fn run(task: Task, index: *Self, at: i64) void {
31+
_ = at;
32+
switch (task) {
33+
.cleanup => {
34+
index.cleanup();
35+
},
36+
}
37+
}
38+
};
39+
2040
pub fn init(allocator: std.mem.Allocator) Self {
2141
return .{
2242
.allocator = allocator,
2343
.stage = InMemoryIndex.init(allocator),
2444
.segments = .{},
45+
.scheduler = zul.Scheduler(Task, *Self).init(allocator),
2546
};
2647
}
2748

49+
pub fn start(self: *Self) !void {
50+
try self.scheduler.start(self);
51+
}
52+
2853
pub fn deinit(self: *Self) void {
2954
self.stage.deinit();
3055
while (self.segments.popFirst()) |node| {
3156
node.data.deinit();
3257
self.allocator.destroy(node);
3358
}
59+
self.scheduler.deinit();
60+
}
61+
62+
fn cleanup(self: *Self) void {
63+
const now = std.time.milliTimestamp();
64+
if (now - self.last_cleanup_at < self.cleanup_interval)
65+
return;
66+
self.last_cleanup_at = now;
67+
log.info("cleanup", .{});
3468
}
3569

3670
pub fn update(self: *Self, changes: []const Change) !void {
3771
try self.stage.update(changes);
72+
try self.scheduler.scheduleIn(.{ .cleanup = {} }, 0);
3873
}
3974

4075
pub fn search(self: *Self, hashes: []const u32, results: *SearchResults, deadline: Deadline) !void {
@@ -59,6 +94,8 @@ test "insert and search" {
5994
var index = Self.init(std.testing.allocator);
6095
defer index.deinit();
6196

97+
try index.start();
98+
6299
try index.update(&[_]Change{.{ .insert = .{
63100
.id = 1,
64101
.hashes = &[_]u32{ 1, 2, 3 },

src/server.zig

+5-3
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,6 @@ pub fn main() !void {
125125

126126
const allocator = gpa.allocator();
127127

128-
var index = Index.init(allocator);
129-
defer index.deinit();
130-
131128
var args = try zul.CommandLineArgs.parse(allocator);
132129
defer args.deinit();
133130

@@ -144,6 +141,11 @@ pub fn main() !void {
144141
threads = @intCast(try std.Thread.getCpuCount());
145142
}
146143

144+
var index = Index.init(allocator);
145+
defer index.deinit();
146+
147+
try index.start();
148+
147149
try run(&index, address, port, threads);
148150
}
149151

0 commit comments

Comments
 (0)