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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::collections::{BTreeSet, HashSet};
use std::sync::{Arc, Mutex};
use rostra_client_db::{CurrentState, Database, DbResult, WotData};
use rostra_core::ShortEventId;
use rostra_core::id::{RostraId, ToShort as _};
use tokio::sync::{broadcast, watch};
use tokio::task::JoinSet;
use tracing::{debug, error, instrument, trace, warn};
use crate::LOG_TARGET;
use crate::client::Client;
use crate::connection_cache::ConnectionCache;
use crate::net::ClientNetworking;
#[cfg(test)]
mod tests;
const NUM_WORKERS: usize = 8;
const MAX_PENDING_AUTHORS: usize = 128;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HeadReconcileOutcome {
Complete,
MoreCandidates,
QueueFull,
}
/// Work queue that coalesces pending author IDs and prevents
/// concurrent fetches for the same author.
struct WorkQueue {
inner: Mutex<WorkQueueInner>,
notify: watch::Sender<()>,
space_available: tokio::sync::Notify,
}
struct WorkQueueInner {
pending: BTreeSet<RostraId>,
in_progress: HashSet<RostraId>,
}
impl WorkQueue {
fn new() -> (Arc<Self>, watch::Receiver<()>) {
let (notify, notify_rx) = watch::channel(());
let queue = Arc::new(Self {
inner: Mutex::new(WorkQueueInner {
pending: BTreeSet::new(),
in_progress: HashSet::new(),
}),
notify,
space_available: tokio::sync::Notify::new(),
});
(queue, notify_rx)
}
/// Add an author to the pending set and notify workers.
fn try_enqueue(&self, id: RostraId) -> bool {
let mut inner = self.inner.lock().expect("not poisoned");
if inner.pending.contains(&id) {
return true;
}
if MAX_PENDING_AUTHORS <= inner.pending.len() {
return false;
}
inner.pending.insert(id);
drop(inner);
let _ = self.notify.send(());
true
}
/// Take an author from the pending set that is not already
/// in progress. Returns `None` if no eligible work is available.
fn take_work(self: &Arc<Self>) -> Option<WorkLease> {
let mut inner = self.inner.lock().expect("not poisoned");
let id = inner
.pending
.iter()
.find(|id| !inner.in_progress.contains(id))
.copied()?;
inner.pending.remove(&id);
inner.in_progress.insert(id);
Some(WorkLease {
queue: self.clone(),
author: id,
})
}
/// Mark an author as no longer in progress and notify workers,
/// since previously skipped pending items may now be eligible.
fn complete_work(&self, id: &RostraId) {
self.inner
.lock()
.expect("not poisoned")
.in_progress
.remove(id);
let _ = self.notify.send(());
self.space_available.notify_one();
}
}
/// Releases exclusive ownership of an author on every worker exit path.
struct WorkLease {
queue: Arc<WorkQueue>,
author: RostraId,
}
impl Drop for WorkLease {
fn drop(&mut self) {
self.queue.complete_work(&self.author);
}
}
/// Fetches events when any ID gets a new head written to the database.
///
/// This task subscribes to new head notifications from the database
/// and fetches the corresponding events from followers.
///
/// Only processes heads from IDs in our web of trust (self, followees,
/// and extended followees).
///
/// Uses a pool of worker tasks to fetch events in parallel. Incoming
/// author IDs are coalesced in a bounded queue, so multiple rapid updates
/// for the same author result in a single fetch. Durable heads are reconciled
/// at startup, after notification loss, and after WoT changes. At most one
/// worker handles a given author at a time. A database failure in any worker
/// stops the parent and cancels all sibling workers.
pub struct NewHeadFetcher {
networking: Arc<ClientNetworking>,
db: Arc<Database>,
self_id: RostraId,
new_heads_rx: broadcast::Receiver<(RostraId, ShortEventId)>,
wot: CurrentState<Arc<WotData>>,
connections: ConnectionCache,
}
impl NewHeadFetcher {
pub fn new(client: &Client) -> Self {
debug!(target: LOG_TARGET, "Starting new head fetcher");
Self {
networking: client.networking().clone(),
db: client.db().clone(),
self_id: client.rostra_id(),
new_heads_rx: client.new_heads_subscribe(),
wot: client.self_wot_subscribe(),
connections: client.connection_cache().clone(),
}
}
#[instrument(name = "new-head-fetcher", skip(self), fields(self_id = %self.self_id.fmt_short()), ret)]
pub async fn run(mut self) {
debug!(
target: LOG_TARGET,
count = self.wot.snapshot().len(),
"Started with web of trust cache"
);
let (queue, notify_rx) = WorkQueue::new();
let mut workers = JoinSet::new();
for worker_id in 0..NUM_WORKERS {
workers.spawn(Self::worker(
worker_id,
queue.clone(),
notify_rx.clone(),
self.networking.clone(),
self.db.clone(),
self.self_id,
self.connections.clone(),
));
}
let mut reconcile_cursor = None;
// Capture the WoT baseline before the startup scan. Any admission that
// races with the scan remains visible through `changed()`.
let mut previous_wot = self.wot.snapshot();
let mut reconciliation_pending = matches!(
self.advance_current_heads_reconciliation(&queue, &mut reconcile_cursor)
.await,
HeadReconcileOutcome::QueueFull
);
let mut reconcile_again = false;
loop {
tokio::select! {
res = self.new_heads_rx.recv() => {
let (author, head) = match res {
Ok(msg) => msg,
Err(broadcast::error::RecvError::Closed) => {
debug!(target: LOG_TARGET, "New heads channel closed, shutting down");
break;
}
Err(broadcast::error::RecvError::Lagged(n)) => {
warn!(target: LOG_TARGET, lagged = n, "New head fetcher missed notifications; reconciling durable heads");
if reconciliation_pending {
reconcile_again = true;
} else {
reconcile_cursor = None;
reconciliation_pending = matches!(
self.advance_current_heads_reconciliation(
&queue,
&mut reconcile_cursor,
).await,
HeadReconcileOutcome::QueueFull
);
}
continue;
}
};
trace!(target: LOG_TARGET, author = %author.to_short(), %head, "New head notification received");
// Check if author is in our web of trust using the cached WoT
let in_wot = {
let wot = self.wot.snapshot();
wot.contains(author, self.self_id)
};
if !in_wot {
trace!(
target: LOG_TARGET,
author = %author.to_short(),
%head,
"Ignoring head from ID not in web of trust"
);
continue;
}
if !queue.try_enqueue(author) {
if reconciliation_pending {
reconcile_again = true;
} else {
reconcile_cursor = None;
reconciliation_pending = true;
}
}
}
res = self.wot.changed() => {
if res.is_err() {
debug!(target: LOG_TARGET, "WoT channel closed, shutting down");
break;
}
debug!(
target: LOG_TARGET,
count = self.wot.snapshot().len(),
"Web of trust cache updated"
);
let current_wot = self.wot.snapshot();
for author in newly_admitted_authors(
&previous_wot,
¤t_wot,
self.self_id,
) {
if !self.db.get_heads(author).await.is_empty()
&& !queue.try_enqueue(author)
{
break;
}
}
previous_wot = current_wot;
// A watch publication can coalesce remove/re-add transitions
// that have no visible snapshot delta. Reconcile durable heads
// once per coalesced update, without restarting an active scan.
if reconciliation_pending {
reconcile_again = true;
} else {
reconcile_cursor = None;
reconciliation_pending = matches!(
self.advance_current_heads_reconciliation(
&queue,
&mut reconcile_cursor,
).await,
HeadReconcileOutcome::QueueFull
);
}
}
() = queue.space_available.notified(), if reconciliation_pending => {
reconciliation_pending = matches!(
self.advance_current_heads_reconciliation(
&queue,
&mut reconcile_cursor,
).await,
HeadReconcileOutcome::QueueFull
);
if !reconciliation_pending && reconcile_again {
reconcile_again = false;
reconcile_cursor = None;
reconciliation_pending = matches!(
self.advance_current_heads_reconciliation(
&queue,
&mut reconcile_cursor,
).await,
HeadReconcileOutcome::QueueFull
);
}
}
worker = workers.join_next() => {
match worker {
Some(Ok(Ok(()))) => {
error!(target: LOG_TARGET, "New-head worker stopped unexpectedly; stopping fetcher");
}
Some(Ok(Err(err))) => {
error!(
target: LOG_TARGET,
err = %err,
"Database ingestion failed in new-head worker; stopping fetcher"
);
}
Some(Err(err)) => {
error!(
target: LOG_TARGET,
err = %err,
"New-head worker panicked or was cancelled; stopping fetcher"
);
}
None => {
error!(target: LOG_TARGET, "New-head worker pool stopped; stopping fetcher");
}
}
break;
}
}
}
workers.abort_all();
while workers.join_next().await.is_some() {}
}
async fn advance_current_heads_reconciliation(
&self,
queue: &WorkQueue,
cursor: &mut Option<RostraId>,
) -> HeadReconcileOutcome {
loop {
match self.reconcile_current_heads(queue, cursor).await {
HeadReconcileOutcome::MoreCandidates => continue,
outcome => return outcome,
}
}
}
async fn reconcile_current_heads(
&self,
queue: &WorkQueue,
cursor: &mut Option<RostraId>,
) -> HeadReconcileOutcome {
let authors = self
.db
.get_ids_with_heads(*cursor, MAX_PENDING_AUTHORS)
.await;
let reached_end = authors.len() < MAX_PENDING_AUTHORS;
let wot = self.wot.snapshot();
enqueue_reconciled_authors(queue, authors, reached_end, &wot, self.self_id, cursor)
}
async fn worker(
worker_id: usize,
queue: Arc<WorkQueue>,
mut notify_rx: watch::Receiver<()>,
networking: Arc<ClientNetworking>,
db: Arc<Database>,
self_id: RostraId,
connections: ConnectionCache,
) -> DbResult<()> {
loop {
let Some(lease) = queue.take_work() else {
// No eligible work — wait for notification
if notify_rx.changed().await.is_err() {
trace!(target: LOG_TARGET, worker_id, "Worker shutting down");
break;
}
continue;
};
let author = lease.author;
let heads = db.get_heads(author).await;
for head in heads {
if let Err(err) = Self::fetch_events_for_head(
author,
head,
&networking,
&connections,
self_id,
&db,
)
.await
{
error!(
target: LOG_TARGET,
worker_id,
author = %author.to_short(),
%head,
err = %err,
"Database ingestion failed; stopping new-head worker"
);
return Err(err);
}
}
}
Ok(())
}
async fn fetch_events_for_head(
author: RostraId,
head: ShortEventId,
networking: &ClientNetworking,
connections: &ConnectionCache,
self_id: RostraId,
db: &Database,
) -> DbResult<()> {
let followers = db.get_followers(author).await;
let peers: Vec<RostraId> = followers.into_iter().chain([author, self_id]).collect();
match crate::util::rpc::download_events_from_child(
author,
head,
networking,
connections,
&peers,
db,
)
.await?
{
true => {
debug!(
target: LOG_TARGET,
author = %author.to_short(),
%head,
"Successfully fetched events for new head"
);
}
false => {
debug!(
target: LOG_TARGET,
author = %author.to_short(),
%head,
"No new events found from any peer"
);
}
}
Ok(())
}
}
fn newly_admitted_authors<'a>(
previous: &'a WotData,
current: &'a WotData,
self_id: RostraId,
) -> impl Iterator<Item = RostraId> + 'a {
current
.iter_all()
.filter(move |author| !previous.contains(*author, self_id))
}
fn enqueue_reconciled_authors(
queue: &WorkQueue,
authors: Vec<RostraId>,
reached_end: bool,
wot: &WotData,
self_id: RostraId,
cursor: &mut Option<RostraId>,
) -> HeadReconcileOutcome {
for author in authors {
if wot.contains(author, self_id) && !queue.try_enqueue(author) {
return HeadReconcileOutcome::QueueFull;
}
*cursor = Some(author);
}
if reached_end {
*cursor = None;
HeadReconcileOutcome::Complete
} else {
HeadReconcileOutcome::MoreCandidates
}
}