use crate::constants::BodyFormat;
use crate::error::RepeError;
use serde::Serialize;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::future::Future;
use std::hash::Hash;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PeerId(pub u64);
impl PeerId {
pub const DETACHED: PeerId = PeerId(u64::MAX);
}
impl std::fmt::Display for PeerId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, thiserror::Error)]
pub enum PeerSendError {
#[error("peer disconnected")]
Disconnected,
#[error("peer outbound queue full")]
Full,
#[error("peer send failed: {0}")]
Other(String),
}
#[derive(Debug, Clone)]
pub enum NotifyBody {
Beve(Vec<u8>),
Json(Vec<u8>),
Utf8(String),
Raw(Vec<u8>, BodyFormat),
}
impl NotifyBody {
pub fn body_format(&self) -> BodyFormat {
match self {
NotifyBody::Beve(_) => BodyFormat::Beve,
NotifyBody::Json(_) => BodyFormat::Json,
NotifyBody::Utf8(_) => BodyFormat::Utf8,
NotifyBody::Raw(_, fmt) => *fmt,
}
}
pub fn as_bytes(&self) -> &[u8] {
match self {
NotifyBody::Beve(bytes) | NotifyBody::Json(bytes) | NotifyBody::Raw(bytes, _) => bytes,
NotifyBody::Utf8(text) => text.as_bytes(),
}
}
pub fn into_bytes(self) -> Vec<u8> {
match self {
NotifyBody::Beve(bytes) | NotifyBody::Json(bytes) | NotifyBody::Raw(bytes, _) => bytes,
NotifyBody::Utf8(text) => text.into_bytes(),
}
}
}
fn notify_prefix_len(path: &str) -> usize {
crate::constants::HEADER_SIZE + path.len()
}
fn clone_with_prefix_room(src: &[u8], prefix_len: usize) -> Vec<u8> {
let mut buf = Vec::with_capacity(prefix_len + src.len());
buf.extend_from_slice(src);
buf
}
pub trait PeerSink: Send + Sync {
fn send_notify(&self, method: &str, body: NotifyBody) -> Result<(), PeerSendError>;
fn is_connected(&self) -> bool {
true
}
}
#[derive(Clone)]
pub struct PeerHandle {
peer_id: PeerId,
sink: Arc<dyn PeerSink>,
}
impl PeerHandle {
pub fn new(peer_id: PeerId, sink: Arc<dyn PeerSink>) -> Self {
Self { peer_id, sink }
}
pub fn peer_id(&self) -> PeerId {
self.peer_id
}
pub fn send_notify(&self, method: &str, body: NotifyBody) -> Result<(), PeerSendError> {
self.sink.send_notify(method, body)
}
pub fn is_connected(&self) -> bool {
self.sink.is_connected()
}
}
impl std::fmt::Debug for PeerHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PeerHandle")
.field("peer_id", &self.peer_id)
.finish()
}
}
pub(crate) trait CancelSignal: Send + Sync {
fn is_cancelled(&self) -> bool;
fn cancelled(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}
#[derive(Clone, Copy)]
pub struct CallContext<'a> {
method: &'a str,
peer: Option<&'a PeerHandle>,
cancel: Option<&'a dyn CancelSignal>,
}
impl<'a> CallContext<'a> {
pub fn new(method: &'a str, peer: &'a PeerHandle) -> Self {
Self {
method,
peer: Some(peer),
cancel: None,
}
}
pub fn detached(method: &'a str) -> Self {
Self {
method,
peer: None,
cancel: None,
}
}
#[cfg_attr(not(feature = "websocket"), allow(dead_code))]
pub(crate) fn with_cancel(
method: &'a str,
peer: &'a PeerHandle,
cancel: &'a dyn CancelSignal,
) -> Self {
Self {
method,
peer: Some(peer),
cancel: Some(cancel),
}
}
pub fn method(&self) -> &'a str {
self.method
}
pub fn peer(&self) -> Option<&'a PeerHandle> {
self.peer
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_some_and(|c| c.is_cancelled())
}
pub fn cancelled(&self) -> impl Future<Output = ()> + Send + 'a {
let cancel = self.cancel;
async move {
match cancel {
Some(c) => c.cancelled().await,
None => std::future::pending::<()>().await,
}
}
}
}
impl std::fmt::Debug for CallContext<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CallContext")
.field("method", &self.method)
.field("peer", &self.peer)
.field("cancellable", &self.cancel.is_some())
.finish()
}
}
#[derive(Clone)]
pub struct PeerRegistry {
inner: Arc<Mutex<RegistryInner>>,
next_id: Arc<AtomicU64>,
}
#[derive(Default)]
struct RegistryInner {
peers: HashMap<PeerId, PeerHandle>,
aliases: HashMap<String, PeerId>,
alias_index: HashMap<PeerId, Vec<String>>,
}
impl Default for PeerRegistry {
fn default() -> Self {
Self::new()
}
}
impl PeerRegistry {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(RegistryInner::default())),
next_id: Arc::new(AtomicU64::new(0)),
}
}
pub fn next_peer_id(&self) -> PeerId {
let value = self.next_id.fetch_add(1, Ordering::Relaxed);
debug_assert!(
value != PeerId::DETACHED.0,
"PeerRegistry id counter collided with PeerId::DETACHED sentinel \
(this requires ~2^64 connections; debug-only tripwire, not a contract)"
);
PeerId(value)
}
#[cfg(all(feature = "websocket", not(target_arch = "wasm32")))]
pub(crate) fn id_counter(&self) -> Arc<AtomicU64> {
Arc::clone(&self.next_id)
}
pub fn len(&self) -> usize {
self.lock().peers.len()
}
pub fn is_empty(&self) -> bool {
self.lock().peers.is_empty()
}
pub fn peers(&self) -> Vec<PeerHandle> {
self.lock().peers.values().cloned().collect()
}
pub fn get(&self, id: PeerId) -> Option<PeerHandle> {
self.lock().peers.get(&id).cloned()
}
pub fn alias<K: Into<String>>(&self, peer_id: PeerId, key: K) -> bool {
let key = key.into();
let mut guard = self.lock();
let inner: &mut RegistryInner = &mut guard;
if !inner.peers.contains_key(&peer_id) {
return false;
}
match inner.aliases.insert(key.clone(), peer_id) {
Some(prev) if prev == peer_id => return true,
Some(prev) => {
if let Some(keys) = inner.alias_index.get_mut(&prev) {
keys.retain(|k| k != &key);
}
}
None => {}
}
inner.alias_index.entry(peer_id).or_default().push(key);
true
}
pub fn get_by<Q>(&self, key: &Q) -> Option<PeerHandle>
where
String: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let guard = self.lock();
let id = *guard.aliases.get(key)?;
guard.peers.get(&id).cloned()
}
pub fn key_for(&self, peer_id: PeerId) -> Option<String> {
self.lock()
.alias_index
.get(&peer_id)
.and_then(|keys| keys.first().cloned())
}
pub fn aliases_for(&self, peer_id: PeerId) -> Vec<String> {
self.lock()
.alias_index
.get(&peer_id)
.cloned()
.unwrap_or_default()
}
pub fn insert(&self, peer: PeerHandle) {
let prev = self.lock().peers.insert(peer.peer_id(), peer);
debug_assert!(
prev.is_none(),
"PeerRegistry::insert overwrote an existing peer; \
two PeerHandles minted the same PeerId. If you wired multiple \
WebSocketServers to one PeerRegistry without using with_peer_registry, \
share PeerRegistry::next_peer_id across them."
);
}
pub fn remove(&self, id: PeerId) -> Option<PeerHandle> {
let mut guard = self.lock();
let inner: &mut RegistryInner = &mut guard;
let removed = inner.peers.remove(&id);
if let Some(keys) = inner.alias_index.remove(&id) {
for key in keys {
if inner.aliases.get(&key) == Some(&id) {
inner.aliases.remove(&key);
}
}
}
removed
}
pub fn broadcast_notify_json<P, T>(
&self,
path: P,
body: &T,
) -> Result<HashMap<PeerId, Result<(), PeerSendError>>, RepeError>
where
P: AsRef<str>,
T: Serialize + ?Sized,
{
let encoded = serde_json::to_vec(body)?;
Ok(self.broadcast_each(path.as_ref(), |_peer, prefix_room| {
NotifyBody::Json(clone_with_prefix_room(&encoded, prefix_room))
}))
}
pub fn broadcast_notify_beve<P, T>(
&self,
path: P,
body: &T,
) -> Result<HashMap<PeerId, Result<(), PeerSendError>>, RepeError>
where
P: AsRef<str>,
T: Serialize,
{
let encoded = beve::to_vec(body)?;
Ok(self.broadcast_each(path.as_ref(), |_peer, prefix_room| {
NotifyBody::Beve(clone_with_prefix_room(&encoded, prefix_room))
}))
}
pub fn broadcast_notify_utf8<P, S>(
&self,
path: P,
text: S,
) -> HashMap<PeerId, Result<(), PeerSendError>>
where
P: AsRef<str>,
S: AsRef<str>,
{
let text = text.as_ref();
self.broadcast_each(path.as_ref(), |_peer, prefix_room| {
let mut buf = String::with_capacity(prefix_room + text.len());
buf.push_str(text);
NotifyBody::Utf8(buf)
})
}
pub fn broadcast_notify_raw<P>(
&self,
path: P,
body_format: BodyFormat,
body: &[u8],
) -> HashMap<PeerId, Result<(), PeerSendError>>
where
P: AsRef<str>,
{
self.broadcast_each(path.as_ref(), |_peer, prefix_room| {
NotifyBody::Raw(clone_with_prefix_room(body, prefix_room), body_format)
})
}
fn broadcast_each<F>(
&self,
path: &str,
mut body_for: F,
) -> HashMap<PeerId, Result<(), PeerSendError>>
where
F: FnMut(&PeerHandle, usize) -> NotifyBody,
{
let prefix_room = notify_prefix_len(path);
let snapshot = self.peers();
let mut out = HashMap::with_capacity(snapshot.len());
for peer in snapshot {
let body = body_for(&peer, prefix_room);
let result = peer.send_notify(path, body);
out.insert(peer.peer_id(), result);
}
out
}
fn lock(&self) -> std::sync::MutexGuard<'_, RegistryInner> {
match self.inner.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
}
impl std::fmt::Debug for PeerRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PeerRegistry")
.field("len", &self.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct CapturingSink {
sent: Mutex<Vec<(String, Vec<u8>, BodyFormat)>>,
connected: bool,
}
impl PeerSink for CapturingSink {
fn send_notify(&self, method: &str, body: NotifyBody) -> Result<(), PeerSendError> {
if !self.connected {
return Err(PeerSendError::Disconnected);
}
let fmt = body.body_format();
self.sent
.lock()
.unwrap()
.push((method.to_string(), body.into_bytes(), fmt));
Ok(())
}
fn is_connected(&self) -> bool {
self.connected
}
}
#[test]
fn peer_handle_sends_through_sink() {
let sink = Arc::new(CapturingSink {
connected: true,
..Default::default()
});
let peer = PeerHandle::new(PeerId(7), sink.clone());
peer.send_notify("/x", NotifyBody::Beve(vec![1, 2, 3]))
.unwrap();
peer.send_notify("/y", NotifyBody::Utf8("hi".into()))
.unwrap();
let captured = sink.sent.lock().unwrap();
assert_eq!(captured.len(), 2);
assert_eq!(captured[0].0, "/x");
assert_eq!(captured[0].1, vec![1, 2, 3]);
assert_eq!(captured[0].2, BodyFormat::Beve);
assert_eq!(captured[1].0, "/y");
assert_eq!(captured[1].1, b"hi".to_vec());
assert_eq!(captured[1].2, BodyFormat::Utf8);
assert_eq!(peer.peer_id(), PeerId(7));
assert!(peer.is_connected());
}
#[test]
fn peer_handle_propagates_disconnect() {
let sink = Arc::new(CapturingSink::default());
let peer = PeerHandle::new(PeerId(1), sink);
let err = peer
.send_notify("/z", NotifyBody::Json(b"{}".to_vec()))
.unwrap_err();
assert!(matches!(err, PeerSendError::Disconnected));
assert!(!peer.is_connected());
}
#[test]
fn call_context_constructors() {
let sink = Arc::new(CapturingSink {
connected: true,
..Default::default()
});
let peer = PeerHandle::new(PeerId(2), sink);
let with = CallContext::new("/m", &peer);
assert_eq!(with.method(), "/m");
assert!(with.peer().is_some());
let without = CallContext::detached("/m");
assert_eq!(without.method(), "/m");
assert!(without.peer().is_none());
}
struct MockSignal(bool);
impl CancelSignal for MockSignal {
fn is_cancelled(&self) -> bool {
self.0
}
fn cancelled(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
if self.0 {
Box::pin(std::future::ready(()))
} else {
Box::pin(std::future::pending())
}
}
}
#[test]
fn call_context_cancellation_reflects_signal() {
let sink = Arc::new(CapturingSink {
connected: true,
..Default::default()
});
let peer = PeerHandle::new(PeerId(3), sink);
let cancelled = MockSignal(true);
let ctx = CallContext::with_cancel("/m", &peer, &cancelled);
assert!(ctx.is_cancelled());
assert!(ctx.peer().is_some());
let live = MockSignal(false);
let ctx = CallContext::with_cancel("/m", &peer, &live);
assert!(!ctx.is_cancelled());
}
#[test]
fn detached_and_plain_contexts_never_cancel() {
let sink = Arc::new(CapturingSink {
connected: true,
..Default::default()
});
let peer = PeerHandle::new(PeerId(4), sink);
assert!(!CallContext::detached("/m").is_cancelled());
assert!(!CallContext::new("/m", &peer).is_cancelled());
}
fn connected_peer(id: u64) -> PeerHandle {
PeerHandle::new(
PeerId(id),
Arc::new(CapturingSink {
connected: true,
..Default::default()
}),
)
}
#[test]
fn alias_then_get_by_resolves_to_the_peer() {
let registry = PeerRegistry::new();
let peer = connected_peer(1);
registry.insert(peer.clone());
assert!(registry.alias(peer.peer_id(), "session-abc"));
let found = registry.get_by("session-abc").expect("alias resolves");
assert_eq!(found.peer_id(), PeerId(1));
assert_eq!(registry.key_for(PeerId(1)).as_deref(), Some("session-abc"));
assert_eq!(registry.aliases_for(PeerId(1)), vec!["session-abc"]);
}
#[test]
fn alias_on_absent_peer_is_rejected() {
let registry = PeerRegistry::new();
assert!(!registry.alias(PeerId(7), "ghost"));
assert!(registry.get_by("ghost").is_none());
assert!(registry.key_for(PeerId(7)).is_none());
}
#[test]
fn get_by_missing_key_is_none() {
let registry = PeerRegistry::new();
registry.insert(connected_peer(1));
assert!(registry.get_by("nope").is_none());
}
#[test]
fn remove_purges_all_aliases() {
let registry = PeerRegistry::new();
let peer = connected_peer(1);
registry.insert(peer.clone());
registry.alias(peer.peer_id(), "user-1");
registry.alias(peer.peer_id(), "session-1");
assert_eq!(registry.aliases_for(PeerId(1)).len(), 2);
let removed = registry.remove(PeerId(1)).expect("peer was present");
assert_eq!(removed.peer_id(), PeerId(1));
assert!(registry.get_by("user-1").is_none());
assert!(registry.get_by("session-1").is_none());
assert!(registry.aliases_for(PeerId(1)).is_empty());
assert!(registry.key_for(PeerId(1)).is_none());
}
#[test]
fn multiple_aliases_address_one_peer() {
let registry = PeerRegistry::new();
let peer = connected_peer(5);
registry.insert(peer.clone());
registry.alias(peer.peer_id(), "u-5");
registry.alias(peer.peer_id(), "s-5");
assert_eq!(registry.get_by("u-5").unwrap().peer_id(), PeerId(5));
assert_eq!(registry.get_by("s-5").unwrap().peer_id(), PeerId(5));
assert_eq!(registry.aliases_for(PeerId(5)), vec!["u-5", "s-5"]);
}
#[test]
fn re_aliasing_a_key_moves_it_to_the_new_peer() {
let registry = PeerRegistry::new();
registry.insert(connected_peer(1));
registry.insert(connected_peer(2));
registry.alias(PeerId(1), "shared");
assert_eq!(registry.get_by("shared").unwrap().peer_id(), PeerId(1));
registry.alias(PeerId(2), "shared");
assert_eq!(registry.get_by("shared").unwrap().peer_id(), PeerId(2));
assert!(registry.aliases_for(PeerId(1)).is_empty());
assert_eq!(registry.aliases_for(PeerId(2)), vec!["shared"]);
registry.remove(PeerId(1));
assert_eq!(registry.get_by("shared").unwrap().peer_id(), PeerId(2));
}
#[test]
fn re_aliasing_same_peer_is_idempotent() {
let registry = PeerRegistry::new();
registry.insert(connected_peer(1));
assert!(registry.alias(PeerId(1), "k"));
assert!(registry.alias(PeerId(1), "k"));
assert_eq!(registry.aliases_for(PeerId(1)), vec!["k"]);
}
#[test]
fn aliases_let_broadcast_results_map_back_to_keys() {
let registry = PeerRegistry::new();
registry.insert(connected_peer(1));
registry.insert(connected_peer(2));
registry.alias(PeerId(1), "alice");
registry.alias(PeerId(2), "bob");
let results = registry.broadcast_notify_utf8("/ping", "hi");
let keyed: std::collections::HashMap<String, _> = results
.into_iter()
.filter_map(|(id, r)| registry.key_for(id).map(|k| (k, r)))
.collect();
assert!(keyed.contains_key("alice"));
assert!(keyed.contains_key("bob"));
}
#[test]
fn broadcast_bodies_carry_room_for_the_wire_prefix() {
let sink = Arc::new(CapturingSink {
connected: true,
..Default::default()
});
let registry = PeerRegistry::new();
registry.insert(PeerHandle::new(PeerId(1), sink.clone()));
let path = "/broadcast/prefix_room";
registry
.broadcast_notify_json(path, &serde_json::json!({ "n": 1 }))
.unwrap();
registry
.broadcast_notify_beve(path, &vec![1u8, 2, 3])
.unwrap();
registry.broadcast_notify_utf8(path, "hello");
registry.broadcast_notify_raw(path, BodyFormat::RawBinary, &[9u8; 64]);
let captured = sink.sent.lock().unwrap();
assert_eq!(captured.len(), 4);
let prefix = notify_prefix_len(path);
for (method, body, fmt) in captured.iter() {
assert_eq!(method, path);
assert!(!body.is_empty());
assert!(
body.capacity() >= prefix + body.len(),
"{fmt:?} body of {} bytes has capacity {}, short of the {prefix}-byte prefix",
body.len(),
body.capacity(),
);
}
}
#[test]
fn broadcast_prefix_room_matches_the_framed_prefix() {
let path = "/broadcast/prefix_room";
let body = vec![7u8; 32];
let msg = crate::Message::builder()
.id(0)
.notify(true)
.query_str(path)
.query_format(crate::constants::QueryFormat::JsonPointer)
.body_bytes(body.clone())
.body_format(BodyFormat::RawBinary)
.build();
let framed = msg.into_wire_bytes();
assert_eq!(framed.len() - body.len(), notify_prefix_len(path));
}
}