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
//! collection index cleaner — removes entries that should not be in the index
//!
//! two scopes, each triggered via admin API: inactive accounts (queries
//! postgres for accounts with non-active status and removes their entries)
//! and invalid collections (removes every pair filed under a name that is
//! not an NSID).
//! modeled on backfill.zig's Backfiller pattern.
const std = @import("std");
const Io = std.Io;
const pg = @import("pg");
const collection_index_mod = @import("index.zig");
const event_log_mod = @import("../event_log.zig");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.cleaner);
pub const Scope = enum { inactive_accounts, invalid_collections };
pub const Cleaner = struct {
scope: Scope = .inactive_accounts,
allocator: Allocator,
io: Io,
collection_index: *collection_index_mod.CollectionIndex,
persist: *event_log_mod.DiskPersist,
running: std.atomic.Value(bool),
thread: ?std.Thread,
scanned: std.atomic.Value(u64),
removed: std.atomic.Value(u64),
shutdown: *std.atomic.Value(bool),
fn db(self: *Cleaner) *pg.Pool {
return self.persist.db;
}
pub fn init(
allocator: Allocator,
io: Io,
collection_index: *collection_index_mod.CollectionIndex,
persist: *event_log_mod.DiskPersist,
shutdown: *std.atomic.Value(bool),
) Cleaner {
return .{
.allocator = allocator,
.io = io,
.collection_index = collection_index,
.persist = persist,
.running = .{ .raw = false },
.thread = null,
.scanned = .{ .raw = 0 },
.removed = .{ .raw = 0 },
.shutdown = shutdown,
};
}
pub fn isRunning(self: *Cleaner) bool {
return self.running.load(.acquire);
}
/// block until any in-progress cleanup thread completes.
/// must be called before tearing down DiskPersist or CollectionIndex.
pub fn waitForCompletion(self: *Cleaner) void {
if (self.thread) |t| {
t.join();
self.thread = null;
}
}
/// start cleanup. returns error if already running.
pub fn start(self: *Cleaner, scope: Scope) !void {
if (self.running.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) {
return error.AlreadyRunning;
}
errdefer self.running.store(false, .release);
self.scanned.store(0, .release);
self.removed.store(0, .release);
self.scope = scope;
self.thread = std.Thread.spawn(.{}, run, .{self}) catch return error.SpawnFailed;
}
fn run(self: *Cleaner) void {
defer {
// note: do NOT clear self.thread here — waitForCompletion() needs
// the handle to join this thread before dp/ci teardown.
self.running.store(false, .release);
}
if (self.scope == .invalid_collections) {
log.info("invalid-collection purge started", .{});
self.collection_index.purgeInvalidCollections(self.allocator, self.shutdown, &self.removed) catch |err| {
log.err("invalid-collection purge failed: {s}", .{@errorName(err)});
};
log.info("invalid-collection purge finished: removed {d} pairs", .{self.removed.load(.monotonic)});
return;
}
log.info("cleanup started", .{});
const pool = self.db();
// page through inactive accounts by uid
var last_uid: i64 = 0;
while (!self.shutdown.load(.acquire)) {
var batch_count: u64 = 0;
{
var result = pool.query(
"SELECT uid, did FROM account WHERE (status != 'active' OR upstream_status != 'active') AND uid > $1 ORDER BY uid LIMIT 500",
.{last_uid},
) catch |err| {
log.err("cleanup query failed: {s}", .{@errorName(err)});
break;
};
defer result.deinit();
while (result.nextUnsafe() catch null) |row| {
const uid = row.get(i64, 0);
const did = row.get([]const u8, 1);
self.collection_index.removeAll(did) catch |err| {
log.debug("removeAll failed for {s}: {s}", .{ did, @errorName(err) });
};
last_uid = uid;
batch_count += 1;
_ = self.scanned.fetchAdd(1, .monotonic);
_ = self.removed.fetchAdd(1, .monotonic);
}
}
if (batch_count == 0) break;
log.info("cleanup progress: scanned {d}, last_uid={d}", .{
self.scanned.load(.monotonic),
last_uid,
});
// brief pause between batches to avoid hammering postgres
self.io.sleep(Io.Duration.fromMilliseconds(50), .awake) catch {};
}
const total = self.scanned.load(.monotonic);
log.info("cleanup complete: removed {d} inactive accounts from collection index", .{total});
}
pub fn getStatus(self: *Cleaner) struct { running: bool, scanned: u64, removed: u64 } {
return .{
.running = self.isRunning(),
.scanned = self.scanned.load(.monotonic),
.removed = self.removed.load(.monotonic),
};
}
};