1use std::collections::HashSet;
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use crate::logging::{debug, info, warn};
11use tokio::sync::RwLock;
12use tokio_util::sync::CancellationToken;
13
14use saorsa_core::DhtNetworkEvent;
15
16use crate::ant_protocol::XorName;
17use crate::replication::scheduling::ReplicationQueues;
18use crate::replication::types::BootstrapState;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum BootstrapGateResult {
27 Received,
29 TimedOut,
31 Shutdown,
33}
34
35pub async fn wait_for_bootstrap_complete(
47 mut dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
48 timeout_secs: u64,
49 shutdown: &CancellationToken,
50) -> BootstrapGateResult {
51 let timeout = Duration::from_secs(timeout_secs);
52
53 let result = tokio::select! {
54 () = shutdown.cancelled() => {
55 debug!("Bootstrap sync: shutdown during BootstrapComplete wait");
56 BootstrapGateResult::Shutdown
57 }
58 () = tokio::time::sleep(timeout) => {
59 warn!(
60 "Bootstrap sync: timed out after {timeout_secs}s waiting for \
61 BootstrapComplete — proceeding (likely a bootstrap node with no peers)",
62 );
63 BootstrapGateResult::TimedOut
64 }
65 gate = async {
66 loop {
67 match dht_events.recv().await {
68 Ok(DhtNetworkEvent::BootstrapComplete { num_peers }) => {
69 info!(
70 "Bootstrap sync: DHT bootstrap complete \
71 with {num_peers} peers in routing table"
72 );
73 break BootstrapGateResult::Received;
74 }
75 Ok(_) => {}
76 Err(e) => {
77 warn!(
78 "Bootstrap sync: DHT event channel error: {e}, \
79 proceeding without gate"
80 );
81 break BootstrapGateResult::TimedOut;
82 }
83 }
84 }
85 } => gate,
86 };
87 drop(dht_events);
88 result
89}
90
91pub async fn mark_bootstrap_drained(bootstrap_state: &Arc<RwLock<BootstrapState>>) {
99 let mut state = bootstrap_state.write().await;
100 state.drained = true;
101 info!("Bootstrap explicitly marked as drained");
102}
103
104pub async fn check_bootstrap_drained(
113 bootstrap_state: &Arc<RwLock<BootstrapState>>,
114 queues: &ReplicationQueues,
115) -> bool {
116 let mut state = bootstrap_state.write().await;
117 if state.drained {
118 return true;
119 }
120
121 if state.pending_peer_requests > 0 {
122 return false;
123 }
124
125 if !state.capacity_rejected_sources.is_empty() {
134 let n = state.capacity_rejected_sources.len();
135 debug!("Bootstrap NOT drained: {n} source(s) have outstanding capacity-rejected hints");
136 return false;
137 }
138
139 if queues.is_bootstrap_work_empty(&state.pending_keys) {
140 state.drained = true;
141 info!("Bootstrap drained: all peer requests completed and work queues empty");
142 true
143 } else {
144 false
145 }
146}
147
148pub async fn note_capacity_rejected(
160 bootstrap_state: &Arc<RwLock<BootstrapState>>,
161 source: saorsa_core::identity::PeerId,
162) {
163 let mut state = bootstrap_state.write().await;
164 if state.note_capacity_rejected(source, Instant::now()) {
165 let n = state.capacity_rejected_sources.len();
166 debug!(
167 "Bootstrap: source {source} now has outstanding capacity-rejected hints \
168 ({n} sources outstanding)"
169 );
170 }
171}
172
173pub async fn clear_capacity_rejected(
180 bootstrap_state: &Arc<RwLock<BootstrapState>>,
181 source: &saorsa_core::identity::PeerId,
182) -> bool {
183 let mut state = bootstrap_state.write().await;
184 if state.capacity_rejected_sources.remove(source).is_some() {
185 let n = state.capacity_rejected_sources.len();
186 debug!(
187 "Bootstrap: cleared outstanding capacity rejections for {source} \
188 ({n} sources still outstanding)"
189 );
190 true
191 } else {
192 false
193 }
194}
195
196pub async fn expire_capacity_rejected(
206 bootstrap_state: &Arc<RwLock<BootstrapState>>,
207 max_age: Duration,
208) -> usize {
209 let now = Instant::now();
210 let mut state = bootstrap_state.write().await;
211 let before = state.capacity_rejected_sources.len();
212 state
213 .capacity_rejected_sources
214 .retain(|source, rejected_at| {
215 let expired = now.duration_since(*rejected_at) >= max_age;
216 if expired {
217 warn!(
218 "Bootstrap: expiring capacity-rejection record for {source} — the source \
219 abandoned re-delivery (or departed mid-admission) and the hints it still \
220 owed are forfeited"
221 );
222 }
223 !expired
224 });
225 before - state.capacity_rejected_sources.len()
226}
227
228#[allow(clippy::implicit_hasher)]
230pub async fn track_discovered_keys(
231 bootstrap_state: &Arc<RwLock<BootstrapState>>,
232 keys: &HashSet<XorName>,
233) {
234 let mut state = bootstrap_state.write().await;
235 state.pending_keys.extend(keys);
236 debug!(
237 "Bootstrap tracking {} total discovered keys",
238 state.pending_keys.len()
239 );
240}
241
242pub async fn increment_pending_requests(
244 bootstrap_state: &Arc<RwLock<BootstrapState>>,
245 count: usize,
246) {
247 let mut state = bootstrap_state.write().await;
248 state.pending_peer_requests += count;
249}
250
251pub async fn decrement_pending_requests(
253 bootstrap_state: &Arc<RwLock<BootstrapState>>,
254 count: usize,
255) {
256 let mut state = bootstrap_state.write().await;
257 state.pending_peer_requests = state.pending_peer_requests.saturating_sub(count);
258}
259
260#[cfg(test)]
265#[allow(clippy::unwrap_used, clippy::expect_used)]
266mod tests {
267 use super::*;
268
269 fn xor_name_from_byte(b: u8) -> XorName {
270 [b; 32]
271 }
272
273 #[tokio::test]
274 async fn check_drained_when_already_drained() {
275 let state = Arc::new(RwLock::new(BootstrapState {
276 drained: true,
277 pending_peer_requests: 5,
278 pending_keys: HashSet::new(),
279 capacity_rejected_sources: std::collections::HashMap::new(),
280 }));
281 let queues = ReplicationQueues::new();
282
283 assert!(
284 check_bootstrap_drained(&state, &queues).await,
285 "should be drained when flag is already set"
286 );
287 }
288
289 #[tokio::test]
290 async fn check_drained_blocked_by_pending_requests() {
291 let state = Arc::new(RwLock::new(BootstrapState {
292 drained: false,
293 pending_peer_requests: 2,
294 pending_keys: HashSet::new(),
295 capacity_rejected_sources: std::collections::HashMap::new(),
296 }));
297 let queues = ReplicationQueues::new();
298
299 assert!(
300 !check_bootstrap_drained(&state, &queues).await,
301 "should not drain with pending requests"
302 );
303 }
304
305 #[tokio::test]
306 async fn check_drained_transitions_when_all_work_done() {
307 let state = Arc::new(RwLock::new(BootstrapState {
308 drained: false,
309 pending_peer_requests: 0,
310 pending_keys: std::iter::once(xor_name_from_byte(0x01)).collect(),
311 capacity_rejected_sources: std::collections::HashMap::new(),
312 }));
313 let queues = ReplicationQueues::new();
314
315 assert!(check_bootstrap_drained(&state, &queues).await);
317 assert!(state.read().await.drained, "drained flag should be set");
318 }
319
320 #[tokio::test]
321 async fn check_drained_blocked_by_queued_key() {
322 let state = Arc::new(RwLock::new(BootstrapState {
323 drained: false,
324 pending_peer_requests: 0,
325 pending_keys: std::iter::once(xor_name_from_byte(0x01)).collect(),
326 capacity_rejected_sources: std::collections::HashMap::new(),
327 }));
328 let mut queues = ReplicationQueues::new();
329
330 let now = Instant::now();
332 let entry = crate::replication::types::VerificationEntry {
333 state: crate::replication::types::VerificationState::PendingVerify,
334 verified_sources: Vec::new(),
335 tried_sources: HashSet::new(),
336 created_at: now,
337 next_verify_at: now,
338 hint_sources: HashSet::from([saorsa_core::identity::PeerId::from_bytes([0u8; 32])]),
339 replica_hint_sources: HashSet::from([saorsa_core::identity::PeerId::from_bytes(
340 [0u8; 32],
341 )]),
342 unresolved_retries: 0,
343 no_holder_reported: false,
344 };
345 queues.add_pending_verify(xor_name_from_byte(0x01), entry);
346
347 assert!(
348 !check_bootstrap_drained(&state, &queues).await,
349 "should not drain while bootstrap key is still in pipeline"
350 );
351 }
352
353 #[tokio::test]
354 async fn mark_bootstrap_drained_sets_flag() {
355 let state = Arc::new(RwLock::new(BootstrapState::new()));
356 mark_bootstrap_drained(&state).await;
357 assert!(state.read().await.drained);
358 }
359
360 #[tokio::test]
361 async fn track_discovered_keys_accumulates() {
362 let state = Arc::new(RwLock::new(BootstrapState::new()));
363 let set_a: HashSet<XorName> = [xor_name_from_byte(0x01), xor_name_from_byte(0x02)]
364 .into_iter()
365 .collect();
366 let set_b: HashSet<XorName> = [xor_name_from_byte(0x02), xor_name_from_byte(0x03)]
367 .into_iter()
368 .collect();
369
370 track_discovered_keys(&state, &set_a).await;
371 track_discovered_keys(&state, &set_b).await;
372
373 let s = state.read().await;
374 assert_eq!(s.pending_keys.len(), 3, "should deduplicate across calls");
375 }
376
377 #[tokio::test]
378 async fn increment_and_decrement_pending_requests() {
379 let state = Arc::new(RwLock::new(BootstrapState::new()));
380
381 increment_pending_requests(&state, 5).await;
382 assert_eq!(state.read().await.pending_peer_requests, 5);
383
384 decrement_pending_requests(&state, 3).await;
385 assert_eq!(state.read().await.pending_peer_requests, 2);
386
387 decrement_pending_requests(&state, 10).await;
389 assert_eq!(
390 state.read().await.pending_peer_requests,
391 0,
392 "should saturate at zero"
393 );
394 }
395
396 #[tokio::test]
402 async fn capacity_rejected_clears_on_clean_cycle() {
403 let state = Arc::new(RwLock::new(BootstrapState::new()));
404 let queues = ReplicationQueues::new();
405 let source = saorsa_core::identity::PeerId::from_bytes([7u8; 32]);
406
407 note_capacity_rejected(&state, source).await;
409 assert!(
410 !check_bootstrap_drained(&state, &queues).await,
411 "drain must be blocked while a source has outstanding capacity rejections"
412 );
413
414 clear_capacity_rejected(&state, &source).await;
416 assert!(
417 check_bootstrap_drained(&state, &queues).await,
418 "drain must complete once the source's outstanding rejections are cleared"
419 );
420 }
421
422 #[tokio::test]
425 async fn capacity_rejected_is_per_source() {
426 let state = Arc::new(RwLock::new(BootstrapState::new()));
427 let queues = ReplicationQueues::new();
428 let source_a = saorsa_core::identity::PeerId::from_bytes([0xAA; 32]);
429 let source_b = saorsa_core::identity::PeerId::from_bytes([0xBB; 32]);
430
431 note_capacity_rejected(&state, source_a).await;
432 note_capacity_rejected(&state, source_b).await;
433 assert!(!check_bootstrap_drained(&state, &queues).await);
434
435 clear_capacity_rejected(&state, &source_a).await;
437 assert!(
438 !check_bootstrap_drained(&state, &queues).await,
439 "B's outstanding rejections must keep drain blocked"
440 );
441
442 clear_capacity_rejected(&state, &source_b).await;
443 assert!(check_bootstrap_drained(&state, &queues).await);
444 }
445
446 #[tokio::test]
449 async fn capacity_rejected_within_ttl_still_blocks_drain() {
450 let state = Arc::new(RwLock::new(BootstrapState::new()));
451 let queues = ReplicationQueues::new();
452 let source = saorsa_core::identity::PeerId::from_bytes([0xC1; 32]);
453
454 note_capacity_rejected(&state, source).await;
455 assert_eq!(
456 expire_capacity_rejected(&state, Duration::from_secs(3600)).await,
457 0,
458 "a fresh rejection must survive expiry with a generous max_age"
459 );
460 assert!(
461 !check_bootstrap_drained(&state, &queues).await,
462 "a within-TTL rejection must keep drain blocked"
463 );
464 }
465
466 #[tokio::test]
469 async fn capacity_rejected_expiry_unblocks_drain() {
470 let state = Arc::new(RwLock::new(BootstrapState::new()));
471 let queues = ReplicationQueues::new();
472 let source = saorsa_core::identity::PeerId::from_bytes([0xC2; 32]);
473
474 note_capacity_rejected(&state, source).await;
475 assert!(!check_bootstrap_drained(&state, &queues).await);
476
477 assert_eq!(expire_capacity_rejected(&state, Duration::ZERO).await, 1);
478 assert!(
479 check_bootstrap_drained(&state, &queues).await,
480 "drain must complete once the abandoned rejection expires"
481 );
482 }
483
484 #[tokio::test]
487 async fn capacity_rejected_expiry_is_per_source() {
488 let state = Arc::new(RwLock::new(BootstrapState::new()));
489 let queues = ReplicationQueues::new();
490 let stale_source = saorsa_core::identity::PeerId::from_bytes([0xC3; 32]);
491 let fresh_source = saorsa_core::identity::PeerId::from_bytes([0xC4; 32]);
492 let max_age = Duration::from_secs(60);
493 let stale_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
494
495 state
496 .write()
497 .await
498 .capacity_rejected_sources
499 .insert(stale_source, stale_rejected_at);
500 note_capacity_rejected(&state, fresh_source).await;
501
502 assert_eq!(expire_capacity_rejected(&state, max_age).await, 1);
503 assert!(
504 state
505 .read()
506 .await
507 .capacity_rejected_sources
508 .contains_key(&fresh_source),
509 "the fresh source must survive another source's expiry"
510 );
511 assert!(
512 !check_bootstrap_drained(&state, &queues).await,
513 "the fresh source must still block drain"
514 );
515 }
516
517 #[tokio::test]
525 async fn repeat_capacity_rejection_does_not_refresh_timestamp() {
526 let state = Arc::new(RwLock::new(BootstrapState::new()));
527 let source = saorsa_core::identity::PeerId::from_bytes([0xC5; 32]);
528 let max_age = Duration::from_secs(60);
529 let first_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
530
531 state
532 .write()
533 .await
534 .capacity_rejected_sources
535 .insert(source, first_rejected_at);
536 note_capacity_rejected(&state, source).await;
537
538 let recorded_at = state
539 .read()
540 .await
541 .capacity_rejected_sources
542 .get(&source)
543 .copied()
544 .unwrap();
545 assert_eq!(
546 recorded_at, first_rejected_at,
547 "a repeat rejection must leave the first-seen time alone"
548 );
549 assert_eq!(
550 expire_capacity_rejected(&state, max_age).await,
551 1,
552 "an aged debt must still expire even though the source keeps \
553 re-overflowing the queue"
554 );
555 }
556
557 #[tokio::test]
562 async fn sustained_capacity_rejection_still_drains_after_ttl() {
563 const REJECTION_ROUNDS: usize = 8;
564
565 let state = Arc::new(RwLock::new(BootstrapState::new()));
566 let queues = ReplicationQueues::new();
567 let source = saorsa_core::identity::PeerId::from_bytes([0xC6; 32]);
568 let max_age = Duration::from_secs(60);
569
570 for _ in 0..REJECTION_ROUNDS {
571 note_capacity_rejected(&state, source).await;
572 assert!(
573 !check_bootstrap_drained(&state, &queues).await,
574 "an outstanding debt must block drain while it is inside the TTL"
575 );
576 }
577
578 let aged = Instant::now().checked_sub(max_age * 2).unwrap();
580 state
581 .write()
582 .await
583 .capacity_rejected_sources
584 .insert(source, aged);
585
586 assert_eq!(
587 expire_capacity_rejected(&state, max_age).await,
588 1,
589 "the debt must expire once the FIRST rejection is older than the TTL"
590 );
591 assert!(
592 check_bootstrap_drained(&state, &queues).await,
593 "bootstrap must drain once the expired debt is forfeited"
594 );
595 }
596}