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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
#![allow(missing_docs)]

use crate::compat::borrow::Cow;
use crate::compat::rand;
use crate::compat::vec::Vec;
use crate::errcode::{Kind, Origin};
use crate::Result;
use core::fmt::{self, Display, Formatter};
use minicbor::encode::{self, Encoder, Write};
use minicbor::{Decode, Decoder, Encode};
use tinyvec::ArrayVec;

pub const SCHEMA: &str = core::include_str!("schema.cddl");

#[cfg(feature = "tag")]
use {
    crate::TypeTag,
    alloc::collections::btree_map::Entry,
    cddl_cat::{context::BasicContext, flatten::flatten, parse_cddl},
    once_cell::race::OnceBox,
};

#[cfg(feature = "tag")]
pub fn merged_cddl(cddl_schemas: &[&str]) -> Result<BasicContext> {
    fn schema(cddl_schema: &str) -> Result<BasicContext> {
        let cddl =
            parse_cddl(cddl_schema).map_err(|e| crate::Error::new(Origin::Core, Kind::Io, e))?;
        let cddl = flatten(&cddl).map_err(|e| crate::Error::new(Origin::Core, Kind::Io, e))?;
        Ok(BasicContext::new(cddl))
    }

    let merged_schema = [&[SCHEMA], cddl_schemas].concat();
    if let Some(merged_cddl) = merged_schema
        .iter()
        .map(|schema_str| schema(schema_str))
        .reduce(|acc, cddl| {
            let mut ctx = acc?;
            for (k, v) in cddl?.rules {
                match ctx.rules.entry(k) {
                    Entry::Vacant(e) => {
                        e.insert(v);
                    }
                    Entry::Occupied(e) => {
                        return Err(crate::Error::new(
                            Origin::Core,
                            Kind::AlreadyExists,
                            format!("CDDL files contain duplicate keys: {}", e.key()),
                        ));
                    }
                }
            }
            Ok(ctx)
        })
    {
        merged_cddl
    } else {
        Err(crate::Error::new(
            Origin::Core,
            Kind::Io,
            "No valid CDDL schema provided".to_string(),
        ))
    }
}

#[cfg(feature = "tag")]
pub fn cddl() -> &'static BasicContext {
    static INSTANCE: OnceBox<BasicContext> = OnceBox::new();
    INSTANCE.get_or_init(|| Box::new(merged_cddl(&[]).unwrap()))
}

/// A request header.
#[derive(Debug, Clone, Encode, Decode)]
#[rustfmt::skip]
#[cbor(map)]
pub struct Request<'a> {
    /// Nominal type tag.
    ///
    /// If the "tag" feature is enabled, the resulting CBOR will contain a
    /// unique numeric value that identifies this type to help catching type
    /// errors. Otherwise this tag will not be produced and is ignored during
    /// decoding if present.
    #[cfg(feature = "tag")]
    #[n(0)] tag: TypeTag<7586022>,
    /// The request identifier.
    #[n(1)] id: Id,
    /// The resource path.
    #[b(2)] path: Cow<'a, str>,
    /// The request method.
    ///
    /// It is wrapped in an `Option` to be forwards compatible, i.e. adding
    /// methods will not cause decoding errors and client code can decide
    /// how to handle unknown methods.
    #[n(3)] method: Option<Method>,
    /// Indicator if a request body is expected after this header.
    #[n(4)] has_body: bool,
}

/// The response header.
#[derive(Debug, Clone, Encode, Decode)]
#[rustfmt::skip]
#[cbor(map)]
pub struct Response {
    /// Nominal type tag.
    ///
    /// If the "tag" feature is enabled, the resulting CBOR will contain a
    /// unique numeric value that identifies this type to help catching type
    /// errors. Otherwise this tag will not be produced and is ignored during
    /// decoding if present.
    #[cfg(feature = "tag")]
    #[n(0)] tag: TypeTag<9750358>,
    /// The response identifier.
    #[n(1)] id: Id,
    /// The identifier of the request corresponding to this response.
    #[n(2)] re: Id,
    /// A status code.
    ///
    /// It is wrapped in an `Option` to be forwards compatible, i.e. adding
    /// status codes will not cause decoding errors and client code can decide
    /// how to handle unknown codes.
    #[n(3)] status: Option<Status>,
    /// Indicator if a response body is expected after this header.
    #[n(4)] has_body: bool,
}

/// Create an error response because the request path was unknown.
pub fn unknown_path<'a>(r: &'a Request) -> ResponseBuilder<Error<'a>> {
    bad_request(r, "unknown path")
}

/// Create an error response because the request method was unknown or not allowed.
pub fn invalid_method<'a>(r: &'a Request) -> ResponseBuilder<Error<'a>> {
    match r.method() {
        Some(m) => {
            let e = Error::new(r.path()).with_method(m);
            Response::builder(r.id(), Status::MethodNotAllowed).body(e)
        }
        None => {
            let e = Error::new(r.path()).with_message("unknown method");
            Response::not_implemented(r.id()).body(e)
        }
    }
}

/// Create an error response with status forbidden and the given message.
pub fn forbidden<'a>(r: &'a Request, m: &'a str) -> ResponseBuilder<Error<'a>> {
    let mut e = Error::new(r.path()).with_message(m);
    if let Some(m) = r.method() {
        e = e.with_method(m)
    }
    Response::builder(r.id(), Status::Forbidden).body(e)
}

/// Create a generic bad request response.
pub fn bad_request<'a>(r: &'a Request, msg: &'a str) -> ResponseBuilder<Error<'a>> {
    let mut e = Error::new(r.path()).with_message(msg);
    if let Some(m) = r.method() {
        e = e.with_method(m)
    }
    Response::bad_request(r.id()).body(e)
}

/// Create an internal server error response
pub fn internal_error<'a>(r: &'a Request, msg: &'a str) -> ResponseBuilder<Error<'a>> {
    let mut e = Error::new(r.path()).with_message(msg);
    if let Some(m) = r.method() {
        e = e.with_method(m)
    }
    Response::internal_error(r.id()).body(e)
}

/// A request/response identifier.
#[derive(Debug, Default, Copy, Clone, Encode, Decode, PartialEq, Eq, PartialOrd, Ord)]
#[cbor(transparent)]
pub struct Id(#[n(0)] u32);

/// Request methods.
#[derive(Debug, Copy, Clone, Encode, Decode)]
#[rustfmt::skip]
#[cbor(index_only)]
pub enum Method {
    #[n(0)] Get,
    #[n(1)] Post,
    #[n(2)] Put,
    #[n(3)] Delete,
    #[n(4)] Patch,
}

impl Display for Method {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Get => "GET",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Delete => "DELETE",
            Self::Patch => "PATCH",
        })
    }
}

/// The response status codes.
#[derive(Debug, Copy, Clone, Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
#[rustfmt::skip]
#[cbor(index_only)]
pub enum Status {
    #[n(200)] Ok,
    #[n(400)] BadRequest,
    #[n(401)] Unauthorized,
    #[n(403)] Forbidden,
    #[n(404)] NotFound,
    #[n(409)] Conflict,
    #[n(405)] MethodNotAllowed,
    #[n(500)] InternalServerError,
    #[n(501)] NotImplemented,
}

impl Display for Status {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(match self {
            Status::Ok => "200 Ok",
            Status::BadRequest => "400 BadRequest",
            Status::Unauthorized => "401 Unauthorized",
            Status::Forbidden => "403 Forbidden",
            Status::NotFound => "404 NotFound",
            Status::Conflict => "409 Conflict",
            Status::MethodNotAllowed => "405 MethodNotAllowed",
            Status::InternalServerError => "500 InternalServerError",
            Status::NotImplemented => "501 NotImplemented",
        })
    }
}

impl Id {
    pub fn fresh() -> Self {
        // Ensure random Ids are not equal to 0 (the default Id):
        Id(rand::random::<u32>().saturating_add(1))
    }
}

impl From<Id> for u32 {
    fn from(n: Id) -> Self {
        n.0
    }
}

impl Display for Id {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:08x}", self.0)
    }
}

impl<'a> Request<'a> {
    pub fn new<P: Into<Cow<'a, str>>>(method: Method, path: P, has_body: bool) -> Self {
        Request {
            #[cfg(feature = "tag")]
            tag: TypeTag,
            id: Id::fresh(),
            method: Some(method),
            path: path.into(),
            has_body,
        }
    }

    pub fn builder<P: Into<Cow<'a, str>>>(method: Method, path: P) -> RequestBuilder<'a> {
        RequestBuilder {
            header: Request::new(method, path, false),
            body: None,
        }
    }

    pub fn get<P: Into<Cow<'a, str>>>(path: P) -> RequestBuilder<'a> {
        Request::builder(Method::Get, path)
    }

    pub fn post<P: Into<Cow<'a, str>>>(path: P) -> RequestBuilder<'a> {
        Request::builder(Method::Post, path)
    }

    pub fn put<P: Into<Cow<'a, str>>>(path: P) -> RequestBuilder<'a> {
        Request::builder(Method::Put, path)
    }

    pub fn delete<P: Into<Cow<'a, str>>>(path: P) -> RequestBuilder<'a> {
        Request::builder(Method::Delete, path)
    }

    pub fn patch<P: Into<Cow<'a, str>>>(path: P) -> RequestBuilder<'a> {
        Request::builder(Method::Patch, path)
    }

    pub fn id(&self) -> Id {
        self.id
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn path_segments<const N: usize>(&self) -> Segments<N> {
        Segments::parse(self.path())
    }

    pub fn method(&self) -> Option<Method> {
        self.method
    }

    pub fn has_body(&self) -> bool {
        self.has_body
    }
}

impl Response {
    pub fn new(re: Id, status: Status, has_body: bool) -> Self {
        Response {
            #[cfg(feature = "tag")]
            tag: TypeTag,
            id: Id::fresh(),
            re,
            status: Some(status),
            has_body,
        }
    }

    pub fn builder(re: Id, status: Status) -> ResponseBuilder {
        ResponseBuilder {
            header: Response::new(re, status, false),
            body: None,
        }
    }

    pub fn ok(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::Ok)
    }

    pub fn bad_request(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::BadRequest)
    }

    pub fn not_found(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::NotFound)
    }

    pub fn not_implemented(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::NotImplemented)
    }

    pub fn unauthorized(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::Unauthorized)
    }

    pub fn forbidden(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::Forbidden)
    }

    pub fn internal_error(re: Id) -> ResponseBuilder {
        Response::builder(re, Status::InternalServerError)
    }

    pub fn id(&self) -> Id {
        self.id
    }

    pub fn re(&self) -> Id {
        self.re
    }

    pub fn status(&self) -> Option<Status> {
        self.status
    }

    pub fn has_body(&self) -> bool {
        self.has_body
    }
}

/// An error type used in response bodies.
#[derive(Debug, Clone, Default, Encode, Decode)]
#[rustfmt::skip]
#[cbor(map)]
pub struct Error<'a> {
    /// Nominal type tag.
    ///
    /// If the "tag" feature is enabled, the resulting CBOR will contain a
    /// unique numeric value that identifies this type to help catching type
    /// errors. Otherwise this tag will not be produced and is ignored during
    /// decoding if present.
    #[cfg(feature = "tag")]
    #[n(0)] tag: TypeTag<5359172>,
    /// The resource path of this error.
    #[b(1)] path: Option<Cow<'a, str>>,
    /// The request method of this error.
    #[n(2)] method: Option<Method>,
    /// The actual error message.
    #[b(3)] message: Option<Cow<'a, str>>,
}

impl<'a> Error<'a> {
    pub fn new<S: Into<Cow<'a, str>>>(path: S) -> Self {
        Error {
            #[cfg(feature = "tag")]
            tag: TypeTag,
            method: None,
            path: Some(path.into()),
            message: None,
        }
    }

    pub fn with_method(mut self, m: Method) -> Self {
        self.method = Some(m);
        self
    }

    pub fn set_method(&mut self, m: Method) {
        self.method = Some(m);
    }

    pub fn with_message<S: Into<Cow<'a, str>>>(mut self, m: S) -> Self {
        self.message = Some(m.into());
        self
    }

    pub fn path(&self) -> Option<&str> {
        self.path.as_deref()
    }

    pub fn method(&self) -> Option<Method> {
        self.method
    }

    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}

/// Path segments, i.e. '/'-separated string slices.
pub struct Segments<'a, const N: usize>(ArrayVec<[&'a str; N]>);

impl<'a, const N: usize> Segments<'a, N> {
    pub fn parse(s: &'a str) -> Self {
        if s.starts_with('/') {
            Self(s.trim_start_matches('/').splitn(N, '/').collect())
        } else {
            Self(s.splitn(N, '/').collect())
        }
    }

    pub fn as_slice(&self) -> &[&'a str] {
        &self.0[..]
    }
}

#[derive(Debug)]
pub struct RequestBuilder<'a, T = ()> {
    header: Request<'a>,
    body: Option<T>,
}

impl<'a, T> RequestBuilder<'a, T> {
    pub fn id(mut self, id: Id) -> Self {
        self.header.id = id;
        self
    }

    pub fn path<P: Into<Cow<'a, str>>>(mut self, path: P) -> Self {
        self.header.path = path.into();
        self
    }

    pub fn method(mut self, m: Method) -> Self {
        self.header.method = Some(m);
        self
    }

    pub fn header(&self) -> &Request<'a> {
        &self.header
    }

    pub fn into_parts(self) -> (Request<'a>, Option<T>) {
        (self.header, self.body)
    }
}

impl<'a> RequestBuilder<'a, ()> {
    pub fn body<T: Encode<()>>(self, b: T) -> RequestBuilder<'a, T> {
        let mut b = RequestBuilder {
            header: self.header,
            body: Some(b),
        };
        b.header.has_body = true;
        b
    }
}

impl<'a, T: Encode<()>> RequestBuilder<'a, T> {
    pub fn encode<W>(&self, buf: W) -> Result<(), encode::Error<W::Error>>
    where
        W: Write,
    {
        let mut e = Encoder::new(buf);
        e.encode(&self.header)?;
        if let Some(b) = &self.body {
            e.encode(b)?;
        }
        Ok(())
    }

    pub fn to_vec(&self) -> Result<Vec<u8>, encode::Error<<Vec<u8> as Write>::Error>> {
        let mut buf = Vec::new();
        self.encode(&mut buf)?;

        Ok(buf)
    }
}

#[derive(Debug)]
pub struct ResponseBuilder<T = ()> {
    header: Response,
    body: Option<T>,
}

impl<T> ResponseBuilder<T> {
    pub fn id(mut self, id: Id) -> Self {
        self.header.id = id;
        self
    }

    pub fn re(mut self, re: Id) -> Self {
        self.header.re = re;
        self
    }

    pub fn status(mut self, s: Status) -> Self {
        self.header.status = Some(s);
        self
    }

    pub fn header(&self) -> &Response {
        &self.header
    }

    pub fn into_parts(self) -> (Response, Option<T>) {
        (self.header, self.body)
    }
}

impl ResponseBuilder<()> {
    pub fn body<T: Encode<()>>(self, b: T) -> ResponseBuilder<T> {
        let mut b = ResponseBuilder {
            header: self.header,
            body: Some(b),
        };
        b.header.has_body = true;
        b
    }
}

impl<T: Encode<()>> ResponseBuilder<T> {
    pub fn encode<W>(&self, buf: W) -> Result<(), encode::Error<W::Error>>
    where
        W: Write,
    {
        let mut e = Encoder::new(buf);
        e.encode(&self.header)?;
        if let Some(b) = &self.body {
            e.encode(b)?;
        }
        Ok(())
    }

    pub fn to_vec(self) -> Result<Vec<u8>, encode::Error<<Vec<u8> as Write>::Error>> {
        let mut buf = Vec::new();
        self.encode(&mut buf)?;

        Ok(buf)
    }
}

#[allow(unused_variables)]
#[cfg(feature = "tag")]
pub fn assert_request_match<'a>(
    struct_name: impl Into<Option<&'a str>>,
    cbor: &[u8],
    cddl_context: &BasicContext,
) {
    use cddl_cat::validate_cbor;

    let cbor_value = serde_cbor::from_slice(cbor).expect("header");

    match cddl_context.rules.get("request") {
        Some(request_rules) => {
            if let Err(e) = validate_cbor(request_rules, &cbor_value, cddl_context) {
                tracing::error!(error = %e, "request header mismatch")
            }
        }
        None => tracing::error!("no request header definition found"),
    }

    if let Some(struct_name) = struct_name.into() {
        match cddl_context.rules.get(struct_name) {
            Some(request_rules) => {
                if let Err(e) = validate_cbor(request_rules, &cbor_value, cddl_context) {
                    tracing::error!(error = %e, "request body mismatch")
                }
            }
            None => tracing::error!("no request body definition found"),
        }
    }
}

#[cfg(feature = "tag")]
#[allow(unused_variables)]
pub fn assert_response_match<'a>(
    struct_name: impl Into<Option<&'a str>>,
    cbor: &[u8],
    cddl_context: &BasicContext,
) {
    use cddl_cat::validate_cbor;

    let cbor_value = serde_cbor::from_slice(cbor).expect("header");

    match cddl_context.rules.get("response") {
        Some(request_rules) => {
            if let Err(e) = validate_cbor(request_rules, &cbor_value, cddl_context) {
                tracing::error!(error = %e, "response header mismatch")
            }
        }
        None => tracing::error!("no response header definition found"),
    }
    if let Some(struct_name) = struct_name.into() {
        if let Some(struct_name) = struct_name.into() {
            match cddl_context.rules.get(struct_name) {
                Some(request_rules) => {
                    if let Err(e) = validate_cbor(request_rules, &cbor_value, cddl_context) {
                        tracing::error!(error = %e, "response body mismatch")
                    }
                }
                None => tracing::error!("no response body definition found"),
            }
        }
    }
}

/// Decode response header only, without processing the message body.
pub fn is_ok(label: &str, buf: &[u8]) -> Result<()> {
    let mut d = Decoder::new(buf);
    let res = response(label, &mut d)?;

    #[cfg(feature = "tag")]
    assert_response_match(None, buf, cddl());
    if res.status() == Some(Status::Ok) {
        Ok(())
    } else {
        Err(error(label, &res, &mut d))
    }
}

/// Decode response and an optional body.
pub fn decode_option<'a, 'b, T: Decode<'b, ()>>(
    label: &'a str,
    #[allow(unused_variables)] struct_name: impl Into<Option<&'a str>>,
    buf: &'b [u8],
) -> Result<Option<T>> {
    let mut d = Decoder::new(buf);
    let res = response(label, &mut d)?;
    match res.status() {
        Some(Status::Ok) => {
            #[cfg(feature = "tag")]
            assert_response_match(struct_name, buf, cddl());
            Ok(Some(d.decode()?))
        }
        Some(Status::NotFound) => Ok(None),
        _ => Err(error(label, &res, &mut d)),
    }
}

/// Decode and log response header.
pub(crate) fn response(label: &str, dec: &mut Decoder<'_>) -> Result<Response> {
    let res: Response = dec.decode()?;
    trace! {
        target:  "ockam_api",
        id     = %res.id(),
        re     = %res.re(),
        status = ?res.status(),
        body   = %res.has_body(),
        "<- {label}"
    }
    Ok(res)
}

/// Decode, log and map response error to ockam_core error.
pub(crate) fn error(label: &str, res: &Response, dec: &mut Decoder<'_>) -> crate::Error {
    if res.has_body() {
        let err = match dec.decode::<Error>() {
            Ok(e) => e,
            Err(e) => return e.into(),
        };
        warn! {
            target:  "ockam_api",
            id     = %res.id(),
            re     = %res.re(),
            status = ?res.status(),
            error  = ?err.message(),
            "<- {label}"
        }
        let msg = err.message().unwrap_or(label);
        crate::Error::new(Origin::Application, Kind::Protocol, msg)
    } else {
        warn! {
            target:  "ockam_api",
            id     = %res.id(),
            re     = %res.re(),
            status = ?res.status(),
            "<- {label}"
        }
        crate::Error::new(Origin::Application, Kind::Protocol, label)
    }
}

/// Newtype around a byte-slice that is assumed to be CBOR-encoded.
#[derive(Debug, Copy, Clone)]
pub struct Cbor<'a>(pub &'a [u8]);

impl<C> Encode<C> for Cbor<'_> {
    fn encode<W>(&self, e: &mut Encoder<W>, _: &mut C) -> Result<(), encode::Error<W::Error>>
    where
        W: Write,
    {
        // Since we assume an existing CBOR encoding, we just append the bytes as is:
        e.writer_mut()
            .write_all(self.0)
            .map_err(encode::Error::write)
    }
}

#[cfg(test)]
#[cfg(feature = "tag")]
mod merged_cddl_test {
    use super::merged_cddl;

    #[test]
    fn test_merged_cddl() {
        use cddl_cat::validate_cbor;
        use serde::Serialize;

        let schema1: &str = r##"request_1 = {id: int, name: tstr}"##;
        let schema2: &str = r##"request_2 = {id: int, name: tstr}"##;

        let merged_cddl = merged_cddl(&[schema1, schema2]);
        let rule_request_1 = merged_cddl
            .as_ref()
            .unwrap()
            .rules
            .get("request_1")
            .unwrap();

        #[derive(Serialize)]
        struct Request1Struct {
            id: i8,
            name: String,
        }

        let request_1 = Request1Struct {
            id: 1,
            name: "request_1".to_string(),
        };

        let cbor_bytes = serde_cbor::to_vec(&request_1).unwrap();
        let cbor_value = serde_cbor::from_slice(&cbor_bytes).unwrap();
        validate_cbor(rule_request_1, &cbor_value, merged_cddl.as_ref().unwrap()).unwrap();
    }

    #[test]
    fn test_merged_cddl_duplicate_entry() {
        let schema1: &str = r##"request_1 = {id: int, name: tstr}"##;

        // same key, albeit with captial "ID" -> should error
        let schema2: &str = r##"request_1 = {ID: int, name: tstr}"##;

        let merged_cddl = merged_cddl(&[schema1, schema2]);
        match merged_cddl {
            Err(e) => assert_eq!(
                "CDDL files contain duplicate keys: request_1",
                e.to_string()
            ),
            Ok(_) => panic!("Returned an Ok variant!"),
        }
    }

    #[test]
    fn test_merged_cddl_no_valid_cddl() {
        let schema1: &str = r##"foo bar"##;

        let merged_cddl = merged_cddl(&[schema1]);
        match merged_cddl {
            Err(e) => assert_eq!("Unparseable(bar)", e.to_string()),
            Ok(_) => panic!("Returned an Ok variant!"),
        }
    }
}

#[cfg(test)]
#[cfg(feature = "tag")]
mod schema_test {
    use super::*;
    use cddl_cat::validate_cbor_bytes;
    use quickcheck::{quickcheck, Arbitrary, Gen, TestResult};

    const METHODS: &[Method] = &[
        Method::Get,
        Method::Post,
        Method::Put,
        Method::Delete,
        Method::Patch,
    ];

    const STATUS: &[Status] = &[
        Status::Ok,
        Status::BadRequest,
        Status::NotFound,
        Status::MethodNotAllowed,
        Status::InternalServerError,
        Status::NotImplemented,
    ];

    #[derive(Debug, Clone)]
    struct Req(Request<'static>);

    #[derive(Debug, Clone)]
    struct Res(Response);

    #[derive(Debug, Clone)]
    struct Er(Error<'static>);

    impl Arbitrary for Req {
        fn arbitrary(g: &mut Gen) -> Self {
            Req(Request::new(
                *g.choose(METHODS).unwrap(),
                String::arbitrary(g),
                bool::arbitrary(g),
            ))
        }
    }

    impl Arbitrary for Res {
        fn arbitrary(g: &mut Gen) -> Self {
            Res(Response::new(
                Id::fresh(),
                *g.choose(STATUS).unwrap(),
                bool::arbitrary(g),
            ))
        }
    }

    impl Arbitrary for Er {
        fn arbitrary(g: &mut Gen) -> Self {
            let mut e = Error::new(String::arbitrary(g));
            if bool::arbitrary(g) {
                e = e.with_method(*g.choose(METHODS).unwrap())
            }
            if bool::arbitrary(g) {
                e = e.with_message(String::arbitrary(g))
            }
            Er(e)
        }
    }

    quickcheck! {
        fn request_schema(a: Req) -> TestResult {
            let cbor = minicbor::to_vec(a.0).unwrap();
            if let Err(e) = validate_cbor_bytes("request", SCHEMA, &cbor) {
                return TestResult::error(e.to_string())
            }
            TestResult::passed()
        }

        fn response_schema(a: Res) -> TestResult {
            let cbor = minicbor::to_vec(a.0).unwrap();
            if let Err(e) = validate_cbor_bytes("response", SCHEMA, &cbor) {
                return TestResult::error(e.to_string())
            }
            TestResult::passed()
        }

        fn error_schema(a: Er) -> TestResult {
            let cbor = minicbor::to_vec(a.0).unwrap();
            if let Err(e) = validate_cbor_bytes("error", SCHEMA, &cbor) {
                return TestResult::error(e.to_string())
            }
            TestResult::passed()
        }

        fn type_check(a: Req, b: Res, c: Er) -> TestResult {
            let cbor_a = minicbor::to_vec(a.0).unwrap();
            let cbor_b = minicbor::to_vec(b.0).unwrap();
            let cbor_c = minicbor::to_vec(c.0).unwrap();
            assert!(minicbor::decode::<Response>(&cbor_a).is_err());
            assert!(minicbor::decode::<Error>(&cbor_a).is_err());
            assert!(minicbor::decode::<Request>(&cbor_b).is_err());
            assert!(minicbor::decode::<Error>(&cbor_b).is_err());
            assert!(minicbor::decode::<Request>(&cbor_c).is_err());
            assert!(minicbor::decode::<Response>(&cbor_c).is_err());
            TestResult::passed()
        }
    }
}