postcard-rpc 0.10.4

A no_std + serde compatible RPC library for Rust
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! A postcard-rpc host client
//!
//! This library is meant to be used with the `Dispatch` type and the
//! postcard-rpc wire protocol.

use core::time::Duration;
use std::{
    collections::HashSet,
    future::Future,
    marker::PhantomData,
    sync::{
        atomic::{AtomicU32, Ordering},
        Arc, RwLock,
    },
};

use maitake_sync::{
    wait_map::{WaitError, WakeOutcome},
    WaitMap,
};
use postcard_schema::{schema::owned::OwnedNamedType, Schema};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tokio::{
    select,
    sync::{
        mpsc::{Receiver, Sender},
        Mutex,
    },
};
use util::Subscriptions;

use crate::{
    header::{VarHeader, VarKey, VarKeyKind, VarSeq, VarSeqKind},
    standard_icd::{GetAllSchemaDataTopic, GetAllSchemasEndpoint, OwnedSchemaData},
    Endpoint, Key, Topic, TopicDirection,
};

use self::util::Stopper;

#[cfg(all(feature = "raw-nusb", not(target_family = "wasm")))]
mod raw_nusb;

#[cfg(all(feature = "cobs-serial", not(target_family = "wasm")))]
mod serial;

#[cfg(all(feature = "webusb", target_family = "wasm"))]
pub mod webusb;

pub(crate) mod util;

#[cfg(feature = "test-utils")]
pub mod test_channels;

/// Host Error Kind
#[derive(Debug, PartialEq)]
pub enum HostErr<WireErr> {
    /// An error of the user-specified wire error type
    Wire(WireErr),
    /// We got a response that didn't match the expected value or the
    /// user specified wire error type
    BadResponse,
    /// Deserialization of the message failed
    Postcard(postcard::Error),
    /// The interface has been closed, and no further messages are possible
    Closed,
}

impl<T> From<postcard::Error> for HostErr<T> {
    fn from(value: postcard::Error) -> Self {
        Self::Postcard(value)
    }
}

impl<T> From<WaitError> for HostErr<T> {
    fn from(_: WaitError) -> Self {
        Self::Closed
    }
}

/// Wire Transmit Interface
///
/// Responsible for taking a serialized frame (including header and payload),
/// performing any further encoding if necessary, and transmitting to the device.
///
/// Should complete once the message is fully sent (e.g. not just enqueued)
/// if possible.
///
/// All errors are treated as fatal - resolvable or ignorable errors should not
/// be returned to the caller.
#[cfg(target_family = "wasm")]
pub trait WireTx: 'static {
    /// Transmit error type
    type Error: std::error::Error;
    /// Send a single frame
    fn send(&mut self, data: Vec<u8>) -> impl Future<Output = Result<(), Self::Error>>;
}

/// Wire Receive Interface
///
/// Responsible for accumulating a serialized frame (including header and payload),
/// performing any further decoding if necessary, and returning to the caller.
///
/// All errors are treated as fatal - resolvable or ignorable errors should not
/// be returned to the caller.
#[cfg(target_family = "wasm")]
pub trait WireRx: 'static {
    /// Receive error type
    type Error: std::error::Error; // or std?
    /// Receive a single frame
    fn receive(&mut self) -> impl Future<Output = Result<Vec<u8>, Self::Error>>;
}

/// Wire Spawn Interface
///
/// Should be suitable for spawning a task in the host executor.
#[cfg(target_family = "wasm")]
pub trait WireSpawn: 'static {
    /// Spawn a task
    fn spawn(&mut self, fut: impl Future<Output = ()> + 'static);
}

/// Wire Transmit Interface
///
/// Responsible for taking a serialized frame (including header and payload),
/// performing any further encoding if necessary, and transmitting to the device.
///
/// Should complete once the message is fully sent (e.g. not just enqueued)
/// if possible.
///
/// All errors are treated as fatal - resolvable or ignorable errors should not
/// be returned to the caller.
#[cfg(not(target_family = "wasm"))]
pub trait WireTx: Send + 'static {
    /// Transmit error type
    type Error: std::error::Error;
    /// Send a single frame
    fn send(&mut self, data: Vec<u8>) -> impl Future<Output = Result<(), Self::Error>> + Send;
}

/// Wire Receive Interface
///
/// Responsible for accumulating a serialized frame (including header and payload),
/// performing any further decoding if necessary, and returning to the caller.
///
/// All errors are treated as fatal - resolvable or ignorable errors should not
/// be returned to the caller.
#[cfg(not(target_family = "wasm"))]
pub trait WireRx: Send + 'static {
    /// Receive error type
    type Error: std::error::Error;
    /// Receive a single frame
    fn receive(&mut self) -> impl Future<Output = Result<Vec<u8>, Self::Error>> + Send;
}

/// Wire Spawn Interface
///
/// Should be suitable for spawning a task in the host executor.
#[cfg(not(target_family = "wasm"))]
pub trait WireSpawn: 'static {
    /// Spawn a task
    fn spawn(&mut self, fut: impl Future<Output = ()> + Send + 'static);
}

/// The [HostClient] is the primary PC-side interface.
///
/// It is generic over a single type, `WireErr`, which can be used by the
/// embedded system when a request was not understood, or some other error
/// has occurred.
///
/// [HostClient]s can be cloned, and used across multiple tasks/threads.
///
/// There are currently two ways to create one, based on the transport used:
///
/// 1. With raw USB Bulk transfers: [`HostClient::new_raw_nusb()`] (**recommended**)
/// 2. With cobs CDC-ACM transfers: [`HostClient::new_serial_cobs()`]
pub struct HostClient<WireErr> {
    ctx: Arc<HostContext>,
    out: Sender<RpcFrame>,
    subscriptions: Arc<Mutex<Subscriptions>>,
    err_key: Key,
    stopper: Stopper,
    seq_kind: VarSeqKind,
    _pd: PhantomData<fn() -> WireErr>,
}

/// # Constructor Methods
impl<WireErr> HostClient<WireErr>
where
    WireErr: DeserializeOwned + Schema,
{
    /// Private method for creating internal context
    pub(crate) fn new_manual_priv(
        err_uri_path: &str,
        outgoing_depth: usize,
        seq_kind: VarSeqKind,
    ) -> (Self, WireContext) {
        let (tx_pc, rx_pc) = tokio::sync::mpsc::channel(outgoing_depth);

        let ctx = Arc::new(HostContext {
            kkind: RwLock::new(VarKeyKind::Key8),
            map: WaitMap::new(),
            seq: AtomicU32::new(0),
        });

        let err_key = Key::for_path::<WireErr>(err_uri_path);

        let me = HostClient {
            ctx: ctx.clone(),
            out: tx_pc,
            err_key,
            _pd: PhantomData,
            subscriptions: Arc::new(Mutex::new(Subscriptions::default())),
            stopper: Stopper::new(),
            seq_kind,
        };

        let wire = WireContext {
            outgoing: rx_pc,
            incoming: ctx,
        };

        (me, wire)
    }
}

/// Errors related to retrieving the schema
#[derive(Debug)]
pub enum SchemaError<WireErr> {
    /// Some kind of communication error occurred
    Comms(HostErr<WireErr>),
    /// An error occurred internally. Please open an issue.
    TaskError,
    /// Invalid report data was received, including endpoints or
    /// tasks that referred to unknown types. Please open an issue
    InvalidReportData,
    /// Data was lost while transmitting. If a retry does not solve
    /// this, please open an issue.
    LostData,
}

impl<WireErr> From<UnableToFindType> for SchemaError<WireErr> {
    fn from(_: UnableToFindType) -> Self {
        Self::InvalidReportData
    }
}

/// # Interface Methods
impl<WireErr> HostClient<WireErr>
where
    WireErr: DeserializeOwned + Schema,
{
    /// Obtain a [`SchemaReport`] describing the connected device
    pub async fn get_schema_report(&self) -> Result<SchemaReport, SchemaError<WireErr>> {
        let Ok(mut sub) = self.subscribe::<GetAllSchemaDataTopic>(64).await else {
            return Err(SchemaError::Comms(HostErr::Closed));
        };

        let collect_task = tokio::task::spawn({
            async move {
                let mut got = vec![];
                while let Ok(Some(val)) =
                    tokio::time::timeout(Duration::from_millis(100), sub.recv()).await
                {
                    got.push(val);
                }
                got
            }
        });
        let trigger_task = self.send_resp::<GetAllSchemasEndpoint>(&()).await;
        let data = collect_task.await;
        let (resp, data) = match (trigger_task, data) {
            (Ok(a), Ok(b)) => (a, b),
            (Ok(_), Err(_)) => return Err(SchemaError::TaskError),
            (Err(e), Ok(_)) => return Err(SchemaError::Comms(e)),
            (Err(e1), Err(_e2)) => return Err(SchemaError::Comms(e1)),
        };
        let mut rpt = SchemaReport::default();
        let mut e_and_t = vec![];

        for d in data {
            match d {
                OwnedSchemaData::Type(d) => {
                    rpt.add_type(d);
                }
                e @ OwnedSchemaData::Endpoint { .. } => e_and_t.push(e),
                t @ OwnedSchemaData::Topic { .. } => e_and_t.push(t),
            }
        }

        for e in e_and_t {
            match e {
                OwnedSchemaData::Type(_) => unreachable!(),
                OwnedSchemaData::Endpoint {
                    path,
                    request_key,
                    response_key,
                } => {
                    rpt.add_endpoint(path, request_key, response_key)?;
                }
                OwnedSchemaData::Topic {
                    path,
                    key,
                    direction,
                } => match direction {
                    TopicDirection::ToServer => rpt.add_topic_in(path, key)?,
                    TopicDirection::ToClient => rpt.add_topic_out(path, key)?,
                },
            }
        }

        let mut data_matches = true;
        data_matches &= resp.endpoints_sent as usize == rpt.endpoints.len();
        data_matches &= resp.topics_in_sent as usize == rpt.topics_in.len();
        data_matches &= resp.topics_out_sent as usize == rpt.topics_out.len();
        data_matches &= resp.errors == 0;

        if data_matches {
            // TODO: filter primitive types out?
            Ok(rpt)
        } else {
            Err(SchemaError::LostData)
        }
    }

    /// Send a message of type [Endpoint::Request][Endpoint] to `path`, and await
    /// a response of type [Endpoint::Response][Endpoint] (or WireErr) to `path`.
    ///
    /// This function will wait potentially forever. Consider using with a timeout.
    pub async fn send_resp<E: Endpoint>(
        &self,
        t: &E::Request,
    ) -> Result<E::Response, HostErr<WireErr>>
    where
        E::Request: Serialize + Schema,
        E::Response: DeserializeOwned + Schema,
    {
        let seq_no = self.ctx.seq.fetch_add(1, Ordering::Relaxed);

        let msg = postcard::to_stdvec(&t).expect("Allocations should not ever fail");
        let frame = RpcFrame {
            // NOTE: send_resp_raw automatically shrinks down key and sequence
            // kinds to the appropriate amount
            header: VarHeader {
                key: VarKey::Key8(E::REQ_KEY),
                seq_no: VarSeq::Seq4(seq_no),
            },
            body: msg,
        };
        let frame = self.send_resp_raw(frame, E::RESP_KEY).await?;
        let r = postcard::from_bytes::<E::Response>(&frame.body)?;
        Ok(r)
    }

    /// Perform an endpoint request/response,but without handling the
    /// Ser/De automatically
    pub async fn send_resp_raw(
        &self,
        mut rqst: RpcFrame,
        resp_key: Key,
    ) -> Result<RpcFrame, HostErr<WireErr>> {
        let cancel_fut = self.stopper.wait_stopped();
        let kkind: VarKeyKind = *self.ctx.kkind.read().unwrap();
        rqst.header.key.shrink_to(kkind);
        rqst.header.seq_no.resize(self.seq_kind);
        let mut resp_key = VarKey::Key8(resp_key);
        let mut err_key = VarKey::Key8(self.err_key);
        resp_key.shrink_to(kkind);
        err_key.shrink_to(kkind);

        // TODO: Do I need something like a .subscribe method to ensure this is enqueued?
        let ok_resp = self.ctx.map.wait(VarHeader {
            seq_no: rqst.header.seq_no,
            key: resp_key,
        });
        let err_resp = self.ctx.map.wait(VarHeader {
            seq_no: rqst.header.seq_no,
            key: err_key,
        });
        self.out.send(rqst).await.map_err(|_| HostErr::Closed)?;

        select! {
            _c = cancel_fut => Err(HostErr::Closed),
            o = ok_resp => {
                let (hdr, resp) = o?;
                if hdr.key.kind() != kkind {
                    *self.ctx.kkind.write().unwrap() = hdr.key.kind();
                }
                Ok(RpcFrame { header: hdr, body: resp })
            },
            e = err_resp => {
                let (hdr, resp) = e?;
                if hdr.key.kind() != kkind {
                    *self.ctx.kkind.write().unwrap() = hdr.key.kind();
                }
                let r = postcard::from_bytes::<WireErr>(&resp)?;
                Err(HostErr::Wire(r))
            },
        }
    }

    /// Publish a [Topic] [Message][Topic::Message].
    ///
    /// There is no feedback if the server received our message. If the I/O worker is
    /// closed, an error is returned.
    pub async fn publish<T: Topic>(&self, seq_no: VarSeq, msg: &T::Message) -> Result<(), IoClosed>
    where
        T::Message: Serialize,
    {
        let smsg = postcard::to_stdvec(msg).expect("alloc should never fail");
        let frame = RpcFrame {
            header: VarHeader {
                key: VarKey::Key8(T::TOPIC_KEY),
                seq_no,
            },
            body: smsg,
        };
        self.publish_raw(frame).await
    }

    /// Publish the given raw frame
    pub async fn publish_raw(&self, mut frame: RpcFrame) -> Result<(), IoClosed> {
        let kkind: VarKeyKind = *self.ctx.kkind.read().unwrap();
        frame.header.key.shrink_to(kkind);
        frame.header.seq_no.resize(self.seq_kind);

        let cancel_fut = self.stopper.wait_stopped();
        let operate_fut = self.out.send(frame);

        select! {
            _ = cancel_fut => Err(IoClosed),
            res = operate_fut => res.map_err(|_| IoClosed),
        }
    }

    /// Begin listening to a [Topic], receiving a [Subscription] that will give a
    /// stream of [Message][Topic::Message]s.
    ///
    /// If you subscribe to the same topic multiple times, the previous subscription
    /// will be closed (there can be only one).
    ///
    /// Returns an Error if the I/O worker is closed.
    pub async fn subscribe<T: Topic>(
        &self,
        depth: usize,
    ) -> Result<Subscription<T::Message>, IoClosed>
    where
        T::Message: DeserializeOwned,
    {
        let cancel_fut = self.stopper.wait_stopped();
        let operate_fut = self.subscribe_inner::<T>(depth);
        select! {
            _ = cancel_fut => Err(IoClosed),
            res = operate_fut => res,
        }
    }

    /// Inner function version of [Self::subscribe]
    async fn subscribe_inner<T: Topic>(
        &self,
        depth: usize,
    ) -> Result<Subscription<T::Message>, IoClosed>
    where
        T::Message: DeserializeOwned,
    {
        let (tx, rx) = tokio::sync::mpsc::channel(depth);
        {
            let mut guard = self.subscriptions.lock().await;
            if guard.stopped {
                return Err(IoClosed);
            }
            if let Some(entry) = guard.list.iter_mut().find(|(k, _)| *k == T::TOPIC_KEY) {
                tracing::warn!("replacing subscription for topic path '{}'", T::PATH);
                entry.1 = tx;
            } else {
                guard.list.push((T::TOPIC_KEY, tx));
            }
        }
        Ok(Subscription {
            rx,
            _pd: PhantomData,
        })
    }

    /// Subscribe to the given [`Key`], without automatically handling deserialization
    pub async fn subscribe_raw(&self, key: Key, depth: usize) -> Result<RawSubscription, IoClosed> {
        let cancel_fut = self.stopper.wait_stopped();
        let operate_fut = self.subscribe_inner_raw(key, depth);
        select! {
            _ = cancel_fut => Err(IoClosed),
            res = operate_fut => res,
        }
    }

    /// Inner function version of [Self::subscribe]
    async fn subscribe_inner_raw(
        &self,
        key: Key,
        depth: usize,
    ) -> Result<RawSubscription, IoClosed> {
        let (tx, rx) = tokio::sync::mpsc::channel(depth);
        {
            let mut guard = self.subscriptions.lock().await;
            if guard.stopped {
                return Err(IoClosed);
            }
            if let Some(entry) = guard.list.iter_mut().find(|(k, _)| *k == key) {
                tracing::warn!("replacing subscription for raw topic key '{:?}'", key);
                entry.1 = tx;
            } else {
                guard.list.push((key, tx));
            }
        }
        Ok(RawSubscription { rx })
    }

    /// Permanently close the connection to the client
    ///
    /// All other HostClients sharing the connection (e.g. created by cloning
    /// a single HostClient) will also stop, and no further communication will
    /// succeed. The in-flight messages will not be flushed.
    ///
    /// This will also signal any I/O worker tasks to halt immediately as well.
    pub fn close(&self) {
        self.stopper.stop()
    }

    /// Has this host client been closed?
    pub fn is_closed(&self) -> bool {
        self.stopper.is_stopped()
    }

    /// Wait for the host client to be closed
    pub async fn wait_closed(&self) {
        self.stopper.wait_stopped().await;
    }
}

/// Like Subscription, but receives Raw frames that are not
/// automatically deserialized
pub struct RawSubscription {
    rx: Receiver<RpcFrame>,
}

impl RawSubscription {
    /// Await a message for the given subscription.
    ///
    /// Returns [None]` if the subscription was closed
    pub async fn recv(&mut self) -> Option<RpcFrame> {
        self.rx.recv().await
    }
}

/// A structure that represents a subscription to the given topic
pub struct Subscription<M> {
    rx: Receiver<RpcFrame>,
    _pd: PhantomData<M>,
}

impl<M> Subscription<M>
where
    M: DeserializeOwned,
{
    /// Await a message for the given subscription.
    ///
    /// Returns [None]` if the subscription was closed
    pub async fn recv(&mut self) -> Option<M> {
        loop {
            let frame = self.rx.recv().await?;
            if let Ok(m) = postcard::from_bytes(&frame.body) {
                return Some(m);
            }
        }
    }
}

// Manual Clone impl because WireErr may not impl Clone
impl<WireErr> Clone for HostClient<WireErr> {
    fn clone(&self) -> Self {
        Self {
            ctx: self.ctx.clone(),
            out: self.out.clone(),
            err_key: self.err_key,
            _pd: PhantomData,
            subscriptions: self.subscriptions.clone(),
            stopper: self.stopper.clone(),
            seq_kind: self.seq_kind,
        }
    }
}

/// Items necessary for implementing a custom I/O Task
pub struct WireContext {
    /// This is a stream of frames that should be placed on the
    /// wire towards the server.
    pub outgoing: Receiver<RpcFrame>,
    /// This shared information contains the WaitMap used for replying to
    /// open requests.
    pub incoming: Arc<HostContext>,
}

/// A single postcard-rpc frame
pub struct RpcFrame {
    /// The wire header
    pub header: VarHeader,
    /// The serialized message payload
    pub body: Vec<u8>,
}

impl RpcFrame {
    /// Serialize the `RpcFrame` into a Vec of bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = self.header.write_to_vec();
        out.extend_from_slice(&self.body);
        out
    }
}

/// Shared context between [HostClient] and the I/O worker task
pub struct HostContext {
    kkind: RwLock<VarKeyKind>,
    map: WaitMap<VarHeader, (VarHeader, Vec<u8>)>,
    seq: AtomicU32,
}

/// The I/O worker has closed.
#[derive(Debug)]
pub struct IoClosed;

/// Error for [HostContext::process].
#[derive(Debug, PartialEq)]
pub enum ProcessError {
    /// All [HostClient]s have been dropped, no further requests
    /// will be made and no responses will be processed.
    Closed,
}

impl HostContext {
    /// Like `HostContext::process` but tells you if we processed the message or
    /// nobody wanted it
    pub fn process_did_wake(&self, frame: RpcFrame) -> Result<bool, ProcessError> {
        match self.map.wake(&frame.header, (frame.header, frame.body)) {
            WakeOutcome::Woke => Ok(true),
            WakeOutcome::NoMatch(_) => Ok(false),
            WakeOutcome::Closed(_) => Err(ProcessError::Closed),
        }
    }

    /// Process the message, returns Ok if the message was taken or dropped.
    ///
    /// Returns an Err if the map was closed.
    pub fn process(&self, frame: RpcFrame) -> Result<(), ProcessError> {
        if let WakeOutcome::Closed(_) = self.map.wake(&frame.header, (frame.header, frame.body)) {
            Err(ProcessError::Closed)
        } else {
            Ok(())
        }
    }
}

/// A report describing the schema spoken by the connected device
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Schema)]
pub struct SchemaReport {
    /// All custom types spoken by the device (on any endpoint or topic),
    /// as well as all primitive types. In the future, primitive types may
    /// be removed.
    pub types: HashSet<OwnedNamedType>,
    /// All incoming (client to server) topics reported by the device
    pub topics_in: Vec<TopicReport>,
    /// All outgoing (server to client) topics reported by the device
    pub topics_out: Vec<TopicReport>,
    /// All endpoints reported by the device
    pub endpoints: Vec<EndpointReport>,
}

impl Default for SchemaReport {
    fn default() -> Self {
        let mut me = Self {
            types: Default::default(),
            topics_in: Default::default(),
            topics_out: Default::default(),
            endpoints: Default::default(),
        };

        // We need to pre-populate all of the types we consider primitives:
        // DataModelType::Bool
        me.add_type(OwnedNamedType::from(<bool as Schema>::SCHEMA));
        // DataModelType::I8
        me.add_type(OwnedNamedType::from(<i8 as Schema>::SCHEMA));
        // DataModelType::U8
        me.add_type(OwnedNamedType::from(<u8 as Schema>::SCHEMA));
        // DataModelType::I16
        me.add_type(OwnedNamedType::from(<i16 as Schema>::SCHEMA));
        // DataModelType::I32
        me.add_type(OwnedNamedType::from(<i32 as Schema>::SCHEMA));
        // DataModelType::I64
        me.add_type(OwnedNamedType::from(<i64 as Schema>::SCHEMA));
        // DataModelType::I128
        me.add_type(OwnedNamedType::from(<i128 as Schema>::SCHEMA));
        // DataModelType::U16
        me.add_type(OwnedNamedType::from(<u16 as Schema>::SCHEMA));
        // DataModelType::U32
        me.add_type(OwnedNamedType::from(<u32 as Schema>::SCHEMA));
        // DataModelType::U64
        me.add_type(OwnedNamedType::from(<u64 as Schema>::SCHEMA));
        // DataModelType::U128
        me.add_type(OwnedNamedType::from(<u128 as Schema>::SCHEMA));
        // // DataModelType::Usize
        // me.add_type(OwnedNamedType::from(<usize as Schema>::SCHEMA));
        // // DataModelType::Isize
        // me.add_type(OwnedNamedType::from(<isize as Schema>::SCHEMA));
        // DataModelType::F32
        me.add_type(OwnedNamedType::from(<f32 as Schema>::SCHEMA));
        // DataModelType::F64
        me.add_type(OwnedNamedType::from(<f64 as Schema>::SCHEMA));
        // DataModelType::Char
        me.add_type(OwnedNamedType::from(<char as Schema>::SCHEMA));
        // DataModelType::String
        me.add_type(OwnedNamedType::from(<String as Schema>::SCHEMA));
        // DataModelType::ByteArray
        me.add_type(OwnedNamedType::from(<Vec<u8> as Schema>::SCHEMA));
        // DataModelType::Unit
        me.add_type(OwnedNamedType::from(<() as Schema>::SCHEMA));
        // DataModelType::Schema
        me.add_type(OwnedNamedType::from(<OwnedNamedType as Schema>::SCHEMA));

        me
    }
}

/// A description of a single Topic
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Schema)]
pub struct TopicReport {
    /// The human readable path of the topic
    pub path: String,
    /// The Key of the topic (which hashes the path and type)
    pub key: Key,
    /// The schema of the type of the message
    pub ty: OwnedNamedType,
}

/// A description of a single Endpoint
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Schema)]
pub struct EndpointReport {
    /// The human readable path of the endpoint
    pub path: String,
    /// The Key of the request (which hashes the path and type)
    pub req_key: Key,
    /// The schema of the request type
    pub req_ty: OwnedNamedType,
    /// The Key of the response (which hashes the path and type)
    pub resp_key: Key,
    /// The schema of the response type
    pub resp_ty: OwnedNamedType,
}

/// An error that denotes we were unable to resolve the type used by a given key
#[derive(Debug)]
pub struct UnableToFindType;

impl SchemaReport {
    /// Insert a new type
    pub fn add_type(&mut self, t: OwnedNamedType) {
        self.types.insert(t);
    }

    /// Insert a new incoming (client to server) topic
    ///
    /// Returns an error if we are unable to find the type used for this topic
    pub fn add_topic_in(&mut self, path: String, key: Key) -> Result<(), UnableToFindType> {
        // We need to figure out which type goes with this topic
        for ty in self.types.iter() {
            let calc_key = Key::for_owned_schema_path(&path, ty);
            if calc_key == key {
                self.topics_in.push(TopicReport {
                    path,
                    key,
                    ty: ty.clone(),
                });
                return Ok(());
            }
        }
        Err(UnableToFindType)
    }

    /// Insert a new outgoing (server to client) topic
    ///
    /// Returns an error if we are unable to find the type used for this topic
    pub fn add_topic_out(&mut self, path: String, key: Key) -> Result<(), UnableToFindType> {
        // We need to figure out which type goes with this topic
        for ty in self.types.iter() {
            let calc_key = Key::for_owned_schema_path(&path, ty);
            if calc_key == key {
                self.topics_out.push(TopicReport {
                    path,
                    key,
                    ty: ty.clone(),
                });
                return Ok(());
            }
        }
        Err(UnableToFindType)
    }

    /// Insert a new endpoint
    ///
    /// Returns an error if we are unable to find the type used for the request/response
    pub fn add_endpoint(
        &mut self,
        path: String,
        req_key: Key,
        resp_key: Key,
    ) -> Result<(), UnableToFindType> {
        // We need to figure out which types go with this endpoint
        let mut req_ty = None;
        for ty in self.types.iter() {
            let calc_key = Key::for_owned_schema_path(&path, ty);
            if calc_key == req_key {
                req_ty = Some(ty.clone());
                break;
            }
        }
        let Some(req_ty) = req_ty else {
            return Err(UnableToFindType);
        };

        let mut resp_ty = None;
        for ty in self.types.iter() {
            let calc_key = Key::for_owned_schema_path(&path, ty);
            if calc_key == resp_key {
                resp_ty = Some(ty.clone());
                break;
            }
        }
        let Some(resp_ty) = resp_ty else {
            return Err(UnableToFindType);
        };

        self.endpoints.push(EndpointReport {
            path,
            req_key,
            req_ty,
            resp_key,
            resp_ty,
        });
        Ok(())
    }
}