ant_node/replication/fresh.rs
1//! Fresh replication (Section 6.1).
2//!
3//! When a node accepts a newly written record with valid `PoP`:
4//! 1. Store locally (already done by chunk handler).
5//! 2. Record the key in `PaidForList(self)` and send `PaidNotify` to every
6//! peer in `PaidCloseGroup(K)` — immediately, never behind back-pressure.
7//! 3. Send fresh offers to `CLOSE_GROUP_SIZE` nearest peers (excluding self),
8//! bounded by the pending-offer permits so a write burst cannot pile up
9//! chunk-sized buffers.
10
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::sync::Arc;
13
14use crate::logging::{debug, warn};
15use bytes::Bytes;
16use rand::Rng;
17use saorsa_core::identity::PeerId;
18use saorsa_core::P2PNode;
19use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore};
20
21use crate::ant_protocol::XorName;
22use crate::replication::config::{
23 ReplicationConfig, FRESH_REPLICATION_DELIVERY_MAX_RETRIES, REPLICATION_PROTOCOL_ID,
24};
25use crate::replication::paid_list::PaidList;
26use crate::replication::possession::PossessionCheckEvent;
27use crate::replication::protocol::{
28 FreshReplicationOffer, PaidNotify, ReplicationMessage, ReplicationMessageBody,
29};
30
31/// A newly-stored chunk that needs fresh replication.
32///
33/// Sent from the chunk PUT handler to the replication engine via an
34/// unbounded channel so that the PUT response is not blocked by
35/// replication fan-out. The event deliberately carries no chunk bytes: the
36/// chunk is already on disk, and the offer dispatcher reads it back only
37/// once it holds a pending-offer permit, so a replication backlog queues as
38/// small events rather than chunk-sized buffers.
39pub struct FreshWriteEvent {
40 /// Content-address of the stored chunk.
41 pub key: XorName,
42 /// Serialized proof-of-payment.
43 pub payment_proof: Vec<u8>,
44}
45
46/// A write whose paid-list evidence has been announced and whose chunk offer
47/// is waiting for a pending-offer permit. Carries no chunk bytes.
48pub(crate) struct FreshOfferEvent {
49 pub(crate) key: XorName,
50 pub(crate) payment_proof: Vec<u8>,
51 /// Storage read-backs attempted so far; see `MAX_FRESH_READ_ATTEMPTS`.
52 pub(crate) read_attempts: u32,
53}
54
55/// Handles shared by everything that sends fresh offers, so the offer
56/// dispatcher task and the direct entry point run one pipeline.
57pub(crate) struct FreshOfferContext {
58 pub(crate) p2p_node: Arc<P2PNode>,
59 pub(crate) config: Arc<ReplicationConfig>,
60 /// Limits concurrent outbound chunk transfers across the engine.
61 pub(crate) send_semaphore: Arc<Semaphore>,
62 /// Delayed possession checks (ADR-0003) are scheduled here once an
63 /// offer's sends are dispatched.
64 pub(crate) possession_check_tx: mpsc::UnboundedSender<PossessionCheckEvent>,
65 /// Offers encoded and handed to at least one per-peer send, so tests can
66 /// tell a write that went out from one lost to back-pressure.
67 pub(crate) dispatched: Arc<AtomicU64>,
68}
69
70/// An encoded fresh offer and the pending-offer permit it holds.
71///
72/// Wrapped with [`Bytes::from_owner`], so the per-peer send tasks and the
73/// transport share the one buffer through reference-counted handles, and the
74/// permit is released only when the last handle anywhere is dropped. That is
75/// what caps the encoded offers alive at once at `MAX_PENDING_FRESH_OFFERS`.
76struct EncodedOffer {
77 bytes: Vec<u8>,
78 _pending: OwnedSemaphorePermit,
79}
80
81impl AsRef<[u8]> for EncodedOffer {
82 fn as_ref(&self) -> &[u8] {
83 &self.bytes
84 }
85}
86
87/// Rules 6-8: record the paid key locally and announce it to
88/// `PaidCloseGroup(K)`.
89///
90/// This is the evidence peers need to repair the key later, so it runs the
91/// moment a write is accepted and is never gated by the pending-offer permit
92/// or the send semaphore; both messages are small metadata.
93pub(crate) async fn announce_paid_write(
94 key: &XorName,
95 proof_of_payment: &[u8],
96 paid_list: &PaidList,
97 p2p_node: &Arc<P2PNode>,
98 config: &ReplicationConfig,
99) {
100 // Rule 6: Node that validates PoP adds K to PaidForList(self).
101 if let Err(e) = paid_list.insert(key).await {
102 warn!("Failed to add key {} to PaidForList: {e}", hex::encode(key));
103 }
104 // Rules 7-8: PaidNotify to every member of PaidCloseGroup(K).
105 send_paid_notify(key, proof_of_payment, p2p_node, config).await;
106}
107
108/// Rules 2-3: send fresh offers to the close group and schedule the delayed
109/// possession check (ADR-0003) for the responsible peers.
110///
111/// `pending_offer` is the caller's permit from the pending-offer semaphore;
112/// it is held with the encoded offer until the last handle to it is dropped.
113/// `data` and `proof_of_payment` are taken by value so they move into the
114/// offer instead of being copied.
115pub(crate) async fn send_fresh_offers(
116 ctx: &FreshOfferContext,
117 key: &XorName,
118 data: Vec<u8>,
119 proof_of_payment: Vec<u8>,
120 pending_offer: OwnedSemaphorePermit,
121) {
122 let self_id = *ctx.p2p_node.peer_id();
123
124 // Use the self-inclusive query to get the true close group, then filter
125 // self out.
126 let closest = ctx
127 .p2p_node
128 .dht_manager()
129 .find_closest_nodes_local_with_self(key, ctx.config.close_group_size)
130 .await;
131 let target_peers: Vec<PeerId> = closest
132 .iter()
133 .filter(|n| n.peer_id != self_id)
134 .map(|n| n.peer_id)
135 .collect();
136
137 let offer = FreshReplicationOffer {
138 key: *key,
139 data,
140 proof_of_payment,
141 };
142 let request_id = rand::thread_rng().gen::<u64>();
143 let offer_msg = ReplicationMessage {
144 request_id,
145 body: ReplicationMessageBody::FreshReplicationOffer(offer),
146 };
147
148 let Ok(encoded) = offer_msg.encode() else {
149 warn!(
150 "Failed to encode FreshReplicationOffer for {}",
151 hex::encode(key),
152 );
153 return;
154 };
155 // One encoded copy serves every per-peer send task and every retry; the
156 // transport borrows it through `Bytes` instead of taking a copy. The
157 // pending-offer permit travels with the buffer.
158 let encoded = Bytes::from_owner(EncodedOffer {
159 bytes: encoded,
160 _pending: pending_offer,
161 });
162 for peer in &target_peers {
163 let p2p = Arc::clone(&ctx.p2p_node);
164 let offer = encoded.clone();
165 let peer_id = *peer;
166 let sem = Arc::clone(&ctx.send_semaphore);
167 tokio::spawn(async move {
168 // Acquire a permit before sending — this caps the number of
169 // concurrent outbound replication transfers across the engine.
170 let _permit = sem.acquire().await;
171 debug!(
172 "Replication send permit acquired for peer {peer_id} ({} available)",
173 sem.available_permits()
174 );
175 // ADR-0003: best-effort delivery. Retry the push up to
176 // FRESH_REPLICATION_DELIVERY_MAX_RETRIES times on a transport
177 // failure so a transient hiccup doesn't silently drop the offer.
178 // Possession is judged separately by the delayed possession check.
179 let mut attempt = 0u32;
180 loop {
181 match p2p
182 .send_message(&peer_id, REPLICATION_PROTOCOL_ID, offer.clone(), &[])
183 .await
184 {
185 Ok(()) => break,
186 Err(e) => {
187 if attempt >= FRESH_REPLICATION_DELIVERY_MAX_RETRIES {
188 debug!(
189 "Failed to send fresh offer to {peer_id} after {} attempts: {e}",
190 attempt + 1
191 );
192 break;
193 }
194 attempt += 1;
195 debug!(
196 "Retrying fresh offer to {peer_id} (attempt {}): {e}",
197 attempt + 1
198 );
199 }
200 }
201 }
202 });
203 }
204
205 debug!(
206 "Fresh replication initiated for {} to {} peers",
207 hex::encode(key),
208 target_peers.len()
209 );
210
211 // Schedule the delayed possession check (ADR-0003) for the responsible
212 // close-group peers. A closed receiver (engine shutting down) is ignored.
213 if !target_peers.is_empty() {
214 ctx.dispatched.fetch_add(1, Ordering::Relaxed);
215 let _ = ctx.possession_check_tx.send(PossessionCheckEvent {
216 key: *key,
217 peers: target_peers,
218 });
219 }
220}
221
222/// Send `PaidNotify(K)` to every peer in `PaidCloseGroup(K)` (fire-and-forget).
223///
224/// Per Invariant 16: sender MUST attempt delivery to every member. The
225/// message is small metadata (no chunk data), so it is neither gated by the
226/// send semaphore nor by the pending-offer permit.
227async fn send_paid_notify(
228 key: &XorName,
229 proof_of_payment: &[u8],
230 p2p_node: &Arc<P2PNode>,
231 config: &ReplicationConfig,
232) {
233 let self_id = *p2p_node.peer_id();
234 let paid_group = p2p_node
235 .dht_manager()
236 .find_closest_nodes_local_with_self(key, config.paid_list_close_group_size)
237 .await;
238
239 let notify = PaidNotify {
240 key: *key,
241 proof_of_payment: proof_of_payment.to_vec(),
242 };
243 let request_id = rand::thread_rng().gen::<u64>();
244 let msg = ReplicationMessage {
245 request_id,
246 body: ReplicationMessageBody::PaidNotify(notify),
247 };
248
249 let Ok(encoded) = msg.encode() else {
250 warn!("Failed to encode PaidNotify for {}", hex::encode(key));
251 return;
252 };
253 // One buffer for every recipient; the sends only take handles.
254 let encoded = Bytes::from(encoded);
255 for node in &paid_group {
256 if node.peer_id == self_id {
257 continue;
258 }
259 let p2p = Arc::clone(p2p_node);
260 let data = encoded.clone();
261 let peer_id = node.peer_id;
262 tokio::spawn(async move {
263 if let Err(e) = p2p
264 .send_message(&peer_id, REPLICATION_PROTOCOL_ID, data, &[])
265 .await
266 {
267 debug!("Failed to send PaidNotify to {peer_id}: {e}");
268 }
269 });
270 }
271}
272
273#[cfg(test)]
274#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
275mod tests {
276 use super::*;
277
278 /// The permit is released with the last handle to the encoded offer, not
279 /// the first: a slice the transport still holds keeps the offer counted.
280 #[test]
281 fn the_pending_offer_permit_outlives_every_handle() {
282 let permits = Arc::new(Semaphore::new(1));
283 let permit = Arc::clone(&permits)
284 .try_acquire_owned()
285 .expect("free permit");
286 let offer = Bytes::from_owner(EncodedOffer {
287 bytes: vec![7; 16],
288 _pending: permit,
289 });
290 let held_elsewhere = offer.slice(4..8);
291
292 drop(offer);
293 assert_eq!(permits.available_permits(), 0);
294 drop(held_elsewhere);
295 assert_eq!(permits.available_permits(), 1);
296 }
297}