use iceoryx2::prelude::*;
use iceoryx2::service::builder::event::{EventCreateError, EventOpenError, EventOpenOrCreateError};
use iceoryx2::service::builder::publish_subscribe::{
PublishSubscribeCreateError, PublishSubscribeOpenError, PublishSubscribeOpenOrCreateError,
};
use super::{
transport_error, IoxEvent, IoxNode, IoxPubSub, MAX_NODES, MAX_PUBLISHERS, MAX_SUBSCRIBERS,
PAYLOAD_ALIGNMENT, SUBSCRIBER_BUFFER,
};
use crate::types::{RpcError, RpcHeader};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum OpenMode {
CreateOrOpen,
ReadOnly,
}
const REMEDY: &str = "the iceoryx2 state on this machine was created by another build of this \
service (wire format, buffer sizes or port limits changed), or a process was \
killed while it held it. Once no process still runs the previous build, \
remove the iceoryx2 root path: %APPDATA%\\ice-rpc\\iceoryx2 on Windows, \
$XDG_DATA_HOME/ice-rpc/iceoryx2 (or ~/.local/share/ice-rpc/iceoryx2) \
elsewhere";
pub(super) fn open_service(
node: &IoxNode,
channel: &str,
suffix: &str,
mode: OpenMode,
) -> Result<IoxPubSub, RpcError> {
let topic = format!("{channel}{suffix}");
let name = ServiceName::new(&topic).map_err(|e| transport_error("service name", e))?;
let alignment = Alignment::new(PAYLOAD_ALIGNMENT)
.ok_or_else(|| RpcError::Internal("invalid payload alignment".to_string()))?;
let builder = node
.service_builder(&name)
.publish_subscribe::<[u8]>()
.user_header::<RpcHeader>()
.payload_alignment(alignment)
.max_publishers(MAX_PUBLISHERS)
.max_subscribers(MAX_SUBSCRIBERS)
.max_nodes(MAX_NODES)
.subscriber_max_buffer_size(SUBSCRIBER_BUFFER)
.enable_safe_overflow(false);
match mode {
OpenMode::CreateOrOpen => builder.open_or_create().map_err(|e| match e {
PublishSubscribeOpenOrCreateError::PublishSubscribeOpenError(inner) => {
pub_sub_open_error("open service", inner)
}
PublishSubscribeOpenOrCreateError::PublishSubscribeCreateError(inner) => {
pub_sub_create_error("create service", inner)
}
PublishSubscribeOpenOrCreateError::SystemInFlux => system_in_flux("open service"),
}),
OpenMode::ReadOnly => builder
.open()
.map_err(|e| pub_sub_open_error("open service (read-only)", e)),
}
}
pub(super) fn open_event_service(
node: &IoxNode,
channel: &str,
suffix: &str,
mode: OpenMode,
) -> Result<IoxEvent, RpcError> {
let topic = format!("{channel}{suffix}");
let name = ServiceName::new(&topic).map_err(|e| transport_error("service name", e))?;
let builder = node.service_builder(&name).event();
match mode {
OpenMode::CreateOrOpen => builder.open_or_create().map_err(event_error),
OpenMode::ReadOnly => builder
.open()
.map_err(|e| event_open_error("open event service (read-only)", e)),
}
}
fn is_stale_service(error: &PublishSubscribeOpenError) -> bool {
use PublishSubscribeOpenError as E;
matches!(
error,
E::IncompatibleTypes
| E::IncompatibleMessagingPattern
| E::IncompatibleAttributes
| E::IncompatibleOverflowBehavior
| E::DoesNotSupportRequestedMinBufferSize
| E::DoesNotSupportRequestedMinHistorySize
| E::DoesNotSupportRequestedMinSubscriberBorrowedSamples
| E::DoesNotSupportRequestedAmountOfPublishers
| E::DoesNotSupportRequestedAmountOfSubscribers
| E::DoesNotSupportRequestedAmountOfNodes
| E::ServiceInCorruptedState
| E::HangsInCreation
)
}
fn is_stale_creation(error: &PublishSubscribeCreateError) -> bool {
matches!(
error,
PublishSubscribeCreateError::ServiceInCorruptedState
| PublishSubscribeCreateError::HangsInCreation
)
}
fn pub_sub_open_error(context: &str, error: PublishSubscribeOpenError) -> RpcError {
if is_stale_service(&error) {
RpcError::ProtocolMismatch(format!("{context}: {error:?}. {REMEDY}"))
} else {
transport_error(context, error)
}
}
fn pub_sub_create_error(context: &str, error: PublishSubscribeCreateError) -> RpcError {
if is_stale_creation(&error) {
RpcError::ProtocolMismatch(format!("{context}: {error:?}. {REMEDY}"))
} else {
transport_error(context, error)
}
}
fn event_error(error: EventOpenOrCreateError) -> RpcError {
match error {
EventOpenOrCreateError::EventOpenError(inner) => event_open_error("open event", inner),
EventOpenOrCreateError::EventCreateError(inner) => {
event_create_error("create event", inner)
}
EventOpenOrCreateError::SystemInFlux => system_in_flux("open event service"),
}
}
fn system_in_flux(context: &str) -> RpcError {
RpcError::TransportError(format!(
"{context}: SystemInFlux. Either another process is creating or removing this service \
right now, in which case retrying works, or the state is left over from a process that \
died while it held it, in which case retrying cannot help and this persists: {REMEDY}"
))
}
fn event_create_error(context: &str, error: EventCreateError) -> RpcError {
if matches!(error, EventCreateError::ServiceInCorruptedState) {
RpcError::ProtocolMismatch(format!("{context}: {error:?}. {REMEDY}"))
} else {
transport_error(context, error)
}
}
fn event_open_error(context: &str, error: EventOpenError) -> RpcError {
use EventOpenError as E;
let stale = matches!(
error,
E::IncompatibleMessagingPattern
| E::IncompatibleAttributes
| E::IncompatibleDeadline
| E::IncompatibleNotifierCreatedEvent
| E::IncompatibleNotifierDroppedEvent
| E::IncompatibleNotifierDeadEvent
| E::DoesNotSupportRequestedAmountOfNotifiers
| E::DoesNotSupportRequestedAmountOfListeners
| E::DoesNotSupportRequestedMaxEventId
| E::DoesNotSupportRequestedAmountOfNodes
| E::ServiceInCorruptedState
| E::HangsInCreation
);
if stale {
RpcError::ProtocolMismatch(format!("{context}: {error:?}. {REMEDY}"))
} else {
transport_error(context, error)
}
}
#[cfg(test)]
mod tests {
use super::*;
use iceoryx2::service::builder::event::EventOpenError;
use iceoryx2::service::builder::publish_subscribe::PublishSubscribeOpenError;
#[test]
fn a_stale_service_is_reported_as_a_protocol_mismatch() {
for error in [
PublishSubscribeOpenError::IncompatibleTypes,
PublishSubscribeOpenError::IncompatibleOverflowBehavior,
PublishSubscribeOpenError::DoesNotSupportRequestedMinBufferSize,
PublishSubscribeOpenError::ServiceInCorruptedState,
PublishSubscribeOpenError::HangsInCreation,
] {
let mapped = pub_sub_open_error("open service", error);
assert!(
matches!(&mapped, RpcError::ProtocolMismatch(_)),
"{mapped:?}"
);
assert!(!mapped.is_retryable(), "no retry fixes a stale service");
assert!(mapped.to_string().contains("root path"), "{mapped}");
}
}
#[test]
fn another_open_failure_stays_a_transport_error() {
let mapped = pub_sub_open_error("open service", PublishSubscribeOpenError::DoesNotExist);
assert!(matches!(&mapped, RpcError::TransportError(_)), "{mapped:?}");
assert!(mapped.is_retryable());
}
#[test]
fn system_in_flux_names_both_of_its_causes() {
let mapped = system_in_flux("open service");
assert!(matches!(&mapped, RpcError::TransportError(_)), "{mapped:?}");
assert!(
mapped.is_retryable(),
"a concurrent create is transient, so the retry policy must not change"
);
let text = mapped.to_string();
assert!(text.contains("retrying works"), "{text}");
assert!(
text.contains("root path"),
"the persistent case must carry the remedy: {text}"
);
}
#[test]
fn the_event_side_is_classified_too() {
let stale = event_open_error(
"open event",
EventOpenError::IncompatibleNotifierCreatedEvent,
);
assert!(matches!(&stale, RpcError::ProtocolMismatch(_)), "{stale:?}");
let transient = event_open_error("open event", EventOpenError::DoesNotExist);
assert!(
matches!(&transient, RpcError::TransportError(_)),
"{transient:?}"
);
}
}