use std::time::{SystemTime, UNIX_EPOCH};
use iceoryx2::prelude::ZeroCopySend;
use iceoryx2_bb_container::string::StaticString;
use super::context::TraceContext;
use crate::labels::impl_labels;
use crate::types::consts::{METHOD_NAME_LEN, PROTOCOL_VERSION};
pub const CORRELATION_ID_LEN: usize = 16;
#[inline]
pub fn now_ns() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EventKind {
#[default]
Request = 0,
Next = 1,
Complete = 2,
Error = 3,
RpcError = 4,
Cancel = 5,
}
impl EventKind {
#[inline]
pub fn is_terminal(self) -> bool {
matches!(
self,
EventKind::Complete | EventKind::Error | EventKind::RpcError
)
}
#[inline]
pub const fn as_u8(self) -> u8 {
self as u8
}
#[inline]
pub const fn from_u8(value: u8) -> Self {
match value {
0 => EventKind::Request,
1 => EventKind::Next,
2 => EventKind::Complete,
3 => EventKind::Error,
4 => EventKind::RpcError,
5 => EventKind::Cancel,
_ => EventKind::Error,
}
}
}
impl_labels!(EventKind {
EventKind::Request => "request",
EventKind::Next => "next",
EventKind::Complete => "complete",
EventKind::Error => "error",
EventKind::RpcError => "rpc-error",
EventKind::Cancel => "cancel",
});
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, ZeroCopySend)]
pub struct RpcHeader {
pub correlation_id: [u8; CORRELATION_ID_LEN],
pub timestamp_ns: u64,
pub seq: u64,
pub trace_id: [u8; 16],
pub parent_span_id: u64,
pub service_id: u32,
pub method_name: StaticString<METHOD_NAME_LEN>,
pub event_kind: u8,
pub protocol_version: u16,
pub service_version: u16,
pub flags: u8,
}
impl RpcHeader {
#[inline]
pub fn request(method: &str, service_id: u32, service_version: u16) -> Self {
Self {
correlation_id: next_correlation_id(),
service_id,
method_name: StaticString::try_from(method).unwrap_or_default(),
event_kind: EventKind::Request.as_u8(),
protocol_version: PROTOCOL_VERSION,
service_version,
trace_id: [0u8; 16],
parent_span_id: 0,
flags: 0,
seq: 0,
timestamp_ns: now_ns(),
}
}
#[inline]
pub fn with_trace(mut self, trace: TraceContext) -> Self {
self.trace_id = trace.trace_id;
self.parent_span_id = trace.parent_span_id;
self.flags = trace.flags;
self
}
#[inline]
pub fn trace(&self) -> TraceContext {
TraceContext {
trace_id: self.trace_id,
parent_span_id: self.parent_span_id,
flags: self.flags,
}
}
#[inline]
pub fn with_seq(mut self, seq: u64) -> Self {
self.seq = seq;
self
}
#[inline]
pub fn response_from(request: &RpcHeader, event_kind: EventKind, service_version: u16) -> Self {
Self {
correlation_id: request.correlation_id,
service_id: request.service_id,
method_name: StaticString::default(),
event_kind: event_kind.as_u8(),
protocol_version: PROTOCOL_VERSION,
service_version,
trace_id: request.trace_id,
parent_span_id: request.parent_span_id,
flags: request.flags,
seq: 0,
timestamp_ns: now_ns(),
}
}
#[inline]
pub fn cancel_from(request: &RpcHeader) -> Self {
Self {
correlation_id: request.correlation_id,
service_id: request.service_id,
method_name: StaticString::default(),
event_kind: EventKind::Cancel.as_u8(),
protocol_version: PROTOCOL_VERSION,
service_version: request.service_version,
trace_id: request.trace_id,
parent_span_id: request.parent_span_id,
flags: request.flags,
seq: 0,
timestamp_ns: now_ns(),
}
}
#[inline]
pub fn method(&self) -> &str {
std::str::from_utf8(self.method_name.as_bytes_const()).unwrap_or("")
}
#[inline]
pub fn event_kind(&self) -> EventKind {
EventKind::from_u8(self.event_kind)
}
}
#[inline]
pub const fn service_id_of(name: &str) -> u32 {
const OFFSET_BASIS: u32 = 0x811c_9dc5;
const PRIME: u32 = 0x0100_0193;
let bytes = name.as_bytes();
let mut hash = OFFSET_BASIS;
let mut i = 0;
while i < bytes.len() {
hash ^= bytes[i] as u32;
hash = hash.wrapping_mul(PRIME);
i += 1;
}
hash
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ServiceRef {
pub id: u32,
pub version: u16,
}
impl ServiceRef {
#[inline]
pub const fn new(id: u32, version: u16) -> Self {
Self { id, version }
}
}
#[inline]
pub fn next_correlation_id() -> [u8; CORRELATION_ID_LEN] {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
let pid = std::process::id() as u64;
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let mut out = [0u8; CORRELATION_ID_LEN];
out[..8].copy_from_slice(&pid.to_be_bytes());
out[8..].copy_from_slice(&counter.to_be_bytes());
out
}
pub fn fmt_correlation_id(cid: &[u8; CORRELATION_ID_LEN]) -> String {
let [b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15] = cid;
format!(
"{b0:02x}{b1:02x}{b2:02x}{b3:02x}-{b4:02x}{b5:02x}-{b6:02x}{b7:02x}-\
{b8:02x}{b9:02x}-{b10:02x}{b11:02x}{b12:02x}{b13:02x}{b14:02x}{b15:02x}"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn request_header_carries_the_method_and_a_fresh_id() {
let id = service_id_of("DatabaseService");
let a = RpcHeader::request("get_user_age", id, 2);
let b = RpcHeader::request("get_user_age", id, 2);
assert_eq!(a.method(), "get_user_age");
assert_eq!(a.event_kind(), EventKind::Request);
assert_eq!(a.service_id, id);
assert_eq!(a.service_version, 2);
assert_ne!(a.correlation_id, b.correlation_id);
}
#[test]
fn response_header_reuses_the_request_id_and_service() {
let id = service_id_of("GetPerson");
let request = RpcHeader::request("ping", id, 1);
let response = RpcHeader::response_from(&request, EventKind::Complete, 1);
assert_eq!(response.correlation_id, request.correlation_id);
assert_eq!(response.service_id, id);
assert_eq!(response.event_kind(), EventKind::Complete);
assert!(response.method().is_empty());
}
#[test]
fn a_name_longer_than_the_capacity_falls_back_to_empty() {
let long = "x".repeat(METHOD_NAME_LEN + 20);
let header = RpcHeader::request(&long, 0, 1);
assert!(header.method().is_empty());
}
#[test]
fn service_id_is_stable_and_distinguishes_names() {
assert_eq!(service_id_of(""), 0x811c_9dc5);
const ID: u32 = service_id_of("DatabaseService");
assert_eq!(ID, service_id_of("DatabaseService"));
assert_ne!(
service_id_of("DatabaseService"),
service_id_of("ConfigService")
);
}
#[test]
fn the_header_layout_stays_bounded_and_aligned() {
assert_eq!(std::mem::align_of::<RpcHeader>(), 8);
assert_eq!(std::mem::size_of::<RpcHeader>(), 120);
assert_eq!(std::mem::offset_of!(RpcHeader, correlation_id), 0);
assert_eq!(std::mem::offset_of!(RpcHeader, timestamp_ns), 16);
assert_eq!(std::mem::offset_of!(RpcHeader, seq), 24);
assert_eq!(std::mem::offset_of!(RpcHeader, trace_id), 32);
assert_eq!(std::mem::offset_of!(RpcHeader, parent_span_id), 48);
assert_eq!(std::mem::offset_of!(RpcHeader, service_id), 56);
assert_eq!(std::mem::offset_of!(RpcHeader, method_name), 64);
assert_eq!(std::mem::offset_of!(RpcHeader, event_kind), 112);
assert_eq!(std::mem::offset_of!(RpcHeader, protocol_version), 114);
assert_eq!(std::mem::offset_of!(RpcHeader, service_version), 116);
assert_eq!(std::mem::offset_of!(RpcHeader, flags), 118);
}
#[test]
fn the_trace_context_travels_with_the_header() {
let trace = TraceContext {
trace_id: [7u8; 16],
parent_span_id: 42,
flags: 1,
};
let request = RpcHeader::request("ping", service_id_of("Ping"), 1).with_trace(trace);
assert_eq!(request.trace(), trace);
assert!(request.trace().is_present());
assert!(request.trace().is_sampled());
let response = RpcHeader::response_from(&request, EventKind::Complete, 1);
assert_eq!(response.trace(), trace, "the response echoes the trace");
}
#[test]
fn a_request_without_trace_carries_zeros() {
let request = RpcHeader::request("ping", service_id_of("Ping"), 1);
assert!(!request.trace().is_present());
assert_eq!(request.trace().parent_span_id, 0);
}
#[test]
fn request_stamps_a_timestamp() {
let id = service_id_of("Ping");
let before = now_ns();
let header = RpcHeader::request("ping", id, 1);
let after = now_ns();
assert!(header.timestamp_ns >= before);
assert!(header.timestamp_ns <= after);
assert_eq!(header.seq, 0);
assert_eq!(header.with_seq(7).seq, 7);
}
#[test]
fn response_stamps_its_own_emission_time() {
let request = RpcHeader::request("ping", service_id_of("Ping"), 1);
let response = RpcHeader::response_from(&request, EventKind::Complete, 1);
assert_eq!(response.correlation_id, request.correlation_id);
assert!(response.timestamp_ns >= request.timestamp_ns);
assert_eq!(response.with_seq(3).seq, 3);
}
#[test]
fn fmt_correlation_id_is_uuid_shaped() {
let cid = [
0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
0x66, 0x77,
];
assert_eq!(
fmt_correlation_id(&cid),
"deadbeef-cafe-babe-0011-223344556677"
);
}
#[test]
fn an_unknown_event_kind_decodes_as_error_not_complete() {
for value in 6u8..=u8::MAX {
assert_eq!(
EventKind::from_u8(value),
EventKind::Error,
"the unknown kind {value} must not read as a successful completion"
);
}
for kind in [
EventKind::Request,
EventKind::Next,
EventKind::Complete,
EventKind::Error,
EventKind::RpcError,
EventKind::Cancel,
] {
assert_eq!(EventKind::from_u8(kind.as_u8()), kind);
}
}
#[test]
fn a_cancel_is_not_terminal_and_has_its_own_label() {
assert!(!EventKind::Cancel.is_terminal());
assert_eq!(EventKind::Cancel.label(), "cancel");
assert_eq!(EventKind::from_u8(5), EventKind::Cancel);
}
#[test]
fn cancel_header_reuses_the_request_identity_without_a_method() {
let id = service_id_of("GetPerson");
let request = RpcHeader::request("get_person", id, 3).with_trace(TraceContext::new_root());
let cancel = RpcHeader::cancel_from(&request);
assert_eq!(cancel.correlation_id, request.correlation_id);
assert_eq!(cancel.service_id, id);
assert_eq!(cancel.service_version, 3);
assert_eq!(cancel.event_kind(), EventKind::Cancel);
assert!(cancel.method().is_empty(), "a Cancel names no method");
assert_eq!(cancel.trace(), request.trace(), "the Cancel stays traced");
assert_eq!(cancel.seq, 0);
assert_eq!(cancel.with_seq(9).seq, 9);
assert!(cancel.timestamp_ns >= request.timestamp_ns);
}
}