use iceoryx2::prelude::*;
pub use iceoryx2_bb_container::string::StaticString;
use rkyv::{Archive, Deserialize, Serialize};
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ZeroCopySend, Default)]
pub struct NodeId(pub u32);
impl NodeId {
#[inline]
pub fn current() -> Self {
Self(std::process::id())
}
}
impl std::fmt::Display for NodeId {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "node-{}", self.0)
}
}
#[derive(Archive, Serialize, Deserialize, Debug, Clone)]
pub enum Event<T, E> {
Next(T),
Complete,
Error(E),
RpcError(RpcError),
}
pub type Observable<T, E> = Result<Stream<T, E>, RpcError>;
pub type Sender<T, E> = async_channel::Sender<Event<T, E>>;
pub type Stream<T, E> = async_channel::Receiver<Event<T, E>>;
pub fn channel<T, E>(capacity: usize) -> (Sender<T, E>, Stream<T, E>) {
async_channel::bounded(capacity)
}
pub const METHOD_NAME_LEN: usize = 64;
pub const SERVICE_NAME_LEN: usize = 64;
pub const PROTOCOL_VERSION: u16 = 1;
pub const LARGE_PAYLOAD_THRESHOLD: usize = 1024;
pub fn node_default_topic(node_id: NodeId) -> String {
format!("node_{}_default", node_id.0)
}
pub fn node_large_topic(node_id: NodeId) -> String {
format!("node_{}_large", node_id.0)
}
pub fn node_notify_topic(node_id: NodeId) -> String {
format!("node_{}_notify", node_id.0)
}
pub const RPC_CALL_TIMEOUT_SECS: u64 = 30;
pub const PUBLISHER_DEFAULT_MAX_SLICE_LEN: usize = 256;
pub const PUBLISHER_LARGE_MAX_SLICE_LEN: usize = 4096;
pub const WAITSET_TIMEOUT_US: u64 = 500;
pub const SERVER_READY_POLL_MS: u64 = 100;
pub const INIT_RETRY_INTERVAL_MS: u64 = 1_000;
pub const INITIALIZE_ALL_TIMEOUT_SECS: u16 = 30;
pub const BLACKBOARD_MAX_READERS: usize = 64;
pub const DEFAULT_TOPIC_BUFFER_SIZE: usize = 4096;
pub const LARGE_TOPIC_BUFFER_SIZE: usize = 4;
pub const MAX_SERVICES_PER_NODE: usize = 32;
pub const REGISTRY_SERVICE_NAME_LEN: usize = 64;
#[repr(C)]
#[derive(
Debug, Clone, Copy, PartialEq, Eq, ZeroCopySend, Default, Archive, Serialize, Deserialize,
)]
pub enum EventKind {
#[default]
Request = 0,
Next = 1,
Complete = 2,
Error = 3,
}
impl EventKind {
#[inline]
pub fn is_terminal(self) -> bool {
matches!(self, EventKind::Complete | EventKind::Error)
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, ZeroCopySend, Default)]
pub struct RpcHeader {
pub correlation_id: [u8; 16],
pub sent_at_ns: u64,
pub caller_pid: u32,
pub service_name: StaticString<SERVICE_NAME_LEN>,
pub method_name: StaticString<METHOD_NAME_LEN>,
pub event_kind: EventKind,
pub protocol_version: u16,
pub service_version: u16,
}
impl RpcHeader {
pub fn new(service: &str, method: &str) -> Self {
Self {
correlation_id: RpcHeader::next_correlation_id(),
sent_at_ns: RpcHeader::now_ns(),
caller_pid: std::process::id(),
service_name: StaticString::from_bytes_truncated(service.as_bytes())
.unwrap_or_default(),
method_name: StaticString::from_bytes_truncated(method.as_bytes()).unwrap_or_default(),
event_kind: EventKind::Request,
protocol_version: PROTOCOL_VERSION,
service_version: 0,
}
}
#[inline]
pub fn with_service_version(mut self, service_version: u16) -> Self {
self.service_version = service_version;
self
}
#[inline]
pub fn request(service: &str, method: &str, service_version: u16) -> Self {
Self::new(service, method).with_service_version(service_version)
}
#[inline]
pub fn response_from(request: &RpcHeader, event_kind: EventKind, service_version: u16) -> Self {
Self {
correlation_id: request.correlation_id,
sent_at_ns: RpcHeader::now_ns(),
caller_pid: std::process::id(),
service_name: request.service_name,
method_name: request.method_name,
event_kind,
protocol_version: PROTOCOL_VERSION,
service_version,
}
}
#[inline]
pub fn is_request(&self) -> bool {
self.event_kind == EventKind::Request
}
#[inline]
pub fn is_response(&self) -> bool {
self.event_kind != EventKind::Request
}
#[inline]
pub fn service(&self) -> &str {
core::str::from_utf8(self.service_name.as_bytes_const()).unwrap_or("")
}
pub fn next_correlation_id() -> [u8; 16] {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let mut id = [0u8; 16];
id[0..4].copy_from_slice(&pid.to_le_bytes());
id[4..12].copy_from_slice(&seq.to_le_bytes());
id
}
#[inline]
pub fn method(&self) -> &str {
core::str::from_utf8(self.method_name.as_bytes_const()).unwrap_or("")
}
pub fn now_ns() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
}
}
#[inline]
pub fn caller_pid_from_cid(cid: &[u8; 16]) -> u32 {
u32::from_le_bytes([cid[0], cid[1], cid[2], cid[3]])
}
pub fn fmt_correlation_id(cid: &[u8; 16]) -> String {
let [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15] = cid;
format!(
"{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15,
)
}
pub fn fmt_correlation_id_short(cid: &[u8; 16]) -> String {
format!("{:02x}{:02x}{:02x}{:02x}", cid[0], cid[1], cid[2], cid[3])
}
#[derive(Debug, Clone, Archive, Serialize, Deserialize, thiserror::Error)]
pub enum RpcError {
#[error("RPC error: serialization failure")]
SerializationError,
#[error("RPC transport error: {0}")]
TransportError(String),
#[error("RPC discovery error: {0}")]
DiscoveryError(String),
#[error("RPC service not found: {service}")]
ServiceNotFound { service: String },
#[error("RPC provider unavailable (node {node})")]
ProviderUnavailable { node: u32 },
#[error("RPC error: timeout exceeded")]
Timeout,
#[error("RPC error: call cancelled")]
Cancelled,
#[error("RPC payload too large: {size} bytes (limit {limit})")]
PayloadTooLarge { size: usize, limit: usize },
#[error(
"RPC protocol mismatch (protocol {received_protocol} != {expected_protocol}, service {received_service} != {expected_service})"
)]
ProtocolMismatch {
expected_protocol: u16,
received_protocol: u16,
expected_service: u16,
received_service: u16,
},
#[error("RPC internal error: {0}")]
Internal(String),
}
impl RpcError {
pub fn is_retryable(&self) -> bool {
matches!(
self,
RpcError::TransportError(_)
| RpcError::DiscoveryError(_)
| RpcError::ProviderUnavailable { .. }
| RpcError::Timeout
)
}
}
#[derive(Debug, thiserror::Error)]
pub enum TakeOneError<E: std::fmt::Display> {
#[error("IPC error: {0}")]
Ipc(RpcError),
#[error("Service error: {0}")]
Service(E),
#[error("Stream closed without a value")]
Empty,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn event_kind_request_is_not_terminal() {
assert!(!EventKind::Request.is_terminal());
}
#[test]
fn event_kind_next_is_not_terminal() {
assert!(!EventKind::Next.is_terminal());
}
#[test]
fn event_kind_complete_is_terminal() {
assert!(EventKind::Complete.is_terminal());
}
#[test]
fn event_kind_error_is_terminal() {
assert!(EventKind::Error.is_terminal());
}
#[test]
fn event_kind_default_is_request() {
assert_eq!(EventKind::default(), EventKind::Request);
}
#[test]
fn event_kind_discriminants() {
assert_eq!(EventKind::Request as u8, 0);
assert_eq!(EventKind::Next as u8, 1);
assert_eq!(EventKind::Complete as u8, 2);
assert_eq!(EventKind::Error as u8, 3);
}
#[test]
fn rpc_header_new_populates_correlation_id() {
let header = RpcHeader::new("test_svc", "test_method");
assert_ne!(header.correlation_id, [0u8; 16]);
}
#[test]
fn rpc_header_new_sets_service_and_method() {
let header = RpcHeader::new("MyService", "hello_world");
assert_eq!(header.service(), "MyService");
assert_eq!(header.method(), "hello_world");
}
#[test]
fn rpc_header_new_event_kind_is_request() {
let header = RpcHeader::new("any_svc", "any");
assert_eq!(header.event_kind, EventKind::Request);
}
#[test]
fn rpc_header_new_sets_protocol_version() {
let header = RpcHeader::new("svc", "m");
assert_eq!(header.protocol_version, PROTOCOL_VERSION);
assert_eq!(header.service_version, 0);
}
#[test]
fn rpc_header_with_service_version() {
let header = RpcHeader::new("svc", "m").with_service_version(7);
assert_eq!(header.service_version, 7);
}
#[test]
fn rpc_header_new_sent_at_ns_is_nonzero() {
let header = RpcHeader::new("svc", "test");
assert!(header.sent_at_ns > 0);
}
#[test]
fn next_correlation_id_is_unique() {
let id1 = RpcHeader::next_correlation_id();
let id2 = RpcHeader::next_correlation_id();
assert_ne!(id1, id2);
}
#[test]
fn next_correlation_id_pid_field() {
let id = RpcHeader::next_correlation_id();
let pid = u32::from_le_bytes([id[0], id[1], id[2], id[3]]);
assert_eq!(pid, std::process::id());
}
#[test]
fn rpc_header_method_empty_on_default() {
let header = RpcHeader::default();
assert!(header.method().is_empty());
}
#[test]
fn rpc_header_method_truncated_on_long_name() {
let long_name = "a".repeat(METHOD_NAME_LEN + 50);
let header = RpcHeader::new("svc", &long_name);
assert!(header.method().len() <= METHOD_NAME_LEN);
}
#[test]
fn now_ns_returns_reasonable_value() {
let ns = RpcHeader::now_ns();
assert!(ns > 1_500_000_000_000_000_000);
}
#[test]
fn now_ns_is_monotonic() {
let t1 = RpcHeader::now_ns();
let t2 = RpcHeader::now_ns();
assert!(t2 >= t1);
}
#[test]
fn fmt_correlation_id_format_length() {
let cid = [
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10,
];
let formatted = fmt_correlation_id(&cid);
assert_eq!(formatted.len(), 36);
}
#[test]
fn fmt_correlation_id_contains_dashes() {
let cid = [0xAA; 16];
let formatted = fmt_correlation_id(&cid);
assert!(formatted.contains('-'));
assert_eq!(formatted.matches('-').count(), 4);
}
#[test]
fn fmt_correlation_id_stable_output() {
let cid = [
0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
0x66, 0x77,
];
let expected = "deadbeef-cafe-babe-0011-223344556677";
assert_eq!(fmt_correlation_id(&cid), expected);
}
#[test]
fn fmt_correlation_id_short_length() {
let cid = [
0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
];
let formatted = fmt_correlation_id_short(&cid);
assert_eq!(formatted.len(), 8);
}
#[test]
fn fmt_correlation_id_short_first_four_bytes() {
let cid = [
0x12, 0x34, 0x56, 0x78, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF,
];
let formatted = fmt_correlation_id_short(&cid);
assert_eq!(formatted, "12345678");
}
#[test]
fn rpc_error_display_serialization_error() {
let err = RpcError::SerializationError;
assert!(err.to_string().contains("serialization"));
}
#[test]
fn rpc_error_display_transport_error() {
let err = RpcError::TransportError("connection refused".into());
assert!(err.to_string().contains("connection refused"));
}
#[test]
fn rpc_error_display_timeout() {
let err = RpcError::Timeout;
assert!(err.to_string().contains("timeout"));
}
#[test]
fn rpc_error_protocol_mismatch_display() {
let err = RpcError::ProtocolMismatch {
expected_protocol: 1,
received_protocol: 2,
expected_service: 3,
received_service: 4,
};
assert!(err.to_string().contains("protocol mismatch"));
}
#[test]
fn rpc_error_is_retryable_classification() {
assert!(RpcError::TransportError("boom".into()).is_retryable());
assert!(RpcError::DiscoveryError("boom".into()).is_retryable());
assert!(RpcError::ProviderUnavailable { node: 1 }.is_retryable());
assert!(RpcError::Timeout.is_retryable());
assert!(!RpcError::SerializationError.is_retryable());
assert!(!RpcError::ServiceNotFound {
service: "svc".into()
}
.is_retryable());
assert!(!RpcError::Cancelled.is_retryable());
assert!(!RpcError::PayloadTooLarge {
size: 1,
limit: 1
}
.is_retryable());
assert!(!RpcError::Internal("boom".into()).is_retryable());
}
#[test]
fn take_one_error_ipc_contains_message() {
let err = TakeOneError::<String>::Ipc(RpcError::Timeout);
assert!(err.to_string().contains("timeout"));
}
#[test]
fn take_one_error_service_contains_value() {
let err = TakeOneError::Service("not found".to_string());
assert!(err.to_string().contains("not found"));
}
#[test]
fn take_one_error_empty_message() {
let err = TakeOneError::<String>::Empty;
assert!(!err.to_string().is_empty());
}
}