use std::collections::BTreeSet;
use std::time::Duration;
use iceoryx2::prelude::*;
use iceoryx2::service::header::publish_subscribe::Header as SampleHeader;
use iceoryx2::service::static_config::messaging_pattern::MessagingPattern;
use iceoryx2::service::{Service, ServiceDetails};
use super::open::{open_event_service, open_service, OpenMode};
use super::{
shared_node, transport_error, Iox, IoxEvent, IoxListener, IoxPubSub, IoxSubscriber,
REQUEST_NOTIFY_SUFFIX, REQUEST_SUFFIX, RESPONSE_NOTIFY_SUFFIX, RESPONSE_SUFFIX,
};
use crate::types::{RpcError, RpcHeader};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
Request,
Response,
}
impl Direction {
const fn pub_sub_suffix(self) -> &'static str {
match self {
Direction::Request => REQUEST_SUFFIX,
Direction::Response => RESPONSE_SUFFIX,
}
}
const fn notify_suffix(self) -> &'static str {
match self {
Direction::Request => REQUEST_NOTIFY_SUFFIX,
Direction::Response => RESPONSE_NOTIFY_SUFFIX,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Emitter {
pub pid: u32,
pub node_id: u128,
pub publisher_id: u128,
}
impl Emitter {
fn from_native(header: &SampleHeader) -> Self {
Self {
pid: crate::types::node_pid_to_u32(header.node_id().pid::<Iox>()),
node_id: header.node_id().value(),
publisher_id: header.publisher_id().value(),
}
}
}
pub struct DirectionView {
subscriber: IoxSubscriber,
listener: IoxListener,
_pub_sub: IoxPubSub,
_event: IoxEvent,
}
impl DirectionView {
pub fn open(channel: &str, direction: Direction) -> Result<Self, RpcError> {
let node = shared_node()?;
let pub_sub = open_service(
&node,
channel,
direction.pub_sub_suffix(),
OpenMode::ReadOnly,
)?;
let event = open_event_service(
&node,
channel,
direction.notify_suffix(),
OpenMode::ReadOnly,
)?;
let subscriber = pub_sub
.subscriber_builder()
.create()
.map_err(|e| transport_error("monitor subscriber", e))?;
let listener = event
.listener_builder()
.create()
.map_err(|e| transport_error("monitor listener", e))?;
Ok(Self {
subscriber,
listener,
_pub_sub: pub_sub,
_event: event,
})
}
pub fn try_receive(&self) -> Result<Option<(RpcHeader, Emitter, usize)>, RpcError> {
match self.subscriber.receive() {
Ok(Some(sample)) => Ok(Some((
*sample.user_header(),
Emitter::from_native(sample.header()),
sample.len(),
))),
Ok(None) => Ok(None),
Err(e) => Err(transport_error("monitor receive", e)),
}
}
pub fn try_receive_payload(&self) -> Result<Option<(RpcHeader, Emitter, Vec<u8>)>, RpcError> {
match self.subscriber.receive() {
Ok(Some(sample)) => {
let header = *sample.user_header();
let emitter = Emitter::from_native(sample.header());
let payload = sample.to_vec();
Ok(Some((header, emitter, payload)))
}
Ok(None) => Ok(None),
Err(e) => Err(transport_error("monitor receive", e)),
}
}
pub fn wait(&self, timeout: Duration) -> Result<bool, RpcError> {
match self.listener.timed_wait(|_activation| {}, timeout) {
Ok(activations) => Ok(activations > 0),
Err(e) => Err(transport_error("monitor wait", e)),
}
}
pub fn buffer_size(&self) -> usize {
self.subscriber.buffer_size()
}
pub fn service_name(&self) -> String {
self._pub_sub.name().as_str().to_owned()
}
pub fn publisher_count(&self) -> usize {
self._pub_sub.dynamic_config().number_of_publishers()
}
pub fn subscriber_count(&self) -> usize {
self._pub_sub
.dynamic_config()
.number_of_subscribers()
.saturating_sub(1)
}
pub fn max_publishers(&self) -> usize {
self._pub_sub.static_config().max_publishers()
}
pub fn max_subscribers(&self) -> usize {
self._pub_sub.static_config().max_subscribers()
}
pub fn subscriber_max_buffer_size(&self) -> usize {
self._pub_sub.static_config().subscriber_max_buffer_size()
}
pub fn history_size(&self) -> usize {
self._pub_sub.static_config().history_size()
}
pub fn has_safe_overflow(&self) -> bool {
self._pub_sub.static_config().has_safe_overflow()
}
pub fn payload_size(&self) -> usize {
self._pub_sub
.static_config()
.message_type_details()
.payload
.size()
}
}
fn strip_direction_suffix(name: &str) -> Option<&str> {
name.strip_suffix(REQUEST_SUFFIX)
.or_else(|| name.strip_suffix(RESPONSE_SUFFIX))
}
pub fn discover_channels() -> Result<Vec<String>, RpcError> {
let config = crate::config::build_iceoryx2_config();
let mut channels: BTreeSet<String> = BTreeSet::new();
<Iox as Service>::list(&config, |details: ServiceDetails<Iox>| {
if matches!(
details.static_details.messaging_pattern(),
MessagingPattern::PublishSubscribe(_)
) {
if let Some(channel) = strip_direction_suffix(details.static_details.name().as_str()) {
channels.insert(channel.to_owned());
}
}
CallbackProgression::Continue
})
.map_err(|e| transport_error("service discovery", e))?;
Ok(channels.into_iter().collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn direction_suffixes_match_the_transport() {
assert_eq!(Direction::Request.pub_sub_suffix(), "_req");
assert_eq!(Direction::Response.pub_sub_suffix(), "_resp");
assert_eq!(Direction::Request.notify_suffix(), "_req_notify");
assert_eq!(Direction::Response.notify_suffix(), "_resp_notify");
}
#[test]
fn discovery_strips_only_the_direction_suffix() {
assert_eq!(
strip_direction_suffix("DatabaseService_req"),
Some("DatabaseService")
);
assert_eq!(
strip_direction_suffix("DatabaseService_resp"),
Some("DatabaseService")
);
assert_eq!(strip_direction_suffix("DatabaseService_req_notify"), None);
assert_eq!(strip_direction_suffix("DatabaseService_resp_notify"), None);
assert_eq!(strip_direction_suffix("DatabaseService"), None);
}
}