Skip to main content

ant_node/replication/
audit_coordinator.rs

1//! Auditor-side per-target admission for outbound `AuditChallenge`s.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use saorsa_core::identity::PeerId;
7use tokio::sync::{OwnedSemaphorePermit, Semaphore};
8
9/// Maximum concurrent `AuditChallenge` requests this auditor may have in
10/// flight to one target peer.
11///
12/// This intentionally matches the per-source digest admission cap enforced by
13/// the already-deployed fleet. Waiting here happens before the response
14/// deadline starts, so excess local bursts are serialized instead of being
15/// converted into guaranteed remote admission drops and false timeouts.
16pub(crate) const MAX_CONCURRENT_AUDIT_CHALLENGES_PER_TARGET: usize = 2;
17
18#[derive(Debug)]
19struct TargetLimiter {
20    semaphore: Arc<Semaphore>,
21    references: usize,
22}
23
24/// Shared limiter for all auditor-side flows that send `AuditChallenge`.
25#[derive(Debug, Default)]
26pub struct AuditChallengeCoordinator {
27    targets: Mutex<HashMap<PeerId, TargetLimiter>>,
28}
29
30/// Permit held while one outbound challenge is in flight.
31#[derive(Debug)]
32pub(crate) struct AuditChallengePermit {
33    coordinator: Arc<AuditChallengeCoordinator>,
34    peer: PeerId,
35    permit: Option<OwnedSemaphorePermit>,
36}
37
38/// RAII guard that releases a counted target reference unless disarmed.
39///
40/// A reference is counted *before* `acquire` awaits the per-target semaphore.
41/// Holding this guard across that await guarantees the reference is released
42/// even if the future is dropped while parked in the wait queue (task abort,
43/// enclosing `timeout`, or a racing `select!` branch). On a successful acquire
44/// the guard is disarmed and the returned [`AuditChallengePermit`] assumes the
45/// release on its own drop.
46struct ReferenceGuard<'a> {
47    coordinator: &'a AuditChallengeCoordinator,
48    peer: PeerId,
49    armed: bool,
50}
51
52impl ReferenceGuard<'_> {
53    fn disarm(&mut self) {
54        self.armed = false;
55    }
56}
57
58impl Drop for ReferenceGuard<'_> {
59    fn drop(&mut self) {
60        if self.armed {
61            self.coordinator.release_reference(self.peer);
62        }
63    }
64}
65
66impl AuditChallengeCoordinator {
67    /// Create an empty coordinator.
68    #[must_use]
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// Wait for a target-peer slot. Returns `None` only if the internal
74    /// semaphore was closed, which the coordinator never does in production.
75    pub(crate) async fn acquire(self: &Arc<Self>, peer: PeerId) -> Option<AuditChallengePermit> {
76        let semaphore = {
77            let mut targets = self.lock_targets();
78            let entry = targets.entry(peer).or_insert_with(|| TargetLimiter {
79                semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_CHALLENGES_PER_TARGET)),
80                references: 0,
81            });
82            entry.references = entry.references.saturating_add(1);
83            Arc::clone(&entry.semaphore)
84        };
85
86        // The reference is now counted. Hold it under an RAII guard across the
87        // await so a dropped/cancelled future still releases it; a closed
88        // semaphore releases it via the same guard on the early return.
89        let mut reference_guard = ReferenceGuard {
90            coordinator: self,
91            peer,
92            armed: true,
93        };
94
95        let Ok(permit) = semaphore.acquire_owned().await else {
96            return None;
97        };
98
99        // Hand the release off to the permit's own drop.
100        reference_guard.disarm();
101        Some(AuditChallengePermit {
102            coordinator: Arc::clone(self),
103            peer,
104            permit: Some(permit),
105        })
106    }
107
108    #[cfg(test)]
109    pub(crate) fn tracked_target_count(&self) -> usize {
110        self.lock_targets().len()
111    }
112
113    fn release_reference(&self, peer: PeerId) {
114        let mut targets = self.lock_targets();
115        let Some(entry) = targets.get_mut(&peer) else {
116            return;
117        };
118        entry.references = entry.references.saturating_sub(1);
119        if entry.references == 0 {
120            targets.remove(&peer);
121        }
122    }
123
124    fn lock_targets(&self) -> std::sync::MutexGuard<'_, HashMap<PeerId, TargetLimiter>> {
125        match self.targets.lock() {
126            Ok(guard) => guard,
127            Err(poisoned) => poisoned.into_inner(),
128        }
129    }
130}
131
132impl Drop for AuditChallengePermit {
133    fn drop(&mut self) {
134        let _permit = self.permit.take();
135        self.coordinator.release_reference(self.peer);
136    }
137}
138
139#[cfg(test)]
140#[allow(clippy::panic)]
141mod tests {
142    use std::sync::atomic::{AtomicUsize, Ordering};
143    use std::time::Duration;
144
145    use super::*;
146
147    const PEER_A: [u8; 32] = [0xA1; 32];
148    const PEER_B: [u8; 32] = [0xB2; 32];
149    const SHORT_WAIT: Duration = Duration::from_millis(50);
150
151    fn peer(bytes: [u8; 32]) -> PeerId {
152        PeerId::from_bytes(bytes)
153    }
154
155    #[tokio::test]
156    async fn excess_challenges_wait_and_are_not_dropped() {
157        let coordinator = Arc::new(AuditChallengeCoordinator::new());
158        let target = peer(PEER_A);
159        let first = coordinator.acquire(target).await;
160        let second = coordinator.acquire(target).await;
161        assert!(first.is_some());
162        assert!(second.is_some());
163
164        let acquired = Arc::new(AtomicUsize::new(0));
165        let acquired_clone = Arc::clone(&acquired);
166        let coordinator_clone = Arc::clone(&coordinator);
167        let waiting = tokio::spawn(async move {
168            let permit = coordinator_clone.acquire(target).await;
169            if permit.is_some() {
170                acquired_clone.fetch_add(1, Ordering::SeqCst);
171            }
172            permit
173        });
174
175        tokio::time::sleep(SHORT_WAIT).await;
176        assert_eq!(acquired.load(Ordering::SeqCst), 0);
177
178        drop(first);
179        let third = tokio::time::timeout(SHORT_WAIT, waiting).await;
180        assert!(third.is_ok());
181        assert_eq!(acquired.load(Ordering::SeqCst), 1);
182
183        drop(second);
184        if let Ok(joined) = third {
185            match joined {
186                Ok(permit) => drop(permit),
187                Err(e) => panic!("waiting task failed: {e}"),
188            }
189        }
190        assert_eq!(coordinator.tracked_target_count(), 0);
191    }
192
193    #[tokio::test]
194    async fn cross_peer_parallelism_is_preserved() {
195        let coordinator = Arc::new(AuditChallengeCoordinator::new());
196        let target_a = peer(PEER_A);
197        let target_b = peer(PEER_B);
198        let first_a = coordinator.acquire(target_a).await;
199        let second_a = coordinator.acquire(target_a).await;
200        assert!(first_a.is_some());
201        assert!(second_a.is_some());
202
203        let coordinator_clone = Arc::clone(&coordinator);
204        let acquired_b = tokio::spawn(async move { coordinator_clone.acquire(target_b).await });
205        let result = tokio::time::timeout(SHORT_WAIT, acquired_b).await;
206        assert!(result.is_ok());
207    }
208
209    #[tokio::test]
210    async fn cancelled_wait_releases_reference() {
211        let coordinator = Arc::new(AuditChallengeCoordinator::new());
212        let target = peer(PEER_A);
213        // Saturate the target so a third acquire parks in the wait queue.
214        let first = coordinator.acquire(target).await;
215        let second = coordinator.acquire(target).await;
216        assert!(first.is_some());
217        assert!(second.is_some());
218
219        // A parked acquire whose future is dropped mid-await must not leak the
220        // reference it counted before parking.
221        let parked = coordinator.acquire(target);
222        let dropped = tokio::time::timeout(SHORT_WAIT, parked).await;
223        assert!(dropped.is_err(), "third acquire should still be parked");
224
225        drop(first);
226        drop(second);
227        assert_eq!(
228            coordinator.tracked_target_count(),
229            0,
230            "cancelled wait leaked a target reference"
231        );
232    }
233}