prns-runtime-embassy 0.3.4

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use core::future::Future;
use core::mem::MaybeUninit;

use embassy_futures::join::join;
use embassy_sync::blocking_mutex::raw::RawMutex;
use embassy_sync::channel::{Channel, Receiver};
use embedded_storage_async::nor_flash::NorFlash;
use heapless::Vec as HeaplessVec;
use static_cell::StaticCell;

use crate::engine::{IssuedCommand, Journaled, MAX_SEND_REQUEST_DATA_LEN};
use crate::interfaces::{InterfaceDescriptor, InterfaceId, InterfaceIfac};
use crate::manifold::driver::{
    run_pooled, InterfaceLifecycle, PooledEgress, PooledWiring, ResumableHost,
};
use crate::manifold::grant::ManifoldLaneReader;
use crate::manifold::Host;
use crate::storage::StorageLayout;

use super::super::request_endpoints::RequestEndpointSet;
use super::super::request_runner::{run_router, RunnerRequest};
use super::super::{
    EmbassyInterfaceStore, EmbeddedFlashPersistence, EmbeddedPersistenceDiagnostic,
    EmbeddedPersistenceRestoreReport, InterfaceInspectionStore, ManifoldPersistence,
    ManuallyAttached, NoInterfaceInspectionStore, NoManifoldPersistence, PreConfiguredDestination,
    PrnsEvent, PrnsNodeRecipe, RouteSnapshotKeys,
};
use super::command_handle::PrnsNodeHandle;
use prns_runtime::runtime::placement::assemble_node_in_place;
use prns_runtime::runtime::{assemble_node, AssembledNode, NoPersistence};

pub struct ManifoldWiring<
    M,
    const LANE_COUNT: usize,
    const NOTIFY: usize,
    const COMMANDS: usize,
    const LIFECYCLE: usize,
    const COMPLETIONS: usize,
> where
    M: RawMutex + 'static,
{
    pub(super) inbound: HeaplessVec<(InterfaceId, &'static mut dyn ManifoldLaneReader), LANE_COUNT>,
    pub(super) egress: PooledEgress<LANE_COUNT>,
    pub(super) initial: HeaplessVec<InterfaceDescriptor, LANE_COUNT>,
    pub(super) ifacs: HeaplessVec<InterfaceIfac, LANE_COUNT>,
    pub(super) notify: Receiver<'static, M, InterfaceId, NOTIFY>,
    pub(super) commands: Receiver<'static, M, IssuedCommand, COMMANDS>,
    pub(super) lifecycle: Receiver<'static, M, InterfaceLifecycle, LIFECYCLE>,
    pub(super) handle: PrnsNodeHandle<'static, M, COMMANDS, COMPLETIONS>,
}

pub struct PrnsNode<
    St,
    R,
    F,
    S,
    H,
    M,
    const LANE_COUNT: usize,
    const INTERFACE_CAPACITY: usize,
    const NOTIFY: usize,
    const COMMANDS: usize,
    const LIFECYCLE: usize,
    const COMPLETIONS: usize,
    const ROUTED_REQUESTS: usize = 4,
    const ROUTED_REQUEST_BYTES: usize = MAX_SEND_REQUEST_DATA_LEN,
> where
    S: StorageLayout,
    M: RawMutex + 'static,
{
    node: AssembledNode<St, R, F, S>,
    inbound: HeaplessVec<(InterfaceId, &'static mut dyn ManifoldLaneReader), LANE_COUNT>,
    egress: PooledEgress<LANE_COUNT>,
    notify: Receiver<'static, M, InterfaceId, NOTIFY>,
    commands: Receiver<'static, M, IssuedCommand, COMMANDS>,
    lifecycle: Receiver<'static, M, InterfaceLifecycle, LIFECYCLE>,
    handle: PrnsNodeHandle<'static, M, COMMANDS, COMPLETIONS>,
    host: H,
    descriptors: HeaplessVec<InterfaceDescriptor, INTERFACE_CAPACITY>,
    ifacs: HeaplessVec<InterfaceIfac, LANE_COUNT>,
}

pub struct RequestRoutingCapacity<const REQUESTS: usize, const REQUEST_BYTES: usize>;

impl<const REQUESTS: usize, const REQUEST_BYTES: usize> Default
    for RequestRoutingCapacity<REQUESTS, REQUEST_BYTES>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const REQUESTS: usize, const REQUEST_BYTES: usize>
    RequestRoutingCapacity<REQUESTS, REQUEST_BYTES>
{
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl<
        St,
        R,
        F,
        S,
        H,
        M,
        const LANE_COUNT: usize,
        const INTERFACE_CAPACITY: usize,
        const NOTIFY: usize,
        const COMMANDS: usize,
        const LIFECYCLE: usize,
        const COMPLETIONS: usize,
    >
    PrnsNode<
        St,
        R,
        F,
        S,
        H,
        M,
        LANE_COUNT,
        INTERFACE_CAPACITY,
        NOTIFY,
        COMMANDS,
        LIFECYCLE,
        COMPLETIONS,
        4,
        MAX_SEND_REQUEST_DATA_LEN,
    >
where
    R: RequestEndpointSet<St>,
    F: FnMut(PrnsEvent<'_>, &St),
    S: StorageLayout,
    H: Host,
    M: RawMutex + 'static,
{
    pub fn new<'d, D>(
        recipe: PrnsNodeRecipe<D, St, R, F, ManuallyAttached, S>,
        wiring: ManifoldWiring<M, LANE_COUNT, NOTIFY, COMMANDS, LIFECYCLE, COMPLETIONS>,
        host: H,
    ) -> Self
    where
        D: IntoIterator<Item = PreConfiguredDestination<'d>>,
    {
        Self::build(recipe, wiring, host)
    }
}

impl<
        St,
        R,
        F,
        S,
        H,
        M,
        const LANE_COUNT: usize,
        const INTERFACE_CAPACITY: usize,
        const NOTIFY: usize,
        const COMMANDS: usize,
        const LIFECYCLE: usize,
        const COMPLETIONS: usize,
        const ROUTED_REQUESTS: usize,
        const ROUTED_REQUEST_BYTES: usize,
    >
    PrnsNode<
        St,
        R,
        F,
        S,
        H,
        M,
        LANE_COUNT,
        INTERFACE_CAPACITY,
        NOTIFY,
        COMMANDS,
        LIFECYCLE,
        COMPLETIONS,
        ROUTED_REQUESTS,
        ROUTED_REQUEST_BYTES,
    >
where
    R: RequestEndpointSet<St>,
    F: FnMut(PrnsEvent<'_>, &St),
    S: StorageLayout,
    H: Host,
    M: RawMutex + 'static,
{
    pub fn init_static<'d, D>(
        cell: &'static StaticCell<Self>,
        recipe: PrnsNodeRecipe<D, St, R, F, ManuallyAttached, S>,
        wiring: ManifoldWiring<M, LANE_COUNT, NOTIFY, COMMANDS, LIFECYCLE, COMPLETIONS>,
        host: H,
    ) -> &'static mut Self
    where
        D: IntoIterator<Item = PreConfiguredDestination<'d>>,
    {
        let (node, NoPersistence) = Self::init_static_with_persistence(cell, recipe, wiring, host);
        node
    }

    #[expect(
        unsafe_code,
        clippy::undocumented_unsafe_blocks,
        clippy::mut_from_ref,
        reason = "every PrnsNode field is initialized before the slot is exposed"
    )]
    pub fn init_static_with_persistence<'d, D, P>(
        cell: &'static StaticCell<Self>,
        recipe: PrnsNodeRecipe<D, St, R, F, ManuallyAttached, S, P>,
        wiring: ManifoldWiring<M, LANE_COUNT, NOTIFY, COMMANDS, LIFECYCLE, COMPLETIONS>,
        host: H,
    ) -> (&'static mut Self, P)
    where
        D: IntoIterator<Item = PreConfiguredDestination<'d>>,
    {
        const {
            assert!(
                INTERFACE_CAPACITY >= LANE_COUNT,
                "PrnsNode INTERFACE_CAPACITY must cover every manifold lane"
            );
        }
        let slot = cell.uninit();
        let ManifoldWiring {
            inbound,
            egress,
            initial,
            ifacs,
            notify,
            commands,
            lifecycle,
            handle,
        } = wiring;
        let node = slot.as_mut_ptr();
        let persistence = unsafe {
            let assembled = &mut *core::ptr::addr_of_mut!((*node).node)
                .cast::<MaybeUninit<AssembledNode<St, R, F, S>>>();
            let (_, ManuallyAttached, persistence) = assemble_node_in_place(assembled, recipe);
            core::ptr::addr_of_mut!((*node).inbound).write(inbound);
            core::ptr::addr_of_mut!((*node).egress).write(egress);
            core::ptr::addr_of_mut!((*node).notify).write(notify);
            core::ptr::addr_of_mut!((*node).commands).write(commands);
            core::ptr::addr_of_mut!((*node).lifecycle).write(lifecycle);
            core::ptr::addr_of_mut!((*node).handle).write(handle);
            core::ptr::addr_of_mut!((*node).host).write(host);
            core::ptr::addr_of_mut!((*node).descriptors).write(HeaplessVec::new());
            core::ptr::addr_of_mut!((*node).ifacs).write(ifacs);
            persistence
        };
        let node = unsafe { slot.assume_init_mut() };
        for descriptor in initial {
            if node.descriptors.push(descriptor).is_err() {
                unreachable!()
            }
        }
        (node, persistence)
    }

    pub fn new_with_request_capacity<'d, D>(
        recipe: PrnsNodeRecipe<D, St, R, F, ManuallyAttached, S>,
        wiring: ManifoldWiring<M, LANE_COUNT, NOTIFY, COMMANDS, LIFECYCLE, COMPLETIONS>,
        host: H,
        _capacity: RequestRoutingCapacity<ROUTED_REQUESTS, ROUTED_REQUEST_BYTES>,
    ) -> Self
    where
        D: IntoIterator<Item = PreConfiguredDestination<'d>>,
    {
        Self::build(recipe, wiring, host)
    }

    fn build<'d, D>(
        recipe: PrnsNodeRecipe<D, St, R, F, ManuallyAttached, S>,
        wiring: ManifoldWiring<M, LANE_COUNT, NOTIFY, COMMANDS, LIFECYCLE, COMPLETIONS>,
        host: H,
    ) -> Self
    where
        D: IntoIterator<Item = PreConfiguredDestination<'d>>,
    {
        const {
            assert!(
                INTERFACE_CAPACITY >= LANE_COUNT,
                "PrnsNode INTERFACE_CAPACITY must cover every manifold lane"
            );
        }
        let (node, ManuallyAttached, NoPersistence) = assemble_node(recipe);
        let mut descriptors = HeaplessVec::new();
        for descriptor in wiring.initial {
            if descriptors.push(descriptor).is_err() {
                unreachable!()
            }
        }

        PrnsNode {
            node,
            inbound: wiring.inbound,
            egress: wiring.egress,
            notify: wiring.notify,
            commands: wiring.commands,
            lifecycle: wiring.lifecycle,
            handle: wiring.handle,
            host,
            descriptors,
            ifacs: wiring.ifacs,
        }
    }

    pub fn set_protocol_policy(&mut self, policy: crate::engine::EngineProtocolPolicy) {
        self.node.engine.set_protocol_policy(policy);
    }

    #[must_use]
    pub fn handle(&self) -> PrnsNodeHandle<'static, M, COMMANDS, COMPLETIONS> {
        self.handle
    }

    /// Runs the manifold with the caller's interface and supervisor tasks.
    pub async fn run(self, drive: impl Future<Output = ()>) {
        self.run_with_inspection_store(&NoInterfaceInspectionStore, drive)
            .await;
    }

    pub async fn run_with_interface_store<
        const INTERFACES: usize,
        const PACKET_PHY_CAPACITY: usize,
        const PACKET_PHY_INDEX_BUCKETS: usize,
    >(
        self,
        store: &EmbassyInterfaceStore<M, INTERFACES, PACKET_PHY_CAPACITY, PACKET_PHY_INDEX_BUCKETS>,
        drive: impl Future<Output = ()>,
    ) where
        M: Sync,
    {
        const {
            assert!(
                INTERFACES >= INTERFACE_CAPACITY,
                "EmbassyInterfaceStore INTERFACES must cover PrnsNode INTERFACE_CAPACITY"
            );
        }
        self.run_with_inspection_store(store, drive).await;
    }

    async fn run_with_inspection_store<Store>(self, store: &Store, drive: impl Future<Output = ()>)
    where
        Store: InterfaceInspectionStore,
    {
        let PrnsNode {
            node,
            mut inbound,
            mut egress,
            notify,
            commands,
            lifecycle,
            handle,
            mut host,
            mut descriptors,
            mut ifacs,
        } = self;
        let AssembledNode {
            mut engine,
            state,
            mut on_event,
            request_endpoints: _,
        } = node;
        let request_channel =
            Channel::<M, RunnerRequest<ROUTED_REQUEST_BYTES>, ROUTED_REQUESTS>::new();
        let request_sender = request_channel.sender();
        let mut persistence = NoManifoldPersistence;
        let manifold = run_pooled(
            &mut engine,
            &mut host,
            PooledWiring {
                descriptors: &mut descriptors,
                ifacs: &mut ifacs,
                inbound: &mut inbound,
                egress: &mut egress,
                notify,
                commands,
                lifecycle,
            },
            |journaled| {
                if let Journaled::CommandSettled { id, settlement } = &journaled {
                    if handle.settle(*id, settlement.clone()) {
                        return;
                    }
                }
                if let Some(request) = RunnerRequest::copy_from(&journaled) {
                    let _ = request_sender.try_send(request);
                }
                on_event(PrnsEvent::from(journaled), &state);
            },
            crate::manifold::decline_all(),
            store,
            &mut persistence,
        );
        let router =
            run_router::<St, R, M, COMMANDS, COMPLETIONS, ROUTED_REQUESTS, ROUTED_REQUEST_BYTES>(
                &state,
                request_channel.receiver(),
                handle,
            );
        join(join(manifold, router), drive).await;
    }

    /// Runs only the manifold for boards that schedule interfaces separately.
    pub async fn run_manifold(&mut self) {
        self.run_manifold_with_inspection_store(&NoInterfaceInspectionStore)
            .await;
    }

    pub async fn run_manifold_with_interface_store<
        const INTERFACES: usize,
        const PACKET_PHY_CAPACITY: usize,
        const PACKET_PHY_INDEX_BUCKETS: usize,
    >(
        &mut self,
        store: &EmbassyInterfaceStore<M, INTERFACES, PACKET_PHY_CAPACITY, PACKET_PHY_INDEX_BUCKETS>,
    ) where
        M: Sync,
    {
        const {
            assert!(
                INTERFACES >= INTERFACE_CAPACITY,
                "EmbassyInterfaceStore INTERFACES must cover PrnsNode INTERFACE_CAPACITY"
            );
        }
        self.run_manifold_with_inspection_store(store).await;
    }

    async fn run_manifold_with_inspection_store<Store>(&mut self, store: &Store)
    where
        Store: InterfaceInspectionStore,
    {
        let mut persistence = NoManifoldPersistence;
        self.run_manifold_with_inspection_store_and_persistence(store, &mut persistence)
            .await;
    }

    pub async fn run_manifold_with_persistence_and_interface_store<
        Fl,
        Keys,
        Observe,
        const PENDING: usize,
        const INTERFACES: usize,
        const PACKET_PHY_CAPACITY: usize,
        const PACKET_PHY_INDEX_BUCKETS: usize,
    >(
        &mut self,
        store: &EmbassyInterfaceStore<M, INTERFACES, PACKET_PHY_CAPACITY, PACKET_PHY_INDEX_BUCKETS>,
        persistence: &mut EmbeddedFlashPersistence<Fl, Keys, Observe, PENDING>,
    ) where
        M: Sync,
        Fl: NorFlash,
        Keys: RouteSnapshotKeys,
        Observe: FnMut(EmbeddedPersistenceDiagnostic),
    {
        const {
            assert!(
                INTERFACES >= INTERFACE_CAPACITY,
                "EmbassyInterfaceStore INTERFACES must cover PrnsNode INTERFACE_CAPACITY"
            );
        }
        self.run_manifold_with_inspection_store_and_persistence(store, persistence)
            .await;
    }

    pub async fn restore_embedded_persistence<Fl, Keys, Observe, const PENDING: usize>(
        &mut self,
        persistence: &mut EmbeddedFlashPersistence<Fl, Keys, Observe, PENDING>,
    ) -> EmbeddedPersistenceRestoreReport
    where
        Fl: NorFlash,
        Keys: RouteSnapshotKeys,
        Observe: FnMut(EmbeddedPersistenceDiagnostic),
        H: ResumableHost,
    {
        let report = persistence
            .restore(&mut self.node.engine, self.host.now())
            .await;
        self.host.resume_at(report.logical_start);
        report
    }

    async fn run_manifold_with_inspection_store_and_persistence<Store, P>(
        &mut self,
        store: &Store,
        persistence: &mut P,
    ) where
        Store: InterfaceInspectionStore,
        P: ManifoldPersistence<S>,
    {
        let PrnsNode {
            node,
            inbound,
            egress,
            notify,
            commands,
            lifecycle,
            handle,
            host,
            descriptors,
            ifacs,
        } = self;
        let AssembledNode {
            engine,
            state,
            on_event,
            request_endpoints: _,
        } = node;
        let request_channel =
            Channel::<M, RunnerRequest<ROUTED_REQUEST_BYTES>, ROUTED_REQUESTS>::new();
        let request_sender = request_channel.sender();
        let manifold = run_pooled(
            engine,
            host,
            PooledWiring {
                descriptors,
                ifacs,
                inbound,
                egress,
                notify: *notify,
                commands: *commands,
                lifecycle: *lifecycle,
            },
            |journaled| {
                if let Journaled::CommandSettled { id, settlement } = &journaled {
                    if handle.settle(*id, settlement.clone()) {
                        return;
                    }
                }
                if let Some(request) = RunnerRequest::copy_from(&journaled) {
                    let _ = request_sender.try_send(request);
                }
                on_event(PrnsEvent::from(journaled), state);
            },
            crate::manifold::decline_all(),
            store,
            persistence,
        );
        let router =
            run_router::<St, R, M, COMMANDS, COMPLETIONS, ROUTED_REQUESTS, ROUTED_REQUEST_BYTES>(
                state,
                request_channel.receiver(),
                *handle,
            );
        join(manifold, router).await;
    }
}

#[cfg(test)]
mod tests;