Security audit findings NET-01 (partial) and Codex #9 ("unauthenticated hints can make the victim pull arbitrary known peers"). Inbound QUIC connections are intentionally anonymous: only the responder is authenticated, so any LAN host can open a stream and send `LibraryChanged`/`CallToPlayChanged` hints naming any `claimed_peer_id`. If the claimed peer was known and the forged session or revision did not match the cached snapshot, state sync scheduled a full pinned Hello pull to that peer. Sending one small forged hint to every node on the LAN therefore made all of them pull a victim's complete snapshot at once (reflected amplification), bounded only by the 5-second per-peer coalesce window. Full mutual TLS would bind hints to a verified identity but is a larger protocol change than this application warrants. Instead the hint now carries the source IP of the anonymous connection, and `hint_requires_pull_from_snapshot` discards any hint whose source IP differs from the address at which the claimed peer was last authenticated. On a LAN a QUIC connection cannot be established from a spoofed IP, so a third host can no longer select which peer this node pulls. A genuine peer whose address changed loses only the hint fast path; mDNS rediscovery and pinned liveness reconciliation still pick it up. `PeerEndpointGeneration::for_tests` is added under cfg(test) so unit tests can build a `PeerRevisionSnapshot`. Test plan: `just test`. The new test accepts a hint from the peer's address, rejects the same hint from another IP or with no address, and keeps the revision comparison for matching sources. Manual: with two peer-cli containers, adding a game on one still triggers the other to refresh its library promptly. Claude-Session: https://claude.ai/code/session_017C3Nbgwpdm3YNwZhhFLHwg
1308 lines
43 KiB
Rust
1308 lines
43 KiB
Rust
//! Authenticated remote-peer endpoint and responder-owned state cache.
|
|
|
|
use std::{
|
|
collections::{HashMap, HashSet},
|
|
fmt,
|
|
net::SocketAddr,
|
|
sync::{Arc, Mutex, MutexGuard},
|
|
time::Duration,
|
|
};
|
|
|
|
use lanspread_db::content_manifest::ContentId;
|
|
pub use lanspread_proto::PeerId;
|
|
use lanspread_proto::{
|
|
GameAvailability,
|
|
LibrarySnapshot,
|
|
PeerEndpoint,
|
|
PeerRevisions,
|
|
RuntimeSessionId,
|
|
};
|
|
use tokio::time::Instant;
|
|
|
|
pub const MAX_AUTHENTICATED_PEERS: usize = 64;
|
|
|
|
/// Monotonic identity for one successfully authenticated endpoint observation.
|
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
|
pub struct PeerEndpointGeneration(u64);
|
|
|
|
impl PeerEndpointGeneration {
|
|
#[must_use]
|
|
pub const fn get(self) -> u64 {
|
|
self.0
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) const fn for_tests(value: u64) -> Self {
|
|
Self(value)
|
|
}
|
|
}
|
|
|
|
/// One endpoint generation retired by an authenticated topology transition.
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct RetiredPeerEndpoint {
|
|
pub endpoint: PeerEndpoint,
|
|
pub generation: PeerEndpointGeneration,
|
|
}
|
|
|
|
/// Immutable liveness probe target and the generation it may update.
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct PeerLivenessSnapshot {
|
|
pub endpoint: PeerEndpoint,
|
|
pub generation: PeerEndpointGeneration,
|
|
pub last_seen: Instant,
|
|
pub last_revision_check: Instant,
|
|
pub consecutive_ping_failures: u8,
|
|
}
|
|
|
|
/// Cached revision authority for one authenticated endpoint generation.
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct PeerRevisionSnapshot {
|
|
pub endpoint: PeerEndpoint,
|
|
pub generation: PeerEndpointGeneration,
|
|
pub runtime_session_id: RuntimeSessionId,
|
|
pub library_revision: Option<u64>,
|
|
pub call_to_play_revision: Option<u64>,
|
|
}
|
|
|
|
/// Opaque authority to commit one peer negotiation if it is still current.
|
|
pub struct PeerNegotiationTicket {
|
|
claim: PeerNegotiationClaim,
|
|
registry: Arc<Mutex<PeerNegotiationRegistry>>,
|
|
active: bool,
|
|
}
|
|
|
|
impl fmt::Debug for PeerNegotiationTicket {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
formatter
|
|
.debug_struct("PeerNegotiationTicket")
|
|
.field("endpoint", &self.claim.endpoint)
|
|
.field("active", &self.active)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl Drop for PeerNegotiationTicket {
|
|
fn drop(&mut self) {
|
|
if self.active {
|
|
lock_negotiation_registry(&self.registry).release_if_current(self.claim);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
|
struct PeerNegotiationTicketId(u64);
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
struct PeerNegotiationClaim {
|
|
endpoint: PeerEndpoint,
|
|
ticket_id: PeerNegotiationTicketId,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
struct PeerNegotiationRegistry {
|
|
latest_by_peer: HashMap<PeerId, PeerNegotiationClaim>,
|
|
latest_by_addr: HashMap<SocketAddr, PeerNegotiationClaim>,
|
|
/// Invalidated claims continue occupying their peer and address until the
|
|
/// owner releases the ticket, but can no longer commit responder state.
|
|
fenced: HashSet<PeerNegotiationTicketId>,
|
|
last_ticket: u64,
|
|
}
|
|
|
|
impl PeerNegotiationTicket {
|
|
fn new(claim: PeerNegotiationClaim, registry: Arc<Mutex<PeerNegotiationRegistry>>) -> Self {
|
|
Self {
|
|
claim,
|
|
registry,
|
|
active: true,
|
|
}
|
|
}
|
|
|
|
fn consume_if_current_and_valid(&mut self) -> bool {
|
|
if !self.active {
|
|
return false;
|
|
}
|
|
let released = lock_negotiation_registry(&self.registry).release_if_current(self.claim);
|
|
if released.is_some() {
|
|
self.active = false;
|
|
}
|
|
released == Some(true)
|
|
}
|
|
|
|
fn release_if_current(&mut self) -> bool {
|
|
if !self.active {
|
|
return false;
|
|
}
|
|
let released = lock_negotiation_registry(&self.registry).release_if_current(self.claim);
|
|
if released.is_some() {
|
|
self.active = false;
|
|
}
|
|
released.is_some()
|
|
}
|
|
|
|
/// Returns the generation a successful commit of this ticket will publish.
|
|
/// Wasted ticket values are intentional: domain preparation can therefore
|
|
/// finish before either state lock is acquired.
|
|
#[must_use]
|
|
pub(crate) const fn endpoint_generation(&self) -> PeerEndpointGeneration {
|
|
PeerEndpointGeneration(self.claim.ticket_id.0)
|
|
}
|
|
}
|
|
|
|
impl PeerNegotiationRegistry {
|
|
fn reserve_candidate(&mut self, endpoint: PeerEndpoint) -> eyre::Result<PeerNegotiationClaim> {
|
|
if self.latest_by_peer.contains_key(&endpoint.peer_id)
|
|
|| self.latest_by_addr.contains_key(&endpoint.addr)
|
|
{
|
|
eyre::bail!("peer or address already has an in-flight authenticated negotiation");
|
|
}
|
|
self.reserve(endpoint)
|
|
}
|
|
|
|
fn reserve_refresh(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
) -> eyre::Result<Option<PeerNegotiationClaim>> {
|
|
if self.latest_by_peer.contains_key(&endpoint.peer_id)
|
|
|| self.latest_by_addr.contains_key(&endpoint.addr)
|
|
{
|
|
return Ok(None);
|
|
}
|
|
self.reserve(endpoint).map(Some)
|
|
}
|
|
|
|
fn reserve(&mut self, endpoint: PeerEndpoint) -> eyre::Result<PeerNegotiationClaim> {
|
|
let ticket_value = self
|
|
.last_ticket
|
|
.checked_add(1)
|
|
.ok_or_else(|| eyre::eyre!("peer negotiation ticket exhausted"))?;
|
|
let claim = PeerNegotiationClaim {
|
|
endpoint,
|
|
ticket_id: PeerNegotiationTicketId(ticket_value),
|
|
};
|
|
|
|
debug_assert!(!self.latest_by_peer.contains_key(&endpoint.peer_id));
|
|
debug_assert!(!self.latest_by_addr.contains_key(&endpoint.addr));
|
|
|
|
self.last_ticket = ticket_value;
|
|
self.latest_by_peer.insert(endpoint.peer_id, claim);
|
|
self.latest_by_addr.insert(endpoint.addr, claim);
|
|
Ok(claim)
|
|
}
|
|
|
|
/// Releases physical occupancy and reports whether the claim retained
|
|
/// commit authority. `None` means a non-current/foreign ticket.
|
|
fn release_if_current(&mut self, claim: PeerNegotiationClaim) -> Option<bool> {
|
|
if self.latest_by_peer.get(&claim.endpoint.peer_id) != Some(&claim)
|
|
|| self.latest_by_addr.get(&claim.endpoint.addr) != Some(&claim)
|
|
{
|
|
return None;
|
|
}
|
|
self.latest_by_peer.remove(&claim.endpoint.peer_id);
|
|
self.latest_by_addr.remove(&claim.endpoint.addr);
|
|
Some(!self.fenced.remove(&claim.ticket_id))
|
|
}
|
|
|
|
fn fence_peer_or_addr(&mut self, endpoint: PeerEndpoint) {
|
|
if let Some(claim) = self.latest_by_peer.get(&endpoint.peer_id) {
|
|
self.fenced.insert(claim.ticket_id);
|
|
}
|
|
if let Some(claim) = self.latest_by_addr.get(&endpoint.addr) {
|
|
self.fenced.insert(claim.ticket_id);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn lock_negotiation_registry(
|
|
registry: &Mutex<PeerNegotiationRegistry>,
|
|
) -> MutexGuard<'_, PeerNegotiationRegistry> {
|
|
registry
|
|
.lock()
|
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
}
|
|
|
|
/// Information cached only after a pinned responder exchange.
|
|
#[derive(Clone, Debug)]
|
|
pub struct PeerInfo {
|
|
pub peer_id: PeerId,
|
|
pub addr: SocketAddr,
|
|
pub endpoint_generation: PeerEndpointGeneration,
|
|
pub last_seen: Instant,
|
|
pub last_revision_check: Instant,
|
|
consecutive_ping_failures: u8,
|
|
pub runtime_session_id: RuntimeSessionId,
|
|
pub library_revision: Option<u64>,
|
|
pub call_to_play_revision: Option<u64>,
|
|
pub games: HashMap<String, ContentId>,
|
|
}
|
|
|
|
/// Immutable peer state suitable for CLI assertions and diagnostics.
|
|
#[derive(Clone, Debug)]
|
|
pub struct PeerSnapshot {
|
|
pub peer_id: PeerId,
|
|
pub addr: SocketAddr,
|
|
pub endpoint_generation: PeerEndpointGeneration,
|
|
pub runtime_session_id: RuntimeSessionId,
|
|
pub library_revision: Option<u64>,
|
|
pub call_to_play_revision: Option<u64>,
|
|
pub game_count: usize,
|
|
pub games: Vec<GameAvailability>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct PeerGameDB {
|
|
peers: HashMap<PeerId, PeerInfo>,
|
|
addr_index: HashMap<SocketAddr, PeerId>,
|
|
negotiation_registry: Arc<Mutex<PeerNegotiationRegistry>>,
|
|
}
|
|
|
|
#[allow(clippy::struct_excessive_bools)]
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub struct PeerUpsert {
|
|
pub is_new: bool,
|
|
pub addr_changed: bool,
|
|
pub endpoint_generation: PeerEndpointGeneration,
|
|
pub previous_endpoint: Option<PeerEndpoint>,
|
|
pub evicted_endpoint: Option<RetiredPeerEndpoint>,
|
|
pub session_changed: bool,
|
|
pub library_changed: bool,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub enum PongObservation {
|
|
StaleGeneration,
|
|
Current,
|
|
RevisionMismatch,
|
|
NewSession,
|
|
}
|
|
|
|
/// Result of reserving a refresh for one captured authenticated generation.
|
|
#[derive(Debug)]
|
|
pub(crate) enum RefreshReservation {
|
|
Reserved(PeerNegotiationTicket),
|
|
/// Another physical negotiation owns the peer or address claim. The
|
|
/// scheduler retains one bounded/coalesced retry for this case.
|
|
DeferredByCandidate,
|
|
Stale,
|
|
}
|
|
|
|
impl Default for PeerGameDB {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl PeerGameDB {
|
|
#[must_use]
|
|
pub fn new() -> Self {
|
|
Self {
|
|
peers: HashMap::new(),
|
|
addr_index: HashMap::new(),
|
|
negotiation_registry: Arc::new(Mutex::new(PeerNegotiationRegistry::default())),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn negotiation_claim_counts(&self) -> (usize, usize) {
|
|
let registry = lock_negotiation_registry(&self.negotiation_registry);
|
|
(registry.latest_by_peer.len(), registry.latest_by_addr.len())
|
|
}
|
|
|
|
pub fn begin_candidate_negotiation(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
) -> eyre::Result<PeerNegotiationTicket> {
|
|
let claim =
|
|
lock_negotiation_registry(&self.negotiation_registry).reserve_candidate(endpoint)?;
|
|
Ok(PeerNegotiationTicket::new(
|
|
claim,
|
|
Arc::clone(&self.negotiation_registry),
|
|
))
|
|
}
|
|
|
|
pub(crate) fn begin_peer_refresh(
|
|
&mut self,
|
|
snapshot: PeerLivenessSnapshot,
|
|
) -> eyre::Result<RefreshReservation> {
|
|
let Some(peer) = self.peers.get(&snapshot.endpoint.peer_id) else {
|
|
return Ok(RefreshReservation::Stale);
|
|
};
|
|
if peer.addr != snapshot.endpoint.addr || peer.endpoint_generation != snapshot.generation {
|
|
return Ok(RefreshReservation::Stale);
|
|
}
|
|
let claim = lock_negotiation_registry(&self.negotiation_registry)
|
|
.reserve_refresh(snapshot.endpoint)?;
|
|
Ok(
|
|
claim.map_or(RefreshReservation::DeferredByCandidate, |claim| {
|
|
RefreshReservation::Reserved(PeerNegotiationTicket::new(
|
|
claim,
|
|
Arc::clone(&self.negotiation_registry),
|
|
))
|
|
}),
|
|
)
|
|
}
|
|
|
|
/// Commits one independently validated responder snapshot.
|
|
#[allow(clippy::needless_pass_by_value, clippy::too_many_lines)]
|
|
pub fn commit_authenticated_snapshot(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
mut ticket: PeerNegotiationTicket,
|
|
runtime_session_id: RuntimeSessionId,
|
|
library: Option<LibrarySnapshot>,
|
|
) -> eyre::Result<Option<PeerUpsert>> {
|
|
let endpoint_generation = ticket.endpoint_generation();
|
|
if endpoint != ticket.claim.endpoint
|
|
|| !Arc::ptr_eq(&self.negotiation_registry, &ticket.registry)
|
|
|| !ticket.consume_if_current_and_valid()
|
|
{
|
|
return Ok(None);
|
|
}
|
|
|
|
let existing_at_addr = self.addr_index.get(&endpoint.addr).copied();
|
|
let is_new = !self.peers.contains_key(&endpoint.peer_id);
|
|
let makes_room = existing_at_addr.is_some_and(|id| id != endpoint.peer_id);
|
|
if is_new && self.peers.len() >= MAX_AUTHENTICATED_PEERS && !makes_room {
|
|
eyre::bail!("authenticated peer limit of {MAX_AUTHENTICATED_PEERS} reached");
|
|
}
|
|
|
|
let PeerEndpoint { peer_id, addr } = endpoint;
|
|
let now = Instant::now();
|
|
|
|
let evicted_endpoint = existing_at_addr
|
|
.filter(|existing_id| *existing_id != peer_id)
|
|
.and_then(|existing_id| {
|
|
self.addr_index.remove(&addr);
|
|
self.peers
|
|
.remove(&existing_id)
|
|
.map(|evicted| RetiredPeerEndpoint {
|
|
endpoint: PeerEndpoint::new(evicted.peer_id, evicted.addr),
|
|
generation: evicted.endpoint_generation,
|
|
})
|
|
});
|
|
|
|
let incoming_library = library
|
|
.as_ref()
|
|
.map(|snapshot| (snapshot.revision, library_map(snapshot)));
|
|
if let Some(peer) = self.peers.get_mut(&peer_id) {
|
|
let previous_endpoint =
|
|
(peer.addr != addr).then(|| PeerEndpoint::new(peer.peer_id, peer.addr));
|
|
let addr_changed = previous_endpoint.is_some();
|
|
if addr_changed {
|
|
self.addr_index.remove(&peer.addr);
|
|
self.addr_index.insert(addr, peer_id);
|
|
peer.addr = addr;
|
|
}
|
|
|
|
let session_changed = peer.runtime_session_id != runtime_session_id;
|
|
let library_changed = match incoming_library {
|
|
Some((revision, games))
|
|
if session_changed
|
|
|| peer
|
|
.library_revision
|
|
.is_none_or(|current| revision > current) =>
|
|
{
|
|
let changed = peer.library_revision != Some(revision) || peer.games != games;
|
|
peer.library_revision = Some(revision);
|
|
peer.games = games;
|
|
changed
|
|
}
|
|
None if session_changed => {
|
|
let changed = peer.library_revision.is_some() || !peer.games.is_empty();
|
|
peer.library_revision = None;
|
|
peer.games.clear();
|
|
changed
|
|
}
|
|
Some(_) | None => false,
|
|
};
|
|
|
|
peer.endpoint_generation = endpoint_generation;
|
|
peer.last_seen = now;
|
|
peer.last_revision_check = now;
|
|
peer.consecutive_ping_failures = 0;
|
|
peer.runtime_session_id = runtime_session_id;
|
|
if session_changed {
|
|
peer.call_to_play_revision = None;
|
|
}
|
|
return Ok(Some(PeerUpsert {
|
|
is_new: false,
|
|
addr_changed,
|
|
endpoint_generation,
|
|
previous_endpoint,
|
|
evicted_endpoint,
|
|
session_changed,
|
|
library_changed,
|
|
}));
|
|
}
|
|
|
|
self.peers.insert(
|
|
peer_id,
|
|
PeerInfo {
|
|
peer_id,
|
|
addr,
|
|
endpoint_generation,
|
|
last_seen: now,
|
|
last_revision_check: now,
|
|
consecutive_ping_failures: 0,
|
|
runtime_session_id,
|
|
library_revision: incoming_library.as_ref().map(|(revision, _)| *revision),
|
|
call_to_play_revision: None,
|
|
games: incoming_library.map_or_else(HashMap::new, |(_, games)| games),
|
|
},
|
|
);
|
|
self.addr_index.insert(addr, peer_id);
|
|
Ok(Some(PeerUpsert {
|
|
is_new: true,
|
|
addr_changed: false,
|
|
endpoint_generation,
|
|
previous_endpoint: None,
|
|
evicted_endpoint,
|
|
session_changed: true,
|
|
library_changed: true,
|
|
}))
|
|
}
|
|
|
|
pub fn abandon_peer_negotiation(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
mut ticket: PeerNegotiationTicket,
|
|
) -> bool {
|
|
endpoint == ticket.claim.endpoint
|
|
&& Arc::ptr_eq(&self.negotiation_registry, &ticket.registry)
|
|
&& ticket.release_if_current()
|
|
}
|
|
|
|
/// Stamps a pinned Pong and clears previous-session state before a pull.
|
|
pub fn observe_pong_if_generation(
|
|
&mut self,
|
|
snapshot: PeerLivenessSnapshot,
|
|
revisions: PeerRevisions,
|
|
) -> PongObservation {
|
|
let Some(peer) = self.peers.get_mut(&snapshot.endpoint.peer_id) else {
|
|
return PongObservation::StaleGeneration;
|
|
};
|
|
if peer.addr != snapshot.endpoint.addr || peer.endpoint_generation != snapshot.generation {
|
|
return PongObservation::StaleGeneration;
|
|
}
|
|
|
|
let now = Instant::now();
|
|
peer.last_seen = now;
|
|
peer.last_revision_check = now;
|
|
peer.consecutive_ping_failures = 0;
|
|
if peer.runtime_session_id != revisions.runtime_session_id {
|
|
peer.runtime_session_id = revisions.runtime_session_id;
|
|
peer.library_revision = None;
|
|
peer.call_to_play_revision = None;
|
|
peer.games.clear();
|
|
lock_negotiation_registry(&self.negotiation_registry)
|
|
.fence_peer_or_addr(snapshot.endpoint);
|
|
return PongObservation::NewSession;
|
|
}
|
|
if peer.library_revision != Some(revisions.library_revision)
|
|
|| peer.call_to_play_revision != Some(revisions.call_to_play_revision)
|
|
{
|
|
PongObservation::RevisionMismatch
|
|
} else {
|
|
PongObservation::Current
|
|
}
|
|
}
|
|
|
|
pub fn set_call_to_play_revision_if_generation(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
generation: PeerEndpointGeneration,
|
|
revision: Option<u64>,
|
|
) -> bool {
|
|
let Some(peer) = self.peers.get_mut(&endpoint.peer_id) else {
|
|
return false;
|
|
};
|
|
if peer.addr != endpoint.addr || peer.endpoint_generation != generation {
|
|
return false;
|
|
}
|
|
peer.call_to_play_revision = revision;
|
|
true
|
|
}
|
|
|
|
/// Records a failed pinned Ping without refreshing either liveness clock.
|
|
/// A generation mismatch is a strict no-op.
|
|
pub fn record_ping_failure_if_generation(&mut self, snapshot: PeerLivenessSnapshot) -> bool {
|
|
let Some(peer) = self.peers.get_mut(&snapshot.endpoint.peer_id) else {
|
|
return false;
|
|
};
|
|
if peer.addr != snapshot.endpoint.addr || peer.endpoint_generation != snapshot.generation {
|
|
return false;
|
|
}
|
|
peer.consecutive_ping_failures = peer.consecutive_ping_failures.saturating_add(1);
|
|
true
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn revision_snapshot(&self, peer_id: &PeerId) -> Option<PeerRevisionSnapshot> {
|
|
self.peers.get(peer_id).map(|peer| PeerRevisionSnapshot {
|
|
endpoint: PeerEndpoint::new(peer.peer_id, peer.addr),
|
|
generation: peer.endpoint_generation,
|
|
runtime_session_id: peer.runtime_session_id,
|
|
library_revision: peer.library_revision,
|
|
call_to_play_revision: peer.call_to_play_revision,
|
|
})
|
|
}
|
|
|
|
pub fn remove_peer(&mut self, peer_id: &PeerId) -> Option<PeerInfo> {
|
|
let peer = self.peers.remove(peer_id)?;
|
|
self.addr_index.remove(&peer.addr);
|
|
lock_negotiation_registry(&self.negotiation_registry)
|
|
.fence_peer_or_addr(PeerEndpoint::new(peer.peer_id, peer.addr));
|
|
Some(peer)
|
|
}
|
|
|
|
pub fn remove_peer_if_generation(
|
|
&mut self,
|
|
endpoint: PeerEndpoint,
|
|
generation: PeerEndpointGeneration,
|
|
) -> Option<PeerInfo> {
|
|
let peer = self.peers.get(&endpoint.peer_id)?;
|
|
if peer.addr != endpoint.addr || peer.endpoint_generation != generation {
|
|
return None;
|
|
}
|
|
self.remove_peer(&endpoint.peer_id)
|
|
}
|
|
|
|
/// Retires every authenticated remote peer and invalidates every
|
|
/// outstanding negotiation ticket.
|
|
///
|
|
/// The fresh registry retains the monotonic ticket counter so a later
|
|
/// endpoint generation cannot repeat one issued before the clear. Replacing
|
|
/// the registry [`Arc`] also makes every old ticket fail pointer-identity
|
|
/// validation without allowing its eventual release to affect new claims.
|
|
#[must_use]
|
|
pub fn clear_remote_peers(&mut self) -> Vec<RetiredPeerEndpoint> {
|
|
let last_ticket = lock_negotiation_registry(&self.negotiation_registry).last_ticket;
|
|
self.negotiation_registry = Arc::new(Mutex::new(PeerNegotiationRegistry {
|
|
last_ticket,
|
|
..PeerNegotiationRegistry::default()
|
|
}));
|
|
|
|
self.addr_index.clear();
|
|
let mut retired = self
|
|
.peers
|
|
.drain()
|
|
.map(|(_, peer)| RetiredPeerEndpoint {
|
|
endpoint: PeerEndpoint::new(peer.peer_id, peer.addr),
|
|
generation: peer.endpoint_generation,
|
|
})
|
|
.collect::<Vec<_>>();
|
|
retired.sort_by_key(|peer| peer.endpoint.peer_id);
|
|
retired
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_endpoint(&self, peer_id: &PeerId) -> Option<PeerEndpoint> {
|
|
self.peers
|
|
.get(peer_id)
|
|
.map(|peer| PeerEndpoint::new(peer.peer_id, peer.addr))
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_endpoints(&self) -> Vec<PeerEndpoint> {
|
|
self.peers
|
|
.values()
|
|
.map(|peer| PeerEndpoint::new(peer.peer_id, peer.addr))
|
|
.collect()
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_liveness_snapshot(&self) -> Vec<PeerLivenessSnapshot> {
|
|
self.peers.values().map(peer_liveness_snapshot).collect()
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_liveness_for(&self, peer_id: &PeerId) -> Option<PeerLivenessSnapshot> {
|
|
self.peers.get(peer_id).map(peer_liveness_snapshot)
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_snapshots(&self) -> Vec<PeerSnapshot> {
|
|
let mut peers = self
|
|
.peers
|
|
.values()
|
|
.map(|peer| {
|
|
let mut games = peer
|
|
.games
|
|
.iter()
|
|
.map(|(game_id, content_id)| GameAvailability {
|
|
game_id: game_id.clone(),
|
|
content_id: *content_id,
|
|
})
|
|
.collect::<Vec<_>>();
|
|
games.sort_by(|left, right| left.game_id.cmp(&right.game_id));
|
|
PeerSnapshot {
|
|
peer_id: peer.peer_id,
|
|
addr: peer.addr,
|
|
endpoint_generation: peer.endpoint_generation,
|
|
runtime_session_id: peer.runtime_session_id,
|
|
library_revision: peer.library_revision,
|
|
call_to_play_revision: peer.call_to_play_revision,
|
|
game_count: games.len(),
|
|
games,
|
|
}
|
|
})
|
|
.collect::<Vec<_>>();
|
|
peers.sort_by_key(|peer| peer.peer_id);
|
|
peers
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn contains_peer(&self, peer_id: &PeerId) -> bool {
|
|
self.peers.contains_key(peer_id)
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_endpoints_with_content(
|
|
&self,
|
|
game_id: &str,
|
|
content_id: ContentId,
|
|
) -> Vec<PeerEndpoint> {
|
|
let mut endpoints = self
|
|
.peers
|
|
.values()
|
|
.filter(|peer| peer.games.get(game_id) == Some(&content_id))
|
|
.map(|peer| PeerEndpoint::new(peer.peer_id, peer.addr))
|
|
.collect::<Vec<_>>();
|
|
endpoints.sort_by_key(|endpoint| endpoint.peer_id);
|
|
endpoints
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn peer_count_for_content(&self, game_id: &str, content_id: ContentId) -> u32 {
|
|
u32::try_from(
|
|
self.peers
|
|
.values()
|
|
.filter(|peer| peer.games.get(game_id) == Some(&content_id))
|
|
.count(),
|
|
)
|
|
.unwrap_or(u32::MAX)
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn stale_peer_liveness_snapshots(&self, timeout: Duration) -> Vec<PeerLivenessSnapshot> {
|
|
self.peers
|
|
.values()
|
|
.filter(|peer| {
|
|
peer.consecutive_ping_failures >= 2 && peer.last_seen.elapsed() > timeout
|
|
})
|
|
.map(peer_liveness_snapshot)
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
fn library_map(snapshot: &LibrarySnapshot) -> HashMap<String, ContentId> {
|
|
snapshot
|
|
.games
|
|
.iter()
|
|
.map(|game| (game.game_id.clone(), game.content_id))
|
|
.collect()
|
|
}
|
|
|
|
fn peer_liveness_snapshot(peer: &PeerInfo) -> PeerLivenessSnapshot {
|
|
PeerLivenessSnapshot {
|
|
endpoint: PeerEndpoint::new(peer.peer_id, peer.addr),
|
|
generation: peer.endpoint_generation,
|
|
last_seen: peer.last_seen,
|
|
last_revision_check: peer.last_revision_check,
|
|
consecutive_ping_failures: peer.consecutive_ping_failures,
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn addr(port: u16) -> SocketAddr {
|
|
SocketAddr::from(([127, 0, 0, 1], port))
|
|
}
|
|
|
|
fn peer_id(seed: u8) -> PeerId {
|
|
PeerId::from_bytes([seed; 32])
|
|
}
|
|
|
|
fn endpoint(seed: u8, port: u16) -> PeerEndpoint {
|
|
PeerEndpoint::new(peer_id(seed), addr(port))
|
|
}
|
|
|
|
fn session(seed: u8) -> RuntimeSessionId {
|
|
RuntimeSessionId::from_bytes([seed; 16])
|
|
}
|
|
|
|
fn library(revision: u64, game: Option<(&str, u8)>) -> LibrarySnapshot {
|
|
LibrarySnapshot {
|
|
revision,
|
|
games: game
|
|
.into_iter()
|
|
.map(|(game_id, seed)| GameAvailability {
|
|
game_id: game_id.to_owned(),
|
|
content_id: ContentId::from_bytes([seed; 32]),
|
|
})
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
fn commit(
|
|
db: &mut PeerGameDB,
|
|
endpoint: PeerEndpoint,
|
|
runtime_session_id: RuntimeSessionId,
|
|
library: LibrarySnapshot,
|
|
ctp_revision: Option<u64>,
|
|
) -> PeerUpsert {
|
|
let ticket = db
|
|
.begin_candidate_negotiation(endpoint)
|
|
.expect("candidate should reserve");
|
|
let upsert = db
|
|
.commit_authenticated_snapshot(endpoint, ticket, runtime_session_id, Some(library))
|
|
.expect("snapshot commit should not fail")
|
|
.expect("ticket should be current");
|
|
assert!(db.set_call_to_play_revision_if_generation(
|
|
endpoint,
|
|
upsert.endpoint_generation,
|
|
ctp_revision,
|
|
));
|
|
upsert
|
|
}
|
|
|
|
#[test]
|
|
fn reconnect_gets_new_generation_and_stale_removal_loses_authority() {
|
|
let endpoint = endpoint(1, 12001);
|
|
let mut db = PeerGameDB::new();
|
|
let first = commit(&mut db, endpoint, session(1), library(0, None), Some(0));
|
|
let stale = db
|
|
.peer_liveness_for(&endpoint.peer_id)
|
|
.expect("peer should exist");
|
|
let second = commit(&mut db, endpoint, session(1), library(0, None), Some(0));
|
|
|
|
assert!(second.endpoint_generation.get() > first.endpoint_generation.get());
|
|
assert!(
|
|
db.remove_peer_if_generation(stale.endpoint, stale.generation)
|
|
.is_none()
|
|
);
|
|
assert_eq!(db.peer_endpoint(&endpoint.peer_id), Some(endpoint));
|
|
}
|
|
|
|
#[test]
|
|
fn clear_remote_peers_returns_peer_id_sorted_retirements() {
|
|
let mut db = PeerGameDB::new();
|
|
let third_endpoint = endpoint(23, 12123);
|
|
let first_endpoint = endpoint(21, 12121);
|
|
let second_endpoint = endpoint(22, 12122);
|
|
let third = commit(
|
|
&mut db,
|
|
third_endpoint,
|
|
session(23),
|
|
library(0, None),
|
|
Some(0),
|
|
);
|
|
let first = commit(
|
|
&mut db,
|
|
first_endpoint,
|
|
session(21),
|
|
library(0, None),
|
|
Some(0),
|
|
);
|
|
let second = commit(
|
|
&mut db,
|
|
second_endpoint,
|
|
session(22),
|
|
library(0, None),
|
|
Some(0),
|
|
);
|
|
|
|
assert_eq!(
|
|
db.clear_remote_peers(),
|
|
vec![
|
|
RetiredPeerEndpoint {
|
|
endpoint: first_endpoint,
|
|
generation: first.endpoint_generation,
|
|
},
|
|
RetiredPeerEndpoint {
|
|
endpoint: second_endpoint,
|
|
generation: second.endpoint_generation,
|
|
},
|
|
RetiredPeerEndpoint {
|
|
endpoint: third_endpoint,
|
|
generation: third.endpoint_generation,
|
|
},
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn clear_remote_peers_empties_peer_state_and_address_index() {
|
|
let mut db = PeerGameDB::new();
|
|
let first = endpoint(24, 12124);
|
|
let second = endpoint(25, 12125);
|
|
commit(&mut db, first, session(24), library(0, None), Some(0));
|
|
commit(&mut db, second, session(25), library(0, None), Some(0));
|
|
|
|
assert_eq!(db.clear_remote_peers().len(), 2);
|
|
assert!(db.peers.is_empty());
|
|
assert!(db.addr_index.is_empty());
|
|
assert!(db.peer_endpoints().is_empty());
|
|
assert_eq!(db.peer_endpoint(&first.peer_id), None);
|
|
assert_eq!(db.peer_endpoint(&second.peer_id), None);
|
|
assert_eq!(db.negotiation_claim_counts(), (0, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn clear_remote_peers_invalidates_ticket_reserved_before_clear() {
|
|
let stale_endpoint = endpoint(26, 12126);
|
|
let mut db = PeerGameDB::new();
|
|
let stale_ticket = db
|
|
.begin_candidate_negotiation(stale_endpoint)
|
|
.expect("stale candidate should reserve");
|
|
|
|
assert!(db.clear_remote_peers().is_empty());
|
|
assert!(
|
|
db.commit_authenticated_snapshot(
|
|
stale_endpoint,
|
|
stale_ticket,
|
|
session(26),
|
|
Some(library(0, None)),
|
|
)
|
|
.expect("stale commit check should work")
|
|
.is_none()
|
|
);
|
|
assert!(!db.contains_peer(&stale_endpoint.peer_id));
|
|
assert_eq!(db.negotiation_claim_counts(), (0, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn clear_remote_peers_isolates_held_old_ticket_occupancy() {
|
|
let shared_endpoint = endpoint(27, 12127);
|
|
let mut db = PeerGameDB::new();
|
|
let old_ticket = db
|
|
.begin_candidate_negotiation(shared_endpoint)
|
|
.expect("old candidate should reserve");
|
|
|
|
assert!(db.clear_remote_peers().is_empty());
|
|
let fresh_ticket = db
|
|
.begin_candidate_negotiation(shared_endpoint)
|
|
.expect("old registry occupancy must not block the fresh registry");
|
|
assert_eq!(db.negotiation_claim_counts(), (1, 1));
|
|
|
|
drop(old_ticket);
|
|
assert_eq!(
|
|
db.negotiation_claim_counts(),
|
|
(1, 1),
|
|
"releasing an old ticket must not release a fresh claim"
|
|
);
|
|
assert!(
|
|
db.commit_authenticated_snapshot(
|
|
shared_endpoint,
|
|
fresh_ticket,
|
|
session(27),
|
|
Some(library(0, None)),
|
|
)
|
|
.expect("fresh commit should work")
|
|
.is_some()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn clear_remote_peers_keeps_next_generation_strictly_monotonic() {
|
|
let first_endpoint = endpoint(28, 12128);
|
|
let wasted_endpoint = endpoint(29, 12129);
|
|
let fresh_endpoint = endpoint(30, 12130);
|
|
let mut db = PeerGameDB::new();
|
|
let first = commit(
|
|
&mut db,
|
|
first_endpoint,
|
|
session(28),
|
|
library(0, None),
|
|
Some(0),
|
|
);
|
|
let wasted_ticket = db
|
|
.begin_candidate_negotiation(wasted_endpoint)
|
|
.expect("pre-clear candidate should reserve");
|
|
let highest_pre_clear_generation = wasted_ticket.endpoint_generation();
|
|
assert!(highest_pre_clear_generation.get() > first.endpoint_generation.get());
|
|
|
|
assert_eq!(db.clear_remote_peers().len(), 1);
|
|
let fresh_ticket = db
|
|
.begin_candidate_negotiation(fresh_endpoint)
|
|
.expect("post-clear candidate should reserve");
|
|
assert!(
|
|
fresh_ticket.endpoint_generation().get() > highest_pre_clear_generation.get(),
|
|
"the fresh registry must continue after every issued ticket"
|
|
);
|
|
|
|
drop(wasted_ticket);
|
|
assert!(
|
|
db.commit_authenticated_snapshot(
|
|
fresh_endpoint,
|
|
fresh_ticket,
|
|
session(30),
|
|
Some(library(0, None)),
|
|
)
|
|
.expect("fresh commit should work")
|
|
.is_some()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn one_candidate_per_peer_is_physically_in_flight() {
|
|
let old = endpoint(2, 12002);
|
|
let new = endpoint(2, 12003);
|
|
let mut db = PeerGameDB::new();
|
|
let old_ticket = db
|
|
.begin_candidate_negotiation(old)
|
|
.expect("old candidate should reserve");
|
|
assert!(db.begin_candidate_negotiation(new).is_err());
|
|
assert_eq!(db.negotiation_claim_counts(), (1, 1));
|
|
drop(old_ticket);
|
|
let new_ticket = db
|
|
.begin_candidate_negotiation(new)
|
|
.expect("new candidate should reserve after release");
|
|
assert!(
|
|
db.commit_authenticated_snapshot(new, new_ticket, session(2), Some(library(0, None)),)
|
|
.expect("new commit should work")
|
|
.is_some()
|
|
);
|
|
assert_eq!(db.peer_endpoint(&new.peer_id), Some(new));
|
|
assert_eq!(db.negotiation_claim_counts(), (0, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn reserved_refresh_blocks_overlapping_candidate_until_release() {
|
|
let owner = endpoint(3, 12004);
|
|
let replacement = endpoint(4, 12004);
|
|
let mut db = PeerGameDB::new();
|
|
commit(&mut db, owner, session(3), library(0, None), Some(0));
|
|
let liveness = db
|
|
.peer_liveness_for(&owner.peer_id)
|
|
.expect("owner should exist");
|
|
let RefreshReservation::Reserved(refresh) = db
|
|
.begin_peer_refresh(liveness)
|
|
.expect("refresh check should work")
|
|
else {
|
|
panic!("refresh should reserve");
|
|
};
|
|
assert!(db.begin_candidate_negotiation(replacement).is_err());
|
|
drop(refresh);
|
|
let candidate = db
|
|
.begin_candidate_negotiation(replacement)
|
|
.expect("candidate should reserve after refresh release");
|
|
let upsert = db
|
|
.commit_authenticated_snapshot(
|
|
replacement,
|
|
candidate,
|
|
session(4),
|
|
Some(library(0, None)),
|
|
)
|
|
.expect("replacement should commit")
|
|
.expect("replacement should be current");
|
|
assert_eq!(
|
|
upsert.evicted_endpoint.map(|evicted| evicted.endpoint),
|
|
Some(owner)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn candidate_owned_address_defers_refresh_until_candidate_releases() {
|
|
let known = endpoint(30, 12030);
|
|
let forged = endpoint(31, 12030);
|
|
let mut db = PeerGameDB::new();
|
|
commit(&mut db, known, session(30), library(0, None), Some(0));
|
|
let liveness = db
|
|
.peer_liveness_for(&known.peer_id)
|
|
.expect("known peer should exist");
|
|
let candidate = db
|
|
.begin_candidate_negotiation(forged)
|
|
.expect("candidate should reserve the address");
|
|
|
|
assert!(matches!(
|
|
db.begin_peer_refresh(liveness)
|
|
.expect("refresh decision should work"),
|
|
RefreshReservation::DeferredByCandidate
|
|
));
|
|
assert!(matches!(
|
|
db.begin_peer_refresh(liveness)
|
|
.expect("repeated refresh decision should work"),
|
|
RefreshReservation::DeferredByCandidate
|
|
));
|
|
assert_eq!(db.negotiation_claim_counts(), (1, 1));
|
|
|
|
drop(candidate);
|
|
assert!(matches!(
|
|
db.begin_peer_refresh(liveness)
|
|
.expect("released candidate should unblock refresh"),
|
|
RefreshReservation::Reserved(_)
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn same_session_accepts_higher_library_and_preserves_lower_or_conflicting_equal() {
|
|
let endpoint = endpoint(5, 12005);
|
|
let mut db = PeerGameDB::new();
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(5),
|
|
library(2, Some(("game", 1))),
|
|
Some(2),
|
|
);
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(5),
|
|
library(2, Some(("game", 9))),
|
|
Some(2),
|
|
);
|
|
assert_eq!(
|
|
db.peer_endpoints_with_content("game", ContentId::from_bytes([1; 32])),
|
|
[endpoint]
|
|
);
|
|
commit(&mut db, endpoint, session(5), library(1, None), Some(2));
|
|
assert_eq!(
|
|
db.peer_endpoints_with_content("game", ContentId::from_bytes([1; 32])),
|
|
[endpoint]
|
|
);
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(5),
|
|
library(3, Some(("game", 7))),
|
|
Some(3),
|
|
);
|
|
assert_eq!(
|
|
db.peer_endpoints_with_content("game", ContentId::from_bytes([7; 32])),
|
|
[endpoint]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn new_session_replaces_library_even_at_revision_zero() {
|
|
let endpoint = endpoint(6, 12006);
|
|
let mut db = PeerGameDB::new();
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(6),
|
|
library(8, Some(("old", 1))),
|
|
Some(8),
|
|
);
|
|
let upsert = commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(7),
|
|
library(0, Some(("new", 2))),
|
|
Some(0),
|
|
);
|
|
assert!(upsert.session_changed);
|
|
assert!(
|
|
db.peer_endpoints_with_content("old", ContentId::from_bytes([1; 32]))
|
|
.is_empty()
|
|
);
|
|
assert_eq!(
|
|
db.peer_endpoints_with_content("new", ContentId::from_bytes([2; 32])),
|
|
[endpoint]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn pong_new_session_clears_old_domains_before_pull() {
|
|
let endpoint = endpoint(7, 12007);
|
|
let mut db = PeerGameDB::new();
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(7),
|
|
library(4, Some(("old", 1))),
|
|
Some(4),
|
|
);
|
|
let probe = db
|
|
.peer_liveness_for(&endpoint.peer_id)
|
|
.expect("peer should exist");
|
|
|
|
assert_eq!(
|
|
db.observe_pong_if_generation(
|
|
probe,
|
|
PeerRevisions {
|
|
runtime_session_id: session(8),
|
|
library_revision: 0,
|
|
call_to_play_revision: 0,
|
|
},
|
|
),
|
|
PongObservation::NewSession
|
|
);
|
|
let cached = db
|
|
.revision_snapshot(&endpoint.peer_id)
|
|
.expect("peer should remain");
|
|
assert_eq!(cached.runtime_session_id, session(8));
|
|
assert_eq!(cached.library_revision, None);
|
|
assert_eq!(cached.call_to_play_revision, None);
|
|
assert!(
|
|
db.peer_endpoints_with_content("old", ContentId::from_bytes([1; 32]))
|
|
.is_empty()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn new_session_pong_fences_an_older_reserved_snapshot() {
|
|
let endpoint = endpoint(40, 12040);
|
|
let mut db = PeerGameDB::new();
|
|
commit(
|
|
&mut db,
|
|
endpoint,
|
|
session(40),
|
|
library(4, Some(("old", 1))),
|
|
Some(4),
|
|
);
|
|
let probe = db
|
|
.peer_liveness_for(&endpoint.peer_id)
|
|
.expect("peer should exist");
|
|
let RefreshReservation::Reserved(old_ticket) = db
|
|
.begin_peer_refresh(probe)
|
|
.expect("old refresh should reserve")
|
|
else {
|
|
panic!("old refresh should reserve");
|
|
};
|
|
|
|
assert_eq!(
|
|
db.observe_pong_if_generation(
|
|
probe,
|
|
PeerRevisions {
|
|
runtime_session_id: session(41),
|
|
library_revision: 0,
|
|
call_to_play_revision: 0,
|
|
},
|
|
),
|
|
PongObservation::NewSession
|
|
);
|
|
assert!(matches!(
|
|
db.begin_peer_refresh(probe)
|
|
.expect("fenced occupancy check should work"),
|
|
RefreshReservation::DeferredByCandidate
|
|
));
|
|
assert!(
|
|
db.begin_candidate_negotiation(endpoint).is_err(),
|
|
"a fenced ticket owner must retain physical peer/address occupancy"
|
|
);
|
|
assert!(
|
|
db.commit_authenticated_snapshot(
|
|
endpoint,
|
|
old_ticket,
|
|
session(40),
|
|
Some(library(5, Some(("resurrected", 2)))),
|
|
)
|
|
.expect("stale commit check should work")
|
|
.is_none()
|
|
);
|
|
assert_eq!(db.negotiation_claim_counts(), (0, 0));
|
|
assert!(matches!(
|
|
db.begin_peer_refresh(probe)
|
|
.expect("released stale ticket should unblock refresh"),
|
|
RefreshReservation::Reserved(_)
|
|
));
|
|
let cached = db
|
|
.revision_snapshot(&endpoint.peer_id)
|
|
.expect("peer should remain");
|
|
assert_eq!(cached.runtime_session_id, session(41));
|
|
assert_eq!(cached.library_revision, None);
|
|
assert!(
|
|
db.peer_endpoints_with_content("resurrected", ContentId::from_bytes([2; 32]))
|
|
.is_empty()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn generation_removal_fences_an_older_reserved_snapshot() {
|
|
let endpoint = endpoint(42, 12042);
|
|
let mut db = PeerGameDB::new();
|
|
commit(&mut db, endpoint, session(42), library(0, None), Some(0));
|
|
let probe = db
|
|
.peer_liveness_for(&endpoint.peer_id)
|
|
.expect("peer should exist");
|
|
let RefreshReservation::Reserved(old_ticket) = db
|
|
.begin_peer_refresh(probe)
|
|
.expect("old refresh should reserve")
|
|
else {
|
|
panic!("old refresh should reserve");
|
|
};
|
|
|
|
assert!(
|
|
db.remove_peer_if_generation(probe.endpoint, probe.generation)
|
|
.is_some()
|
|
);
|
|
assert!(
|
|
db.begin_candidate_negotiation(endpoint).is_err(),
|
|
"removal must fence commit without releasing physical occupancy"
|
|
);
|
|
assert!(
|
|
db.commit_authenticated_snapshot(
|
|
endpoint,
|
|
old_ticket,
|
|
session(42),
|
|
Some(library(1, Some(("resurrected", 3)))),
|
|
)
|
|
.expect("stale commit check should work")
|
|
.is_none()
|
|
);
|
|
assert!(db.peer_endpoint(&endpoint.peer_id).is_none());
|
|
assert_eq!(db.negotiation_claim_counts(), (0, 0));
|
|
let replacement = db
|
|
.begin_candidate_negotiation(endpoint)
|
|
.expect("released stale ticket should unblock a candidate");
|
|
drop(replacement);
|
|
}
|
|
|
|
#[test]
|
|
fn pong_stamps_only_its_current_generation() {
|
|
let endpoint = endpoint(8, 12008);
|
|
let mut db = PeerGameDB::new();
|
|
commit(&mut db, endpoint, session(8), library(0, None), Some(0));
|
|
let stale = db
|
|
.peer_liveness_for(&endpoint.peer_id)
|
|
.expect("peer should exist");
|
|
commit(&mut db, endpoint, session(8), library(0, None), Some(0));
|
|
|
|
assert_eq!(
|
|
db.observe_pong_if_generation(
|
|
stale,
|
|
PeerRevisions {
|
|
runtime_session_id: session(8),
|
|
library_revision: 0,
|
|
call_to_play_revision: 0,
|
|
},
|
|
),
|
|
PongObservation::StaleGeneration
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn exact_content_identity_selects_sources() {
|
|
let mut db = PeerGameDB::new();
|
|
let first = endpoint(9, 12009);
|
|
let second = endpoint(10, 12010);
|
|
commit(
|
|
&mut db,
|
|
first,
|
|
session(9),
|
|
library(1, Some(("game", 1))),
|
|
Some(0),
|
|
);
|
|
commit(
|
|
&mut db,
|
|
second,
|
|
session(10),
|
|
library(1, Some(("game", 2))),
|
|
Some(0),
|
|
);
|
|
|
|
assert_eq!(
|
|
db.peer_endpoints_with_content("game", ContentId::from_bytes([1; 32])),
|
|
[first]
|
|
);
|
|
assert_eq!(
|
|
db.peer_count_for_content("game", ContentId::from_bytes([2; 32])),
|
|
1
|
|
);
|
|
}
|
|
}
|