prns-runtime-embassy 0.3.6

Embassy host runtime for Personal Reticulum
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use heapless::Vec as HeaplessVec;

use crate::engine::{EngineReaction, FanTarget, InstantMillis, Journaled};
use crate::interfaces::InterfaceIfac;
use crate::interfaces::{InterfaceDescriptor, InterfaceId, InterfaceKind};
use crate::manifold::announce_pacer::{AnnouncePacer, FixedPacerQueue};
use crate::manifold::grant::{FrameTarget, LaneWriteOutcome, ManifoldLaneWriter};
use crate::manifold::interface_seam::EMBEDDED_MAX_WIRE_FRAME_LEN;
use crate::manifold::kernel::{
    route_reaction as route_engine_reaction, AnnounceDirective, DirectiveEgress,
};

fn lane_serves(lane_key: InterfaceId, target: InterfaceId) -> bool {
    if lane_key == target {
        return true;
    }
    match (lane_key.kind(), target.kind()) {
        (Some(supervisor), Some(child)) => supervisor.member_kind() == Some(child),
        _ => false,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum EgressOutcome {
    Enqueued,
    LaneFull {
        lane: InterfaceId,
    },
    FrameTooLarge {
        lane: InterfaceId,
        frame_len: usize,
        capacity: usize,
    },
    NoLane,
}

fn egress_outcome(lane: InterfaceId, outcome: LaneWriteOutcome) -> EgressOutcome {
    match outcome {
        LaneWriteOutcome::Written => EgressOutcome::Enqueued,
        LaneWriteOutcome::Full => EgressOutcome::LaneFull { lane },
        LaneWriteOutcome::FrameTooLarge {
            frame_len,
            capacity,
        } => EgressOutcome::FrameTooLarge {
            lane,
            frame_len,
            capacity,
        },
    }
}

/// Nonblocking direct and fleet egress.
pub trait ManifoldEgress {
    fn enqueue(&mut self, target: InterfaceId, bytes: &[u8]) -> EgressOutcome;
    fn enqueue_broadcast(
        &mut self,
        supervisor: InterfaceKind,
        fan: FanTarget,
        bytes: &[u8],
    ) -> EgressOutcome;
    fn lane_for(&self, target: InterfaceId) -> Option<InterfaceId> {
        Some(target)
    }
    fn fleet_lane(&self, _supervisor: InterfaceKind) -> Option<InterfaceId> {
        None
    }
}

/// Fixed-set egress with erased slot sizes, allowing heterogeneous lanes in one borrowed slice without allocation.
pub struct EmbassyEgress<'a> {
    lanes: &'a mut [(InterfaceId, &'a mut dyn ManifoldLaneWriter)],
}

impl<'a> EmbassyEgress<'a> {
    #[must_use]
    pub fn new(lanes: &'a mut [(InterfaceId, &'a mut dyn ManifoldLaneWriter)]) -> Self {
        Self { lanes }
    }
}

impl ManifoldEgress for EmbassyEgress<'_> {
    fn enqueue(&mut self, target: InterfaceId, bytes: &[u8]) -> EgressOutcome {
        for (id, producer) in self.lanes.iter_mut() {
            if lane_serves(*id, target) {
                return egress_outcome(*id, producer.try_write(FrameTarget::Direct(target), bytes));
            }
        }
        EgressOutcome::NoLane
    }

    fn enqueue_broadcast(
        &mut self,
        supervisor: InterfaceKind,
        fan: FanTarget,
        bytes: &[u8],
    ) -> EgressOutcome {
        for (id, producer) in self.lanes.iter_mut() {
            if id.kind() == Some(supervisor) {
                return egress_outcome(*id, producer.try_write(FrameTarget::Fan(fan), bytes));
            }
        }
        EgressOutcome::NoLane
    }

    fn lane_for(&self, target: InterfaceId) -> Option<InterfaceId> {
        self.lanes
            .iter()
            .map(|(id, _)| *id)
            .find(|id| lane_serves(*id, target))
    }

    fn fleet_lane(&self, supervisor: InterfaceKind) -> Option<InterfaceId> {
        self.lanes
            .iter()
            .map(|(id, _)| *id)
            .find(|id| id.kind() == Some(supervisor))
    }
}

pub(super) const MAX_PACED_INTERFACES: usize = 2;
const PACER_DEPTH: usize = 2;

pub(super) struct InterfacePacer {
    pub(super) id: InterfaceId,
    pacer: AnnouncePacer<FixedPacerQueue<PACER_DEPTH, FrameTarget>, FrameTarget>,
}

impl InterfacePacer {
    pub(super) fn from_descriptor(id: InterfaceId, descriptor: &InterfaceDescriptor) -> Self {
        Self {
            id,
            pacer: AnnouncePacer::new(descriptor.announce_bandwidth_cap, descriptor.bitrate),
        }
    }
}

pub(super) fn route_reaction(
    reaction: EngineReaction<'_>,
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
    pacers: &mut [InterfacePacer],
    now: InstantMillis,
    app: &mut impl FnMut(Journaled<'_>),
) {
    let mut directive_egress = EmbassyDirectiveEgress {
        egress,
        ifacs,
        pacers,
        now,
    };
    route_engine_reaction(reaction, &mut directive_egress, app);
}

struct EmbassyDirectiveEgress<'a, E> {
    egress: &'a mut E,
    ifacs: &'a [InterfaceIfac],
    pacers: &'a mut [InterfacePacer],
    now: InstantMillis,
}

impl<E: ManifoldEgress> EmbassyDirectiveEgress<'_, E> {
    fn offer_to_fleet_pacer(
        &mut self,
        supervisor: InterfaceKind,
        fan: FanTarget,
        bytes: &[u8],
        hops: u8,
    ) {
        let Some(lane) = self.egress.fleet_lane(supervisor) else {
            enqueue_broadcast_for_wire(self.egress, self.ifacs, supervisor, fan, bytes);
            return;
        };
        match self.pacers.iter_mut().find(|entry| entry.id == lane) {
            Some(entry) => {
                let _ = entry.pacer.offer_tagged(
                    bytes,
                    hops,
                    self.now,
                    FrameTarget::Fan(fan),
                    |frame, target| {
                        enqueue_paced_for_wire(self.egress, self.ifacs, lane, target, frame)
                    },
                );
            }
            None => {
                enqueue_broadcast_for_wire(self.egress, self.ifacs, supervisor, fan, bytes);
            }
        }
    }
}

impl<E: ManifoldEgress> DirectiveEgress for EmbassyDirectiveEgress<'_, E> {
    fn send(&mut self, target: InterfaceId, bytes: &[u8]) {
        enqueue_for_wire(self.egress, self.ifacs, target, bytes);
    }

    fn send_announce(&mut self, target: InterfaceId, announce: AnnounceDirective<'_>) {
        offer_to_pacer(
            self.pacers,
            target,
            announce.bytes(),
            announce.hops(),
            self.now,
            self.egress,
            self.ifacs,
        );
    }

    fn send_to_fleet(&mut self, supervisor: InterfaceKind, fan: FanTarget, bytes: &[u8]) {
        enqueue_broadcast_for_wire(self.egress, self.ifacs, supervisor, fan, bytes);
    }

    fn send_announce_to_fleet(
        &mut self,
        supervisor: InterfaceKind,
        fan: FanTarget,
        announce: AnnounceDirective<'_>,
    ) {
        self.offer_to_fleet_pacer(supervisor, fan, announce.bytes(), announce.hops());
    }

    fn emit_frame(
        &mut self,
        target: InterfaceId,
        _size_hint: usize,
        fill: &mut dyn FnMut(&mut [u8]) -> Option<usize>,
    ) {
        emit_for_wire(self.egress, self.ifacs, target, fill);
    }
}

/// Erased slot sizes require one bounded stack buffer before the frame enters its lane. `fill` runs exactly once even when the lane is full.
fn emit_for_wire(
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
    target: InterfaceId,
    fill: &mut dyn FnMut(&mut [u8]) -> Option<usize>,
) {
    let mut frame = [0u8; EMBEDDED_MAX_WIRE_FRAME_LEN];
    if let Some(len) = fill(&mut frame) {
        enqueue_for_wire(egress, ifacs, target, &frame[..len]);
    }
}

pub(super) fn ifac_for(ifacs: &[InterfaceIfac], id: InterfaceId) -> Option<&InterfaceIfac> {
    if ifacs.is_empty() {
        return None;
    }
    ifacs.iter().find(|entry| entry.id == id)
}

pub(super) fn enqueue_for_wire(
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
    target: InterfaceId,
    bytes: &[u8],
) {
    let lane = egress.lane_for(target).unwrap_or(target);
    match ifac_for(ifacs, lane) {
        Some(entry) => {
            let mut wire = [0u8; EMBEDDED_MAX_WIRE_FRAME_LEN];
            if let Some(masked_len) = entry.context.mask_outbound(bytes, &mut wire) {
                let _ = egress.enqueue(target, &wire[..masked_len]);
            }
        }
        None => {
            let _ = egress.enqueue(target, bytes);
        }
    }
}

pub(super) fn enqueue_broadcast_for_wire(
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
    supervisor: InterfaceKind,
    fan: FanTarget,
    bytes: &[u8],
) {
    match egress
        .fleet_lane(supervisor)
        .and_then(|lane| ifac_for(ifacs, lane))
    {
        Some(entry) => {
            let mut wire = [0u8; EMBEDDED_MAX_WIRE_FRAME_LEN];
            if let Some(masked_len) = entry.context.mask_outbound(bytes, &mut wire) {
                let _ = egress.enqueue_broadcast(supervisor, fan, &wire[..masked_len]);
            }
        }
        None => {
            let _ = egress.enqueue_broadcast(supervisor, fan, bytes);
        }
    }
}

fn offer_to_pacer(
    pacers: &mut [InterfacePacer],
    target: InterfaceId,
    bytes: &[u8],
    hops: u8,
    now: InstantMillis,
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
) {
    let lane = egress.lane_for(target).unwrap_or(target);
    match pacers.iter_mut().find(|entry| entry.id == lane) {
        Some(entry) => {
            let _ = entry.pacer.offer_tagged(
                bytes,
                hops,
                now,
                FrameTarget::Direct(target),
                |frame, target| enqueue_paced_for_wire(egress, ifacs, lane, target, frame),
            );
        }
        None => enqueue_for_wire(egress, ifacs, target, bytes),
    }
}

fn enqueue_paced_for_wire(
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
    lane: InterfaceId,
    target: FrameTarget,
    bytes: &[u8],
) {
    match target {
        FrameTarget::Direct(target) => enqueue_for_wire(egress, ifacs, target, bytes),
        FrameTarget::Fan(fan) => {
            if let Some(supervisor) = lane.kind() {
                enqueue_broadcast_for_wire(egress, ifacs, supervisor, fan, bytes);
            }
        }
    }
}

pub(super) fn flush_due_pacers(
    pacers: &mut [InterfacePacer],
    now: InstantMillis,
    egress: &mut impl ManifoldEgress,
    ifacs: &[InterfaceIfac],
) {
    for entry in pacers.iter_mut() {
        let lane = entry.id;
        let _ = entry.pacer.release_due_tagged(now, |frame, target| {
            enqueue_paced_for_wire(egress, ifacs, lane, target, frame)
        });
    }
}

pub(super) fn soonest_pacer_release(pacers: &[InterfacePacer]) -> Option<InstantMillis> {
    pacers
        .iter()
        .filter_map(|entry| entry.pacer.next_release())
        .min_by_key(|deadline| deadline.0)
}

pub struct PooledEgress<const LANE_COUNT: usize> {
    pub(crate) lanes: HeaplessVec<(InterfaceId, &'static mut dyn ManifoldLaneWriter), LANE_COUNT>,
}

impl<const LANE_COUNT: usize> PooledEgress<LANE_COUNT> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            lanes: HeaplessVec::new(),
        }
    }

    pub(crate) fn push(
        &mut self,
        id: InterfaceId,
        producer: &'static mut dyn ManifoldLaneWriter,
    ) -> Result<(), &'static mut dyn ManifoldLaneWriter> {
        self.lanes
            .push((id, producer))
            .map_err(|(_, producer)| producer)
    }

    pub(crate) fn retag(&mut self, old_id: InterfaceId, new_id: InterfaceId) {
        for (id, _) in self.lanes.iter_mut() {
            if *id == old_id {
                *id = new_id;
            }
        }
    }
}

impl<const LANE_COUNT: usize> ManifoldEgress for PooledEgress<LANE_COUNT> {
    fn enqueue(&mut self, target: InterfaceId, bytes: &[u8]) -> EgressOutcome {
        for (id, producer) in self.lanes.iter_mut() {
            if lane_serves(*id, target) {
                return egress_outcome(*id, producer.try_write(FrameTarget::Direct(target), bytes));
            }
        }
        EgressOutcome::NoLane
    }

    fn enqueue_broadcast(
        &mut self,
        supervisor: InterfaceKind,
        fan: FanTarget,
        bytes: &[u8],
    ) -> EgressOutcome {
        for (id, producer) in self.lanes.iter_mut() {
            if id.kind() == Some(supervisor) {
                return egress_outcome(*id, producer.try_write(FrameTarget::Fan(fan), bytes));
            }
        }
        EgressOutcome::NoLane
    }

    fn lane_for(&self, target: InterfaceId) -> Option<InterfaceId> {
        self.lanes
            .iter()
            .map(|(id, _)| *id)
            .find(|id| lane_serves(*id, target))
    }

    fn fleet_lane(&self, supervisor: InterfaceKind) -> Option<InterfaceId> {
        self.lanes
            .iter()
            .map(|(id, _)| *id)
            .find(|id| id.kind() == Some(supervisor))
    }
}

impl<const LANE_COUNT: usize> Default for PooledEgress<LANE_COUNT> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests;