use crate::constants::BodyFormat;
use std::sync::Arc;
#[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
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[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();
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());
}
}