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
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
use arc_swap::ArcSwap;
use crossbeam::channel::Receiver;
use super::{
arena::{FileArenaSnapshot, FileNode, NO_INDEX, StringPool},
traversal::{LocalId, ScanEvent},
};
pub struct SharedState {
/// Atomic pointer to the latest immutable snapshot of the tree
pub current_snapshot: ArcSwap<FileArenaSnapshot>,
/// Indicates whether the scanner is actively running
pub is_scanning: Arc<AtomicBool>,
/// Background-computed live extension statistics (ext, `total_size`, `file_count`)
pub extension_stats: ArcSwap<Vec<(String, u64, u32)>>,
}
impl Default for SharedState {
fn default() -> Self {
Self::new()
}
}
impl SharedState {
#[must_use]
pub fn new() -> Self {
let initial_snapshot = FileArenaSnapshot {
nodes: Arc::new(Vec::new()),
string_pool: Arc::new(StringPool::new()),
};
Self {
current_snapshot: ArcSwap::new(Arc::new(initial_snapshot)),
is_scanning: Arc::new(AtomicBool::new(false)),
extension_stats: ArcSwap::new(Arc::new(Vec::new())), // Initialize
}
}
}
pub struct Coordinator {
/// Lock-free channel to receive events
event_rx: Receiver<Vec<ScanEvent>>,
/// Shared state wrapper for swapping snapshots
shared_state: Arc<SharedState>,
}
impl Coordinator {
pub const fn new(event_rx: Receiver<Vec<ScanEvent>>, shared_state: Arc<SharedState>) -> Self {
Self {
event_rx,
shared_state,
}
}
pub fn run_coordinator_loop(&mut self, root_path_str: &str) {
self.shared_state.is_scanning.store(true, Ordering::SeqCst);
let mut arena = Vec::with_capacity(1024 * 1024); // Pre-allocate for ~1M nodes
let mut string_pool = StringPool::new();
// Local extension tracking in the background thread
let mut ext_map: std::collections::HashMap<String, (u64, u32)> =
std::collections::HashMap::new();
// Local to Global ID mapping: outer index is worker_id, inner is local_id.0
let mut id_map: Vec<Vec<u32>> = Vec::new();
// Track the last child inserted for each parent global index to ensure O(1) appends
let mut last_child_map: Vec<u32> = Vec::new();
// Register root directory node (Global ID 0)
let root_name_id = string_pool.get_or_insert(root_path_str.as_bytes());
let root_node = FileNode::new(root_name_id, None, true, false, 0, 0, 0);
arena.push(root_node);
last_child_map.push(NO_INDEX);
// Map root node: LocalId(0) for worker 0 is global index 0
register_id(&mut id_map, 0, LocalId(0), 0);
let mut last_publish = Instant::now();
let publish_interval = Duration::from_millis(100);
let mut dirty = false;
while let Ok(batch) = self.event_rx.recv() {
for event in batch {
match event {
ScanEvent::DirDiscovered {
parent_worker_id,
child_worker_id,
local_parent_id,
local_child_id,
name,
modified_timestamp,
created_timestamp,
accessed_timestamp,
} => {
// Resolve parent global index using the parent's creator worker ID
if let Some(parent_global_id) =
resolve_id(&id_map, parent_worker_id, local_parent_id)
{
let name_id = string_pool.get_or_insert(name.as_bytes());
let child_global_id = arena.len() as u32;
// Create the directory node with initial timestamps
let dir_node = FileNode::new(
name_id,
Some(parent_global_id),
true,
false,
modified_timestamp,
created_timestamp,
accessed_timestamp,
);
arena.push(dir_node);
last_child_map.push(NO_INDEX);
// Map worker's local child ID to our global index using the child's creator worker ID
register_id(
&mut id_map,
child_worker_id,
local_child_id,
child_global_id,
);
// Connect child to sibling chain in O(1) using last_child_map
connect_child(
&mut arena,
&mut last_child_map,
parent_global_id,
child_global_id,
);
dirty = true;
}
}
ScanEvent::FileDiscovered {
parent_worker_id,
local_parent_id,
name,
size,
is_symlink,
modified_timestamp,
created_timestamp,
accessed_timestamp,
} => {
if name.is_empty() && size == 0 {
// Directory completion signal
continue;
}
// Resolve parent global index using the parent's creator worker ID
if let Some(parent_global_id) =
resolve_id(&id_map, parent_worker_id, local_parent_id)
{
let name_id = string_pool.get_or_insert(name.as_bytes());
let file_global_id = arena.len() as u32;
// Create file node (parent pointer is set)
let mut file_node = FileNode::new(
name_id,
Some(parent_global_id),
false,
is_symlink,
modified_timestamp,
created_timestamp,
accessed_timestamp,
);
file_node.size = size;
arena.push(file_node);
last_child_map.push(NO_INDEX);
// Connect child to sibling chain in O(1)
connect_child(
&mut arena,
&mut last_child_map,
parent_global_id,
file_global_id,
);
// Propagate size and latest metadata upwards through parent indices
propagate_size_and_time(
&mut arena,
parent_global_id,
size,
modified_timestamp,
created_timestamp,
accessed_timestamp,
);
// O(1) Background Live Extension Tracking
let ext = std::path::Path::new(&name).extension().map_or_else(
|| "(no extension)".to_string(),
|s| s.to_string_lossy().to_ascii_lowercase(),
);
let entry = ext_map.entry(ext).or_insert((0, 0));
entry.0 += size;
entry.1 += 1;
dirty = true;
}
}
}
}
// Publish snapshot if dirty and interval elapsed
if dirty && last_publish.elapsed() >= publish_interval {
let snapshot = FileArenaSnapshot {
nodes: Arc::new(arena.clone()),
string_pool: Arc::new(string_pool.clone()),
};
self.shared_state.current_snapshot.store(Arc::new(snapshot));
// Publish background sorted statistics
let mut stats_vec: Vec<(String, u64, u32)> = ext_map
.iter()
.map(|(ext, &(total_size, file_count))| (ext.clone(), total_size, file_count))
.collect();
stats_vec.sort_by_key(|b| std::cmp::Reverse(b.1));
self.shared_state.extension_stats.store(Arc::new(stats_vec));
last_publish = Instant::now();
dirty = false;
}
}
// Final publish at completion
let snapshot = FileArenaSnapshot {
nodes: Arc::new(arena),
string_pool: Arc::new(string_pool),
};
self.shared_state.current_snapshot.store(Arc::new(snapshot));
let mut stats_vec: Vec<(String, u64, u32)> = ext_map
.into_iter()
.map(|(ext, (total_size, file_count))| (ext, total_size, file_count))
.collect();
stats_vec.sort_by_key(|b| std::cmp::Reverse(b.1));
self.shared_state.extension_stats.store(Arc::new(stats_vec));
self.shared_state.is_scanning.store(false, Ordering::SeqCst);
}
}
#[inline]
fn register_id(id_map: &mut Vec<Vec<u32>>, worker_id: u8, local_id: LocalId, global_id: u32) {
let w_idx = worker_id as usize;
if w_idx >= id_map.len() {
id_map.resize(w_idx + 1, Vec::new());
}
let l_idx = local_id.0 as usize;
if l_idx >= id_map[w_idx].len() {
id_map[w_idx].resize(l_idx + 1, NO_INDEX);
}
id_map[w_idx][l_idx] = global_id;
}
#[inline]
fn resolve_id(id_map: &[Vec<u32>], worker_id: u8, local_id: LocalId) -> Option<u32> {
let w_idx = worker_id as usize;
if w_idx < id_map.len() {
let l_idx = local_id.0 as usize;
if l_idx < id_map[w_idx].len() {
let gid = id_map[w_idx][l_idx];
if gid != NO_INDEX {
return Some(gid);
}
}
}
None
}
#[inline]
fn connect_child(
arena: &mut [FileNode],
last_child_map: &mut [u32],
parent_global_id: u32,
child_global_id: u32,
) {
let p_idx = parent_global_id as usize;
let last_child = last_child_map[p_idx];
if last_child == NO_INDEX {
// This is the first child of the parent
arena[p_idx].first_child = child_global_id;
} else {
// We have a previous child, attach as its next sibling
arena[last_child as usize].next_sibling = child_global_id;
}
// Update the last child pointer for this parent
last_child_map[p_idx] = child_global_id;
}
#[inline]
fn propagate_size_and_time(
arena: &mut [FileNode],
start_parent_idx: u32,
size: u64,
modified: i64,
created: i64,
accessed: i64,
) {
let mut current_idx = Some(start_parent_idx);
while let Some(idx) = current_idx {
let node = &mut arena[idx as usize];
node.size += size;
node.file_count += 1;
if modified > node.modified_timestamp {
node.modified_timestamp = modified;
}
if created > node.created_timestamp {
node.created_timestamp = created;
}
if accessed > node.accessed_timestamp {
node.accessed_timestamp = accessed;
}
current_idx = node.parent_opt();
}
}