use crate::constants::BodyFormat;
use crate::error::RepeError;
use serde::Serialize;
use std::collections::HashMap;
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(),
}
}
}
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()
}
}
#[derive(Debug, Clone, Copy)]
pub struct CallContext<'a> {
method: &'a str,
peer: Option<&'a PeerHandle>,
}
impl<'a> CallContext<'a> {
pub fn new(method: &'a str, peer: &'a PeerHandle) -> Self {
Self {
method,
peer: Some(peer),
}
}
pub fn detached(method: &'a str) -> Self {
Self { method, peer: None }
}
pub fn method(&self) -> &'a str {
self.method
}
pub fn peer(&self) -> Option<&'a PeerHandle> {
self.peer
}
}
#[derive(Clone)]
pub struct PeerRegistry {
inner: Arc<Mutex<HashMap<PeerId, PeerHandle>>>,
next_id: Arc<AtomicU64>,
}
impl Default for PeerRegistry {
fn default() -> Self {
Self::new()
}
}
impl PeerRegistry {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(HashMap::new())),
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)
}
pub(crate) fn id_counter(&self) -> Arc<AtomicU64> {
Arc::clone(&self.next_id)
}
pub fn len(&self) -> usize {
self.lock().len()
}
pub fn is_empty(&self) -> bool {
self.lock().is_empty()
}
pub fn peers(&self) -> Vec<PeerHandle> {
self.lock().values().cloned().collect()
}
pub fn get(&self, id: PeerId) -> Option<PeerHandle> {
self.lock().get(&id).cloned()
}
pub fn insert(&self, peer: PeerHandle) {
let prev = self.lock().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> {
self.lock().remove(&id)
}
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| NotifyBody::Json(encoded.clone())))
}
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| NotifyBody::Beve(encoded.clone())))
}
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().to_owned();
self.broadcast_each(path.as_ref(), |_peer| NotifyBody::Utf8(text.clone()))
}
pub fn broadcast_notify_raw<P>(
&self,
path: P,
body_format: BodyFormat,
body: &[u8],
) -> HashMap<PeerId, Result<(), PeerSendError>>
where
P: AsRef<str>,
{
let bytes = body.to_vec();
self.broadcast_each(path.as_ref(), move |_peer| {
NotifyBody::Raw(bytes.clone(), body_format)
})
}
fn broadcast_each<F>(
&self,
path: &str,
mut body_for: F,
) -> HashMap<PeerId, Result<(), PeerSendError>>
where
F: FnMut(&PeerHandle) -> NotifyBody,
{
let snapshot = self.peers();
let mut out = HashMap::with_capacity(snapshot.len());
for peer in snapshot {
let body = body_for(&peer);
let result = peer.send_notify(path, body);
out.insert(peer.peer_id(), result);
}
out
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<PeerId, PeerHandle>> {
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());
}
}