roplat 0.2.0

roplat: just a robot operation system
Documentation
//! IPC 传输后端抽象
//!
//! `IpcTransport` 把「真实搬运字节的方式」从语义层(三缓冲 / 环形队列)解耦。
//! 上层语义层只关心 `publish` / `try_recv` 两个原子操作,后端可自由替换。

use std::fmt;
use std::sync::Arc;

/// IPC 层错误类型
#[derive(Debug, thiserror::Error)]
pub enum IpcError {
    /// Underlying I/O error.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Endpoint is not ready yet.
    #[error("endpoint not ready (publisher has not advertised yet)")]
    NotReady,

    /// Peer is gone.
    #[error("peer gone")]
    PeerGone,

    /// Schema mismatch.
    #[error("schema mismatch: expected {expected}, got {actual}")]
    SchemaMismatch {
        /// Expected schema.
        expected: String,
        /// Actual schema.
        actual: String,
    },

    /// Role mismatch.
    #[error("role mismatch: expected {expected}, got {actual}")]
    RoleMismatch {
        /// Expected role string.
        expected: String,
        /// Actual role string.
        actual: String,
    },

    /// Invalid URI.
    #[error("invalid endpoint uri: {0}")]
    InvalidUri(String),

    /// Rendezvous failure.
    #[error("rendezvous error: {0}")]
    Rendezvous(String),

    /// Serialization error.
    #[error("serde error: {0}")]
    Serde(String),

    /// Protocol error.
    #[error("protocol error: {0}")]
    Protocol(String),
}

/// Result alias for IPC operations.
pub type IpcResult<T> = Result<T, IpcError>;

/// IPC 传输后端 trait
///
/// 任意后端(TCP / UDS / 命名管道 / 共享内存 / 环回)都应实现本 trait。
/// 语义层(`IpcRingBuffer` 等)只依赖本 trait,后端可运行时选择。
///
/// 线程安全约束:实现必须保证 `publish` 和 `try_recv` 可分别在独立线程调用。
pub trait IpcTransport: Send + Sync {
    /// 后端标识,用于诊断与 `_meta.json` 记录
    fn kind(&self) -> &'static str;

    /// 发布一帧已序列化的字节(长度前缀由后端负责)
    fn publish(&self, bytes: &[u8]) -> IpcResult<()>;

    /// 非阻塞接收一帧;`None` 表示当前无新数据
    fn try_recv(&self) -> IpcResult<Option<Vec<u8>>>;

    /// 对端是否已连接/可用
    ///
    /// 默认实现为 `true`(后端若不支持健康检查则总报 ready);
    /// 实际带连接状态机的后端应自行覆盖。
    fn is_ready(&self) -> bool {
        true
    }
}

/// 擦除类型的后端句柄,供 `IpcRingBuffer` / `IpcTripleBuffer` 共享
///
/// 不要求具体后端是 `Clone`,但需要 `Arc` 包装以便在资源与节点间共享。
pub type IpcTransportHandle = Arc<dyn IpcTransport>;

impl fmt::Debug for dyn IpcTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IpcTransport")
            .field("kind", &self.kind())
            .finish()
    }
}