use std::sync::Arc;
use iceoryx2::prelude::*;
use iceoryx2::service::ipc_threadsafe;
use crate::global::Global;
use crate::types::{RpcError, RpcHeader};
mod bridge;
mod client;
mod monitor;
mod notify;
mod open;
mod publish;
mod pump;
mod server;
mod tuning;
mod waitset;
pub use bridge::{
emit_rpc_error, observable_to_responses, BoxResponseFuture, CollectEmitter, OwnedEmitter,
ResponseEmitter, ServiceDispatcher,
};
pub use client::{native_call, serialize_and_call};
pub use monitor::{discover_channels, Direction, DirectionView, Emitter};
pub use server::{register_native_service, spawn_native_service, start_registered_channels};
use tuning::{
CONSUMER_WAIT_TIMEOUT, IDLE_SPINS, MAX_LOANED_SAMPLES, MAX_NODES, MAX_PUBLISHERS,
MAX_SLICE_LEN, MAX_SUBSCRIBERS, OPEN_RETRY_ATTEMPTS, OPEN_RETRY_SLEEP, PAYLOAD_ALIGNMENT,
PROVIDER_WAIT_DEFAULT, PUBLISH_RETRY_SLEEP, PUBLISH_SPIN_ATTEMPTS, REQUEST_NOTIFY_SUFFIX,
REQUEST_SUFFIX, RESPONSE_NOTIFY_SUFFIX, RESPONSE_SUFFIX, SIGNAL_CHECK_SAMPLES,
SUBSCRIBER_BUFFER, WAITSET_DEADLINE,
};
type Iox = ipc_threadsafe::Service;
type IoxNode = iceoryx2::node::Node<Iox>;
type IoxPubSub =
iceoryx2::service::port_factory::publish_subscribe::PortFactory<Iox, [u8], RpcHeader>;
type IoxEvent = iceoryx2::service::port_factory::event::PortFactory<Iox>;
type IoxPublisher = iceoryx2::port::publisher::Publisher<Iox, [u8], RpcHeader>;
type IoxSubscriber = iceoryx2::port::subscriber::Subscriber<Iox, [u8], RpcHeader>;
type IoxListener = iceoryx2::port::listener::Listener<Iox>;
type IoxNotifier = iceoryx2::port::notifier::Notifier<Iox>;
pub(super) fn transport_error(context: &str, err: impl std::fmt::Debug) -> RpcError {
RpcError::TransportError(format!("{context}: {err:?}"))
}
pub(super) fn shared_node() -> Result<Arc<IoxNode>, RpcError> {
static NODE: Global<Result<Arc<IoxNode>, String>> = Global::new();
NODE.get_or_init(|| {
NodeBuilder::new()
.create::<Iox>()
.map(Arc::new)
.map_err(|e| format!("{e:?}"))
})
.clone()
.map_err(|e| RpcError::TransportError(format!("node creation: {e}")))
}
pub fn release_process_ports() -> usize {
client::release_consumer_ports()
}
pub fn cleanup_dead_nodes() -> u64 {
let mut config = crate::config::build_iceoryx2_config();
config.global.node.cleanup_dead_nodes_on_creation = false;
let Ok(node) = iceoryx2::node::NodeBuilder::new()
.config(&config)
.create::<Iox>()
else {
return 0;
};
let state = node.try_cleanup_dead_nodes();
if state.failed_cleanups > 0 {
log::warn!(
"[ice-rpc] {} dead node(s) could not be reaped, {} reaped \
(insufficient permissions, or another process is on it)",
state.failed_cleanups,
state.cleanups
);
}
state.cleanups
}
pub fn sweep_orphan_shm_markers() -> usize {
use iceoryx2_bb_posix::shared_memory::SharedMemory;
let names = SharedMemory::list();
let before = names.len();
for name in &names {
let _ = SharedMemory::does_exist(name);
}
before.saturating_sub(SharedMemory::list().len())
}
pub fn decode_aligned<T>(bytes: &[u8]) -> Result<T, rkyv::rancor::Error>
where
T: rkyv::Archive,
<T as rkyv::Archive>::Archived:
rkyv::Deserialize<T, rkyv::rancor::Strategy<rkyv::de::Pool, rkyv::rancor::Error>>,
for<'a> <T as rkyv::Archive>::Archived:
rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'a, rkyv::rancor::Error>>,
{
if is_sample_aligned(bytes) {
return rkyv::from_bytes::<T, rkyv::rancor::Error>(bytes);
}
let mut aligned = rkyv::util::AlignedVec::<{ PAYLOAD_ALIGNMENT }>::with_capacity(bytes.len());
aligned.extend_from_slice(bytes);
rkyv::from_bytes::<T, rkyv::rancor::Error>(&aligned)
}
fn is_sample_aligned(bytes: &[u8]) -> bool {
(bytes.as_ptr() as usize).is_multiple_of(PAYLOAD_ALIGNMENT)
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug, PartialEq)]
struct Sample {
id: u32,
count: u64,
}
#[test]
fn decode_aligned_tolerates_an_unaligned_payload() {
let value = Sample {
id: 7,
count: 0x0102_0304_0506_0708,
};
let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
let mut shifted = vec![0u8];
shifted.extend_from_slice(&bytes);
let decoded = decode_aligned::<Sample>(&shifted[1..]).expect("aligned decode");
assert_eq!(decoded, value);
}
#[test]
fn decode_aligned_reads_an_aligned_payload_in_place() {
let value = Sample {
id: 11,
count: 0x0a0b_0c0d_0e0f_1011,
};
let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
assert!(
is_sample_aligned(&bytes),
"an encoded payload must be as aligned as a sample"
);
let decoded = decode_aligned::<Sample>(&bytes).expect("in-place decode");
assert_eq!(decoded, value);
}
}