use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use crate::logging::{debug, warn};
use bytes::Bytes;
use rand::Rng;
use saorsa_core::identity::PeerId;
use saorsa_core::P2PNode;
use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore};
use crate::ant_protocol::XorName;
use crate::replication::config::{
ReplicationConfig, FRESH_REPLICATION_DELIVERY_MAX_RETRIES, REPLICATION_PROTOCOL_ID,
};
use crate::replication::paid_list::PaidList;
use crate::replication::possession::PossessionCheckEvent;
use crate::replication::protocol::{
FreshReplicationOffer, PaidNotify, ReplicationMessage, ReplicationMessageBody,
};
pub struct FreshWriteEvent {
pub key: XorName,
pub payment_proof: Vec<u8>,
}
pub(crate) struct FreshOfferEvent {
pub(crate) key: XorName,
pub(crate) payment_proof: Vec<u8>,
pub(crate) read_attempts: u32,
}
pub(crate) struct FreshOfferContext {
pub(crate) p2p_node: Arc<P2PNode>,
pub(crate) config: Arc<ReplicationConfig>,
pub(crate) send_semaphore: Arc<Semaphore>,
pub(crate) possession_check_tx: mpsc::UnboundedSender<PossessionCheckEvent>,
pub(crate) dispatched: Arc<AtomicU64>,
}
struct EncodedOffer {
bytes: Vec<u8>,
_pending: OwnedSemaphorePermit,
}
impl AsRef<[u8]> for EncodedOffer {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
pub(crate) async fn announce_paid_write(
key: &XorName,
proof_of_payment: &[u8],
paid_list: &PaidList,
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
) {
if let Err(e) = paid_list.insert(key).await {
warn!("Failed to add key {} to PaidForList: {e}", hex::encode(key));
}
send_paid_notify(key, proof_of_payment, p2p_node, config).await;
}
pub(crate) async fn send_fresh_offers(
ctx: &FreshOfferContext,
key: &XorName,
data: Vec<u8>,
proof_of_payment: Vec<u8>,
pending_offer: OwnedSemaphorePermit,
) {
let self_id = *ctx.p2p_node.peer_id();
let closest = ctx
.p2p_node
.dht_manager()
.find_closest_nodes_local_with_self(key, ctx.config.close_group_size)
.await;
let target_peers: Vec<PeerId> = closest
.iter()
.filter(|n| n.peer_id != self_id)
.map(|n| n.peer_id)
.collect();
let offer = FreshReplicationOffer {
key: *key,
data,
proof_of_payment,
};
let request_id = rand::thread_rng().gen::<u64>();
let offer_msg = ReplicationMessage {
request_id,
body: ReplicationMessageBody::FreshReplicationOffer(offer),
};
let Ok(encoded) = offer_msg.encode() else {
warn!(
"Failed to encode FreshReplicationOffer for {}",
hex::encode(key),
);
return;
};
let encoded = Bytes::from_owner(EncodedOffer {
bytes: encoded,
_pending: pending_offer,
});
for peer in &target_peers {
let p2p = Arc::clone(&ctx.p2p_node);
let offer = encoded.clone();
let peer_id = *peer;
let sem = Arc::clone(&ctx.send_semaphore);
tokio::spawn(async move {
let _permit = sem.acquire().await;
debug!(
"Replication send permit acquired for peer {peer_id} ({} available)",
sem.available_permits()
);
let mut attempt = 0u32;
loop {
match p2p
.send_message(&peer_id, REPLICATION_PROTOCOL_ID, offer.clone(), &[])
.await
{
Ok(()) => break,
Err(e) => {
if attempt >= FRESH_REPLICATION_DELIVERY_MAX_RETRIES {
debug!(
"Failed to send fresh offer to {peer_id} after {} attempts: {e}",
attempt + 1
);
break;
}
attempt += 1;
debug!(
"Retrying fresh offer to {peer_id} (attempt {}): {e}",
attempt + 1
);
}
}
}
});
}
debug!(
"Fresh replication initiated for {} to {} peers",
hex::encode(key),
target_peers.len()
);
if !target_peers.is_empty() {
ctx.dispatched.fetch_add(1, Ordering::Relaxed);
let _ = ctx.possession_check_tx.send(PossessionCheckEvent {
key: *key,
peers: target_peers,
});
}
}
async fn send_paid_notify(
key: &XorName,
proof_of_payment: &[u8],
p2p_node: &Arc<P2PNode>,
config: &ReplicationConfig,
) {
let self_id = *p2p_node.peer_id();
let paid_group = p2p_node
.dht_manager()
.find_closest_nodes_local_with_self(key, config.paid_list_close_group_size)
.await;
let notify = PaidNotify {
key: *key,
proof_of_payment: proof_of_payment.to_vec(),
};
let request_id = rand::thread_rng().gen::<u64>();
let msg = ReplicationMessage {
request_id,
body: ReplicationMessageBody::PaidNotify(notify),
};
let Ok(encoded) = msg.encode() else {
warn!("Failed to encode PaidNotify for {}", hex::encode(key));
return;
};
let encoded = Bytes::from(encoded);
for node in &paid_group {
if node.peer_id == self_id {
continue;
}
let p2p = Arc::clone(p2p_node);
let data = encoded.clone();
let peer_id = node.peer_id;
tokio::spawn(async move {
if let Err(e) = p2p
.send_message(&peer_id, REPLICATION_PROTOCOL_ID, data, &[])
.await
{
debug!("Failed to send PaidNotify to {peer_id}: {e}");
}
});
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
#[test]
fn the_pending_offer_permit_outlives_every_handle() {
let permits = Arc::new(Semaphore::new(1));
let permit = Arc::clone(&permits)
.try_acquire_owned()
.expect("free permit");
let offer = Bytes::from_owner(EncodedOffer {
bytes: vec![7; 16],
_pending: permit,
});
let held_elsewhere = offer.slice(4..8);
drop(offer);
assert_eq!(permits.available_permits(), 0);
drop(held_elsewhere);
assert_eq!(permits.available_permits(), 1);
}
}