haematite 0.6.1

Content-addressed, branchable, actor-native storage engine
Documentation
use std::fmt;

/// Opaque identity for one carrier lifecycle episode.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct EpisodeId(u64);

impl EpisodeId {
    /// Creates an episode identity from carrier-owned identity material.
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the identity material without assigning it protocol meaning.
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Monotone identity for one connection attempt.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AttemptGeneration(u64);

impl AttemptGeneration {
    /// Creates a generation from a carrier-local monotone value.
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the carrier-local value.
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Opaque identity for an accepted transport connection.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ConnectionId([u8; 16]);

impl ConnectionId {
    /// Creates an identity from opaque bytes supplied by the connection owner.
    pub const fn new(value: [u8; 16]) -> Self {
        Self(value)
    }

    /// Returns the opaque identity bytes.
    pub const fn as_bytes(&self) -> &[u8; 16] {
        &self.0
    }
}

/// Monotone incarnation of successive accepted connections for one peer.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Incarnation(u64);

impl Incarnation {
    /// Creates an incarnation supplied by the identity owner.
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the monotone value.
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Immutable identity of one accepted connection.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ConnectionKey {
    /// Fresh identity of the accepted connection.
    pub connection_id: ConnectionId,
    /// Peer incarnation fixed for the connection lifetime.
    pub incarnation: Incarnation,
}

/// Bytes that the carrier stores and forwards without interpretation.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct OpaqueBytes(Vec<u8>);

impl OpaqueBytes {
    /// Wraps bytes without decoding or classifying them.
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Borrows the byte sequence.
    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// Returns the byte count.
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    /// Reports whether the byte sequence is empty.
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Transfers the underlying byte sequence to the caller.
    pub fn into_vec(self) -> Vec<u8> {
        self.0
    }
}

impl fmt::Debug for OpaqueBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OpaqueBytes")
            .field("len", &self.len())
            .finish_non_exhaustive()
    }
}

impl From<Vec<u8>> for OpaqueBytes {
    fn from(bytes: Vec<u8>) -> Self {
        Self::new(bytes)
    }
}

impl From<&[u8]> for OpaqueBytes {
    fn from(bytes: &[u8]) -> Self {
        Self::new(bytes.to_vec())
    }
}

/// Opaque peer metadata supplied to an established connection.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct AuthenticatedPeerBinding(Vec<u8>);

impl AuthenticatedPeerBinding {
    /// Wraps supplied metadata without decoding it.
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Borrows the opaque metadata.
    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    /// Transfers the metadata to the caller.
    pub fn into_vec(self) -> Vec<u8> {
        self.0
    }
}

impl fmt::Debug for AuthenticatedPeerBinding {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AuthenticatedPeerBinding")
            .field("len", &self.0.len())
            .finish_non_exhaustive()
    }
}

/// Typed reason that a connection attempt was made.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierEstablishedCause {
    /// A caller explicitly requested an attempt.
    ExplicitAction,
    /// An externally proved online transition requested an attempt.
    ProvedOnline,
    /// Fate of an established connection requested its successor attempt.
    EstablishedConnectionFate,
}

/// Stage at which a connection attempt failed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierConnectFailureStage {
    /// The transport could not be established.
    Dial,
    /// The transport handshake did not complete.
    Handshake,
}

/// State disposition carried by a typed connection failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierConnectFailureDisposition {
    /// Park until a later qualifying event.
    Park,
    /// Terminate the carrier episode.
    Stop,
}

/// Typed cause and disposition of a failed connection attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CarrierConnectFailureCause {
    stage: CarrierConnectFailureStage,
    disposition: CarrierConnectFailureDisposition,
}

impl CarrierConnectFailureCause {
    /// Creates a typed attempt failure.
    pub const fn new(
        stage: CarrierConnectFailureStage,
        disposition: CarrierConnectFailureDisposition,
    ) -> Self {
        Self { stage, disposition }
    }

    /// Returns the stage that failed.
    pub const fn stage(self) -> CarrierConnectFailureStage {
        self.stage
    }

    /// Returns whether the failure parks or stops the episode.
    pub const fn disposition(self) -> CarrierConnectFailureDisposition {
        self.disposition
    }
}

/// Typed reason for a parked carrier.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierParkedCause {
    /// No attempt has been requested yet.
    AwaitingAction,
    /// A proved offline event superseded current work.
    Offline,
    /// An established connection ended and its successor is being attempted.
    EstablishedConnectionFate(CarrierLostCause),
    /// A connection attempt failed and no work is armed.
    ConnectFailed(CarrierConnectFailureCause),
}

/// Fatal refusal vocabulary for an envelope or queue.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierRefusal {
    /// The announced payload exceeds the fixed frame bound.
    FrameTooLarge { announced: u32, maximum: usize },
    /// Fewer than four length-prefix bytes were received.
    TruncatedLengthPrefix { received: usize },
    /// The body ended before the announced length.
    TruncatedFrame { announced: u32, received: usize },
    /// More body bytes were supplied than announced.
    TrailingFrameBytes { announced: u32, received: usize },
    /// A non-binary transport message was supplied.
    NonBinaryWebSocketMessage,
    /// Taking another frame would exceed a queue bound.
    QueueCapacityExceeded {
        queued_frames: usize,
        queued_bytes: usize,
    },
}

/// Typed reason supplied to the carrier close operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierCloseCause {
    /// The application explicitly ended the connection.
    ApplicationRequested,
    /// A fresh explicit action replaced the connection.
    Replaced,
    /// The owning service is shutting down.
    Shutdown,
    /// A fatal typed refusal requires closure.
    Refused(CarrierRefusal),
}

/// Typed terminal fate of an established connection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierLostCause {
    /// The remote side closed the transport cleanly.
    CleanClose,
    /// The transport reported an error.
    TransportError,
    /// A fresh explicit action replaced the connection.
    Replaced,
    /// A local close operation ended the connection.
    LocalClose(CarrierCloseCause),
    /// The owning service shut down.
    Shutdown,
    /// A malformed envelope fatally ended the connection.
    MalformedFrame(CarrierRefusal),
}

/// Typed terminal reason for a carrier episode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierStoppedCause {
    /// A local close operation ended the episode.
    ExplicitClose(CarrierCloseCause),
    /// The owning service shut down.
    Shutdown,
    /// A connection failure required terminal disposition.
    ConnectFailed(CarrierConnectFailureCause),
    /// The carrier-local identity sequence was exhausted.
    IdentitySpaceExhausted,
}

/// Refusal returned directly from [`Carrier::send`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierSendRefusal {
    /// The adapter cannot currently accept another frame.
    Backpressured,
    /// The payload exceeds the fixed frame bound.
    FrameTooLarge { announced: usize, maximum: usize },
    /// Taking another frame would exceed a queue bound.
    QueueCapacityExceeded {
        queued_frames: usize,
        queued_bytes: usize,
    },
    /// The supplied key is not the current established connection.
    ConnectionNotCurrent { key: ConnectionKey },
}

/// Immediate result of transferring bytes to a carrier send queue.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarrierSendOutcome {
    /// The carrier took ownership of the bytes.
    Accepted,
    /// The carrier did not accept the bytes.
    Refused(CarrierSendRefusal),
}

/// Ordered event vocabulary emitted by a carrier implementation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CarrierEvent {
    Established {
        episode: EpisodeId,
        generation: AttemptGeneration,
        key: ConnectionKey,
        authenticated_peer_binding: AuthenticatedPeerBinding,
        cause: CarrierEstablishedCause,
    },
    ConnectFailed {
        episode: EpisodeId,
        generation: AttemptGeneration,
        cause: CarrierConnectFailureCause,
    },
    Parked {
        episode: EpisodeId,
        cause: CarrierParkedCause,
    },
    Stopped {
        episode: EpisodeId,
        cause: CarrierStoppedCause,
    },
    FrameReceived {
        key: ConnectionKey,
        bytes: OpaqueBytes,
    },
    SendReady {
        key: ConnectionKey,
    },
    Refused {
        key: ConnectionKey,
        refusal: CarrierRefusal,
    },
    Lost {
        key: ConnectionKey,
        cause: CarrierLostCause,
    },
}

/// Carrier-neutral ordered binary transport seam.
pub trait Carrier {
    /// Transfers ownership on acceptance while preserving invocation order.
    fn send(&mut self, key: ConnectionKey, bytes: OpaqueBytes) -> CarrierSendOutcome;

    /// Requests closure of the identified connection with a typed cause.
    fn close(&mut self, key: ConnectionKey, cause: CarrierCloseCause);
}