modem-device 0.3.0

The seam between the zenoh-modem driver and a physical or simulated medium
Documentation
//! A layer between the scheduler and the medium (#157): a transform over
//! SDUs with no I/O of its own.
//!
//! Encryption (#158), a peer address on a shared channel (#160),
//! fragmentation below Zenoh's establishment floor (#162), forward error
//! correction (#161), compression (#163): each is a function of its own
//! state over opaque SDUs. A layer never awaits, never owns a task or a
//! socket, and never forwards a method, because it is not a
//! [`Medium`](crate::Medium). One `Stack` in the driver composes the
//! configured layers into the single `Medium` the scheduler sees, and owns
//! every piece of I/O once: backpressure, the receive loop, the timers. See
//! `docs/design/sdu-layers.md` §1–§3; the reason is this workspace's own
//! history of hand-written decorators (#50, #51, #52).
//!
//! What stays absolute: a layer never parses a Zenoh batch (I1), never
//! retransmits (architecture §4.13), and never claims a property it does not
//! provide, for reliability (I2) or security (I6). `conformance::layer`
//! holds every layer to what that implies, without a runtime.

use std::time::Instant;

use crate::action::{ActionError, ActionOutcome, ActionSpec};
use crate::config::ConfigValue;
use crate::{Capabilities, Counter, LaneKey, Sdu, SecurityProperties};

/// What a layer hands down or up: frames for the layer below, or SDUs for
/// the layer above, each on a lane. One SDU may become several frames (a
/// fragment layer, FEC repair) and one frame may become none (a reassembly
/// in progress, a refused forgery).
pub type Frames = Vec<(LaneKey, Sdu)>;

/// Why a layer refused to be built over what is below it, or refused an SDU.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LayerError {
    /// The layer below carries too little for this layer's overhead.
    #[error(
        "{layer}: the layer below carries {below} bytes per SDU and this layer needs {needs}; \
         nothing would fit"
    )]
    TooSmallBelow {
        layer: &'static str,
        needs: u16,
        below: u16,
    },
    /// A lane the layer cannot serve, with the reason.
    #[error("{layer}: lane {lane}: {reason}")]
    Lane {
        layer: &'static str,
        lane: LaneKey,
        reason: String,
    },
    /// The layer cannot transform this SDU, or cannot go on at all, in its
    /// own words. The `Stack` raises it as a device fault, once, and refuses
    /// the SDU the way a medium's refusal is handled.
    #[error("{layer}: {reason}")]
    Failed { layer: &'static str, reason: String },
    /// What is below cannot be layered over: a frame too small to hold a
    /// header, a medium that already fragments.
    #[error("{layer}: {reason}")]
    Unsupported { layer: &'static str, reason: String },
}

/// What [`Layer::decode`] made of a frame.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Decoded {
    /// The frame was taken: whatever it yielded is in `out`, which may be
    /// nothing yet (a reassembly in progress).
    Accepted,
    /// The frame was refused and nothing was delivered. `reason` is a short
    /// fixed word the layer also counts under (`"auth-failed"`,
    /// `"replay"`, `"foreign"`); `detail` is the layer's own sentence for
    /// the log and the fault.
    Refused {
        reason: &'static str,
        detail: String,
    },
}

impl Decoded {
    /// A refusal, with the counted reason and the sentence.
    #[must_use]
    pub fn refused(reason: &'static str, detail: impl Into<String>) -> Self {
        Self::Refused {
            reason,
            detail: detail.into(),
        }
    }
}

/// What a layer is told about its place at construction: the device it
/// serves, and where it may keep state it must not lose (#158's counters),
/// if the host gave the driver one.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LayerContext {
    /// The device's name, the `{device}` chunk of every key about it.
    pub device: String,
    /// A directory of this layer's own, under the daemon's state directory,
    /// or `None` when the host has none. A layer that needs one and is given
    /// none refuses to be built, naming the setting.
    pub state_dir: Option<std::path::PathBuf>,
}

impl LayerContext {
    /// For `device`, with no state directory.
    #[must_use]
    pub fn new(device: impl Into<String>) -> Self {
        Self {
            device: device.into(),
            state_dir: None,
        }
    }

    /// With a state directory.
    #[must_use]
    pub fn state_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
        self.state_dir = Some(dir.into());
        self
    }
}

/// A synchronous transform over SDUs, composed by the driver's `Stack`.
///
/// Every method is called under one lock and never across an `.await`, so
/// a layer is a plain state machine: `encode` and `decode` are called in the
/// order the SDUs and frames arrive, and `tick` whenever the `Stack` reaches
/// a deadline this layer announced, and after every `encode`/`decode` pass
/// (a tick with nothing due is a question, not an order). Time is the
/// caller's: a layer compares the `now` it is handed and never reads a
/// clock, which is what lets a test drive it deterministically.
pub trait Layer: Send {
    /// The name the file and the counters use: `"aead"`, `"fragment"`.
    fn kind(&self) -> &'static str;

    /// What this layer makes of the capabilities below it: the overhead
    /// taken off each direction, `reliable` as the layer's rule says, the
    /// framing it adds or passes through. Refused when nothing would fit or
    /// the layer below cannot be layered over.
    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError>;

    /// The lanes to ask of the layer below, given the lanes asked of this
    /// one. Identity for most layers; an addressing layer maps a lane per
    /// peer onto one channel. Called once, before anything moves.
    fn lanes(&mut self, above: &[LaneKey]) -> Result<Vec<LaneKey>, LayerError> {
        Ok(above.to_vec())
    }

    /// One SDU going down: the frames for the layer below, in order, pushed
    /// onto `out`.
    fn encode(
        &mut self,
        lane: &LaneKey,
        sdu: Sdu,
        now: Instant,
        out: &mut Frames,
    ) -> Result<(), LayerError>;

    /// One frame coming up: the SDUs for the layer above pushed onto `out`,
    /// or a counted refusal.
    fn decode(&mut self, lane: &LaneKey, frame: Sdu, now: Instant, out: &mut Frames) -> Decoded;

    /// Time passing: what the layer's timers owe downward (`down`, as
    /// frames for the layer below) and upward (`up`, as SDUs for the layer
    /// above), and when it next needs a tick. `None` when nothing is
    /// pending.
    fn tick(&mut self, now: Instant, down: &mut Frames, up: &mut Frames) -> Option<Instant> {
        let _ = (now, down, up);
        None
    }

    /// What this layer guarantees about the bytes it carries, given what
    /// the layers below guarantee (I6). A layer that adds nothing passes
    /// `below` through.
    fn security(&self, below: Option<&SecurityProperties>) -> Option<SecurityProperties> {
        below.cloned()
    }

    /// The layer's counters, every one scoped by this layer's kind.
    fn counters(&self) -> Vec<Counter> {
        Vec::new()
    }

    /// The operator actions this layer offers (#129), if any: a key
    /// rotation, for one.
    fn actions(&self) -> Vec<ActionSpec> {
        Vec::new()
    }

    /// Run one of them, now. Synchronous, like everything here.
    fn invoke(
        &mut self,
        name: &str,
        arguments: &std::collections::BTreeMap<String, ConfigValue>,
    ) -> Result<ActionOutcome, ActionError> {
        let _ = arguments;
        Err(ActionError::UnknownAction(name.to_string()))
    }
}