modem_device/layer.rs
1//! A layer between the scheduler and the medium (#157): a transform over
2//! SDUs with no I/O of its own.
3//!
4//! Encryption (#158), a peer address on a shared channel (#160),
5//! fragmentation below Zenoh's establishment floor (#162), forward error
6//! correction (#161), compression (#163): each is a function of its own
7//! state over opaque SDUs. A layer never awaits, never owns a task or a
8//! socket, and never forwards a method, because it is not a
9//! [`Medium`](crate::Medium). One `Stack` in the driver composes the
10//! configured layers into the single `Medium` the scheduler sees, and owns
11//! every piece of I/O once: backpressure, the receive loop, the timers. See
12//! `docs/design/sdu-layers.md` §1–§3; the reason is this workspace's own
13//! history of hand-written decorators (#50, #51, #52).
14//!
15//! What stays absolute: a layer never parses a Zenoh batch (I1), never
16//! retransmits (architecture §4.13), and never claims a property it does not
17//! provide, for reliability (I2) or security (I6). `conformance::layer`
18//! holds every layer to what that implies, without a runtime.
19
20use std::time::Instant;
21
22use crate::action::{ActionError, ActionOutcome, ActionSpec};
23use crate::config::ConfigValue;
24use crate::{Capabilities, Counter, LaneKey, Sdu, SecurityProperties};
25
26/// What a layer hands down or up: frames for the layer below, or SDUs for
27/// the layer above, each on a lane. One SDU may become several frames (a
28/// fragment layer, FEC repair) and one frame may become none (a reassembly
29/// in progress, a refused forgery).
30pub type Frames = Vec<(LaneKey, Sdu)>;
31
32/// Why a layer refused to be built over what is below it, or refused an SDU.
33#[derive(Debug, thiserror::Error)]
34#[non_exhaustive]
35pub enum LayerError {
36 /// The layer below carries too little for this layer's overhead.
37 #[error(
38 "{layer}: the layer below carries {below} bytes per SDU and this layer needs {needs}; \
39 nothing would fit"
40 )]
41 TooSmallBelow {
42 layer: &'static str,
43 needs: u16,
44 below: u16,
45 },
46 /// A lane the layer cannot serve, with the reason.
47 #[error("{layer}: lane {lane}: {reason}")]
48 Lane {
49 layer: &'static str,
50 lane: LaneKey,
51 reason: String,
52 },
53 /// The layer cannot transform this SDU, or cannot go on at all, in its
54 /// own words. The `Stack` raises it as a device fault, once, and refuses
55 /// the SDU the way a medium's refusal is handled.
56 #[error("{layer}: {reason}")]
57 Failed { layer: &'static str, reason: String },
58 /// What is below cannot be layered over: a frame too small to hold a
59 /// header, a medium that already fragments.
60 #[error("{layer}: {reason}")]
61 Unsupported { layer: &'static str, reason: String },
62}
63
64/// What [`Layer::decode`] made of a frame.
65#[derive(Clone, Debug, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum Decoded {
68 /// The frame was taken: whatever it yielded is in `out`, which may be
69 /// nothing yet (a reassembly in progress).
70 Accepted,
71 /// The frame was refused and nothing was delivered. `reason` is a short
72 /// fixed word the layer also counts under (`"auth-failed"`,
73 /// `"replay"`, `"foreign"`); `detail` is the layer's own sentence for
74 /// the log and the fault.
75 Refused {
76 reason: &'static str,
77 detail: String,
78 },
79}
80
81impl Decoded {
82 /// A refusal, with the counted reason and the sentence.
83 #[must_use]
84 pub fn refused(reason: &'static str, detail: impl Into<String>) -> Self {
85 Self::Refused {
86 reason,
87 detail: detail.into(),
88 }
89 }
90}
91
92/// What a layer is told about its place at construction: the device it
93/// serves, and where it may keep state it must not lose (#158's counters),
94/// if the host gave the driver one.
95#[derive(Clone, Debug, PartialEq, Eq)]
96#[non_exhaustive]
97pub struct LayerContext {
98 /// The device's name, the `{device}` chunk of every key about it.
99 pub device: String,
100 /// A directory of this layer's own, under the daemon's state directory,
101 /// or `None` when the host has none. A layer that needs one and is given
102 /// none refuses to be built, naming the setting.
103 pub state_dir: Option<std::path::PathBuf>,
104}
105
106impl LayerContext {
107 /// For `device`, with no state directory.
108 #[must_use]
109 pub fn new(device: impl Into<String>) -> Self {
110 Self {
111 device: device.into(),
112 state_dir: None,
113 }
114 }
115
116 /// With a state directory.
117 #[must_use]
118 pub fn state_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
119 self.state_dir = Some(dir.into());
120 self
121 }
122}
123
124/// A synchronous transform over SDUs, composed by the driver's `Stack`.
125///
126/// Every method is called under one lock and never across an `.await`, so
127/// a layer is a plain state machine: `encode` and `decode` are called in the
128/// order the SDUs and frames arrive, and `tick` whenever the `Stack` reaches
129/// a deadline this layer announced, and after every `encode`/`decode` pass
130/// (a tick with nothing due is a question, not an order). Time is the
131/// caller's: a layer compares the `now` it is handed and never reads a
132/// clock, which is what lets a test drive it deterministically.
133pub trait Layer: Send {
134 /// The name the file and the counters use: `"aead"`, `"fragment"`.
135 fn kind(&self) -> &'static str;
136
137 /// What this layer makes of the capabilities below it: the overhead
138 /// taken off each direction, `reliable` as the layer's rule says, the
139 /// framing it adds or passes through. Refused when nothing would fit or
140 /// the layer below cannot be layered over.
141 fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError>;
142
143 /// The lanes to ask of the layer below, given the lanes asked of this
144 /// one. Identity for most layers; an addressing layer maps a lane per
145 /// peer onto one channel. Called once, before anything moves.
146 fn lanes(&mut self, above: &[LaneKey]) -> Result<Vec<LaneKey>, LayerError> {
147 Ok(above.to_vec())
148 }
149
150 /// One SDU going down: the frames for the layer below, in order, pushed
151 /// onto `out`.
152 fn encode(
153 &mut self,
154 lane: &LaneKey,
155 sdu: Sdu,
156 now: Instant,
157 out: &mut Frames,
158 ) -> Result<(), LayerError>;
159
160 /// One frame coming up: the SDUs for the layer above pushed onto `out`,
161 /// or a counted refusal.
162 fn decode(&mut self, lane: &LaneKey, frame: Sdu, now: Instant, out: &mut Frames) -> Decoded;
163
164 /// Time passing: what the layer's timers owe downward (`down`, as
165 /// frames for the layer below) and upward (`up`, as SDUs for the layer
166 /// above), and when it next needs a tick. `None` when nothing is
167 /// pending.
168 fn tick(&mut self, now: Instant, down: &mut Frames, up: &mut Frames) -> Option<Instant> {
169 let _ = (now, down, up);
170 None
171 }
172
173 /// What this layer guarantees about the bytes it carries, given what
174 /// the layers below guarantee (I6). A layer that adds nothing passes
175 /// `below` through.
176 fn security(&self, below: Option<&SecurityProperties>) -> Option<SecurityProperties> {
177 below.cloned()
178 }
179
180 /// The layer's counters, every one scoped by this layer's kind.
181 fn counters(&self) -> Vec<Counter> {
182 Vec::new()
183 }
184
185 /// The operator actions this layer offers (#129), if any: a key
186 /// rotation, for one.
187 fn actions(&self) -> Vec<ActionSpec> {
188 Vec::new()
189 }
190
191 /// Run one of them, now. Synchronous, like everything here.
192 fn invoke(
193 &mut self,
194 name: &str,
195 arguments: &std::collections::BTreeMap<String, ConfigValue>,
196 ) -> Result<ActionOutcome, ActionError> {
197 let _ = arguments;
198 Err(ActionError::UnknownAction(name.to_string()))
199 }
200}