tarpc-cat 0.1.0

RPC framework built on comp-cat-rs: typed effects, no async, categorical foundations
Documentation
//! Wire protocol types.
//!
//! Defines the message envelope exchanged over the transport.
//! The [`Envelope`] is the unit of serialization on the wire.
//! Payloads are JSON strings embedded inside the envelope,
//! avoiding generic type parameters on the wire format.

use serde::{Deserialize, Serialize};

/// Unique identifier for a request within a connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RequestId(u64);

impl RequestId {
    /// Create a new request identifier.
    #[must_use]
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// The underlying numeric value.
    #[must_use]
    pub fn value(self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for RequestId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RequestId({})", self.0)
    }
}

/// Wire envelope exchanged between client and server.
///
/// Each variant carries a [`RequestId`] for correlation and a
/// payload or message string.  The payload field contains a
/// JSON-serialized request or response body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Envelope {
    /// Client-to-server request.
    Request {
        /// Correlation identifier.
        id: RequestId,
        /// JSON-serialized request body.
        payload: String,
    },
    /// Server-to-client response.
    Response {
        /// Correlation identifier matching the request.
        id: RequestId,
        /// JSON-serialized response body.
        payload: String,
    },
    /// Server-to-client error.
    Error {
        /// Correlation identifier matching the request.
        id: RequestId,
        /// Human-readable error description.
        message: String,
    },
}

impl Envelope {
    /// The [`RequestId`] carried by this envelope.
    #[must_use]
    pub fn id(&self) -> RequestId {
        match self {
            Self::Request { id, .. }
            | Self::Response { id, .. }
            | Self::Error { id, .. } => *id,
        }
    }
}