1
1
const std = @import ("std" );
2
+ const log = std .log .scoped (.index );
3
+
4
+ const zul = @import ("zul" );
2
5
3
6
const InMemoryIndex = @import ("InMemoryIndex.zig" );
4
7
@@ -17,24 +20,56 @@ allocator: std.mem.Allocator,
17
20
stage : InMemoryIndex ,
18
21
segments : Segments ,
19
22
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
+
20
40
pub fn init (allocator : std.mem.Allocator ) Self {
21
41
return .{
22
42
.allocator = allocator ,
23
43
.stage = InMemoryIndex .init (allocator ),
24
44
.segments = .{},
45
+ .scheduler = zul .Scheduler (Task , * Self ).init (allocator ),
25
46
};
26
47
}
27
48
49
+ pub fn start (self : * Self ) ! void {
50
+ try self .scheduler .start (self );
51
+ }
52
+
28
53
pub fn deinit (self : * Self ) void {
29
54
self .stage .deinit ();
30
55
while (self .segments .popFirst ()) | node | {
31
56
node .data .deinit ();
32
57
self .allocator .destroy (node );
33
58
}
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" , .{});
34
68
}
35
69
36
70
pub fn update (self : * Self , changes : []const Change ) ! void {
37
71
try self .stage .update (changes );
72
+ try self .scheduler .scheduleIn (.{ .cleanup = {} }, 0 );
38
73
}
39
74
40
75
pub fn search (self : * Self , hashes : []const u32 , results : * SearchResults , deadline : Deadline ) ! void {
@@ -59,6 +94,8 @@ test "insert and search" {
59
94
var index = Self .init (std .testing .allocator );
60
95
defer index .deinit ();
61
96
97
+ try index .start ();
98
+
62
99
try index .update (&[_ ]Change {.{ .insert = .{
63
100
.id = 1 ,
64
101
.hashes = &[_ ]u32 { 1 , 2 , 3 },
0 commit comments