polyoxide-venue 0.47.0

Shared vocabulary for the polyoxide venue clients: error classes, the status and close-code maps, the Retry-After parser, wire enums, positional decimals and Unix-millisecond time
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
//! Market keys: one canonical name per instrument, whichever venue lists it.

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use crate::{Class, Classify};

/// Whether `id` is a venue or product id: an ASCII lowercase letter, then
/// lowercase letters, digits and `-`, the form a crate's registration declares.
const fn is_id(id: &str) -> bool {
    let bytes = id.as_bytes();
    if bytes.is_empty() || !bytes[0].is_ascii_lowercase() {
        return false;
    }
    let mut i = 1;
    while i < bytes.len() {
        let b = bytes[i];
        if !(b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {
            return false;
        }
        i += 1;
    }
    true
}

macro_rules! id_type {
    ($(#[$doc:meta])* $name:ident, $what:literal) => {
        $(#[$doc])*
        #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(Cow<'static, str>);

        impl $name {
            #[doc = concat!("A ", $what, " id known when the program is built.")]
            ///
            /// # Panics
            ///
            /// Unless `id` is an ASCII lowercase letter followed by lowercase
            /// letters, digits and `-`. In a `const` the panic is a build error.
            pub const fn from_static(id: &'static str) -> Self {
                assert!(
                    is_id(id),
                    "an id is a lowercase letter, then lowercase letters, digits and `-`"
                );
                Self(Cow::Borrowed(id))
            }

            #[doc = concat!("The ", $what, " id.")]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_tuple(stringify!($name)).field(&self.as_str()).finish()
            }
        }
    };
}

id_type! {
    /// A venue's id: the `venue` of `venue.product:id`.
    ///
    /// A venue crate declares its own with [`VenueId::from_static`], equal to
    /// the `venue` its registration declares.
    VenueId, "venue"
}

id_type! {
    /// A product's id: the `product` of `venue.product:id`, naming the module
    /// that trades the instrument.
    ///
    /// A venue crate declares each with [`ProductId::from_static`], equal to one
    /// of the `products` its registration declares.
    ProductId, "product"
}

/// What a product trades, which fixes what its shared records mean.
///
/// A product declares its class as [`KeySpace::CLASS`], and every key it makes
/// carries it, so [`MarketKey::class`] answers without a request. A class is
/// added only when a product of that class lands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ProductClass {
    /// Contracts on an event's outcomes. A key names one outcome, a price lies
    /// between 0 and 1, and a share pays one unit of the settlement currency
    /// when its outcome happens, so a position's size is never negative.
    EventContract,
    /// Perpetual futures. A price is unbounded, a position's size is signed,
    /// and holders pay or receive funding.
    PerpetualFuture,
    /// Buying and selling the asset itself. A price is unbounded, a position
    /// is a balance of the base asset and so never negative, and there is no
    /// funding.
    Spot,
}

impl ProductClass {
    /// The class's id, as a crate's registration spells it in `classes`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::EventContract => "event-contract",
            Self::PerpetualFuture => "perpetual-future",
            Self::Spot => "spot",
        }
    }
}

impl fmt::Display for ProductClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One instrument's name, written `venue.product:id`, such as
/// `acme.perp:ABCUSD`.
///
/// A key has no public constructor from text or from parts. Only a product's
/// [`KeySpace`] makes one, and it canonicalizes the id first, so two keys are
/// equal exactly when they name the same instrument. On an event-contract
/// venue a key names one outcome, not a market.
///
/// It serializes as its text form. To read one back, parse a [`RawKey`] and
/// hand it to the product's constructors, which canonicalize it again.
///
/// ```
/// use std::borrow::Cow;
/// use polyoxide_venue::{KeySpace, MarketKey, ProductClass, ProductId, RawKey, VenueId};
///
/// /// A perpetual whose ids are ASCII and uppercased.
/// struct Perp;
///
/// impl KeySpace for Perp {
///     const VENUE: VenueId = VenueId::from_static("acme");
///     const PRODUCT: ProductId = ProductId::from_static("perp");
///     const CLASS: ProductClass = ProductClass::PerpetualFuture;
///     type Id = PerpId;
///
///     fn parse_id(text: &str) -> Result<PerpId, String> {
///         if text.is_ascii() {
///             Ok(PerpId(text.to_ascii_uppercase()))
///         } else {
///             Err("an id is ASCII".into())
///         }
///     }
///
///     fn id_text(id: &PerpId) -> Cow<'_, str> {
///         Cow::Borrowed(&id.0)
///     }
/// }
///
/// /// An id in canonical form: only `Perp::parse_id` makes one.
/// struct PerpId(String);
///
/// let key = Perp::parse(&RawKey::parse("acme.perp:abcusd")?)?;
/// assert_eq!(key, Perp::key(&Perp::parse_id("ABCUSD")?));
/// assert_eq!(key.to_string(), "acme.perp:ABCUSD");
/// assert_eq!(key.class(), ProductClass::PerpetualFuture);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MarketKey {
    venue: VenueId,
    product: ProductId,
    // After `product`: the class follows from the venue and product, so the
    // derived order still sorts by venue, product and id.
    class: ProductClass,
    id: Arc<str>,
}

impl MarketKey {
    /// The venue that lists the instrument.
    pub fn venue(&self) -> &VenueId {
        &self.venue
    }

    /// The product, the module that trades it.
    pub fn product(&self) -> &ProductId {
        &self.product
    }

    /// The product's class, which its [`KeySpace::CLASS`] declares. It follows
    /// from the venue and product, so the text form does not carry it.
    pub fn class(&self) -> ProductClass {
        self.class
    }

    /// The id, in its product's canonical form. Opaque to everything but its
    /// product.
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl fmt::Display for MarketKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}:{}", self.venue, self.product, self.id)
    }
}

impl fmt::Debug for MarketKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("MarketKey")
            .field(&format_args!("{self}"))
            .finish()
    }
}

impl Serialize for MarketKey {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

/// A key's text split into venue, product and id, checked by no product yet.
///
/// [`RawKey::parse`] splits at the first `:`, then what comes before it at its
/// first `.`. The id is everything after the `:`, so it may hold `:` and `.`
/// of its own. The venue and product must be ids (an ASCII lowercase letter,
/// then lowercase letters, digits and `-`) and the id must not be empty; the
/// id is otherwise kept as written, since only its product knows its
/// canonical form.
///
/// It serializes as its text form and deserializes through
/// [`RawKey::parse`].
///
/// ```
/// use polyoxide_venue::RawKey;
///
/// let raw = RawKey::parse("acme.events:FED-25DEC:yes")?;
/// assert_eq!(raw.venue().as_str(), "acme");
/// assert_eq!(raw.product().as_str(), "events");
/// assert_eq!(raw.id(), "FED-25DEC:yes");
/// assert!(RawKey::parse("acme:spot").is_err());
/// # Ok::<(), polyoxide_venue::KeyError>(())
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct RawKey {
    venue: VenueId,
    product: ProductId,
    id: String,
}

impl RawKey {
    /// Splits `text`, written `venue.product:id`.
    ///
    /// # Errors
    ///
    /// [`KeyError::Malformed`] when there is no `:`, no `.` before it, a venue
    /// or product that is not an id, or an empty id.
    pub fn parse(text: &str) -> Result<Self, KeyError> {
        let malformed = |reason| KeyError::Malformed {
            text: text.to_owned(),
            reason,
        };
        let (scope, id) = text
            .split_once(':')
            .ok_or_else(|| malformed("no `:` before the id"))?;
        let (venue, product) = scope
            .split_once('.')
            .ok_or_else(|| malformed("no `.` between the venue and the product"))?;
        if !is_id(venue) {
            return Err(malformed(
                "the venue is not a lowercase letter followed by lowercase letters, digits and `-`",
            ));
        }
        if !is_id(product) {
            return Err(malformed(
                "the product is not a lowercase letter followed by lowercase letters, digits and `-`",
            ));
        }
        if id.is_empty() {
            return Err(malformed("the id is empty"));
        }
        Ok(Self {
            venue: VenueId(Cow::Owned(venue.to_owned())),
            product: ProductId(Cow::Owned(product.to_owned())),
            id: id.to_owned(),
        })
    }

    /// The venue, as written.
    pub fn venue(&self) -> &VenueId {
        &self.venue
    }

    /// The product, as written.
    pub fn product(&self) -> &ProductId {
        &self.product
    }

    /// The id, as written.
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl FromStr for RawKey {
    type Err = KeyError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::parse(text)
    }
}

impl fmt::Display for RawKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}:{}", self.venue, self.product, self.id)
    }
}

impl fmt::Debug for RawKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("RawKey")
            .field(&format_args!("{self}"))
            .finish()
    }
}

impl Serialize for RawKey {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for RawKey {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = Cow::<'de, str>::deserialize(deserializer)?;
        Self::parse(&text).map_err(de::Error::custom)
    }
}

/// A product's keys. A venue crate implements it once for each product it
/// trades, and its methods are the only way to make a [`MarketKey`].
///
/// The product's [`Id`](Self::Id) type holds an id in canonical form, so
/// [`key`](Self::key) cannot fail, and [`parse_id`](Self::parse_id) is the
/// one place the product checks and canonicalizes text.
pub trait KeySpace {
    /// The venue id, equal to the `venue` the venue crate registers.
    const VENUE: VenueId;
    /// The product id, one of the `products` the venue crate registers.
    const PRODUCT: ProductId;
    /// The product's class, equal to the one the venue crate registers for
    /// the product in `classes`.
    const CLASS: ProductClass;
    /// The product's own id, in canonical form.
    type Id;

    /// Reads an id from text, canonicalizing it.
    ///
    /// # Errors
    ///
    /// Why the text is not one of the product's ids.
    fn parse_id(text: &str) -> Result<Self::Id, String>;

    /// The id's canonical text, the `id` of its key.
    fn id_text(id: &Self::Id) -> Cow<'_, str>;

    /// The key of `id`.
    fn key(id: &Self::Id) -> MarketKey {
        MarketKey {
            venue: Self::VENUE,
            product: Self::PRODUCT,
            class: Self::CLASS,
            id: Arc::from(Self::id_text(id).as_ref()),
        }
    }

    /// The key `raw` names, canonicalized.
    ///
    /// # Errors
    ///
    /// [`KeyError::WrongProduct`] when `raw` names another product, and
    /// [`KeyError::InvalidId`] when its id is not one of this product's.
    fn parse(raw: &RawKey) -> Result<MarketKey, KeyError> {
        id_of::<Self>(raw.venue(), raw.product(), raw.id()).map(|id| Self::key(&id))
    }

    /// The product's id that `key` names.
    ///
    /// # Errors
    ///
    /// [`KeyError::WrongProduct`] when `key` names another product.
    fn id(key: &MarketKey) -> Result<Self::Id, KeyError> {
        id_of::<Self>(key.venue(), key.product(), key.id())
    }
}

/// `K`'s id for a key's parts, after checking they name `K`'s product. A free
/// function, so no implementor can override the check behind `parse` and `id`.
fn id_of<K: KeySpace + ?Sized>(
    venue: &VenueId,
    product: &ProductId,
    id: &str,
) -> Result<K::Id, KeyError> {
    if venue != &K::VENUE || product != &K::PRODUCT {
        return Err(KeyError::WrongProduct {
            expected: format!("{}.{}", K::VENUE, K::PRODUCT),
            found: format!("{venue}.{product}"),
        });
    }
    K::parse_id(id).map_err(|reason| KeyError::InvalidId {
        product: format!("{}.{}", K::VENUE, K::PRODUCT),
        id: id.to_owned(),
        reason,
    })
}

/// Why text or a key named no instrument a product could read. Every one is
/// an [`InvalidRequest`](Class::InvalidRequest): the caller named something
/// no request can carry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyError {
    /// The text is not `venue.product:id`.
    Malformed {
        /// The text, as given.
        text: String,
        /// What is wrong with it.
        reason: &'static str,
    },
    /// No product this build enables has the key's venue and product ids.
    UnknownProduct {
        /// The venue id, as written.
        venue: String,
        /// The product id, as written.
        product: String,
    },
    /// A product was handed a key of another product.
    WrongProduct {
        /// The product that was asked, as `venue.product`.
        expected: String,
        /// The key's product, as `venue.product`.
        found: String,
    },
    /// The product does not read the id as one of its own.
    InvalidId {
        /// The product, as `venue.product`.
        product: String,
        /// The id, as given.
        id: String,
        /// Why the product refused it.
        reason: String,
    },
}

impl KeyError {
    /// The error for a raw key whose venue and product no enabled product has.
    pub fn unknown(raw: &RawKey) -> Self {
        Self::UnknownProduct {
            venue: raw.venue().as_str().to_owned(),
            product: raw.product().as_str().to_owned(),
        }
    }
}

impl fmt::Display for KeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed { text, reason } => {
                write!(
                    f,
                    "{text:?} is not a market key (`venue.product:id`): {reason}"
                )
            }
            Self::UnknownProduct { venue, product } => {
                write!(f, "no product this build enables is {venue}.{product}")
            }
            Self::WrongProduct { expected, found } => {
                write!(f, "a {found} key was given where a {expected} key belongs")
            }
            Self::InvalidId {
                product,
                id,
                reason,
            } => write!(f, "{id:?} is not a {product} id: {reason}"),
        }
    }
}

impl Error for KeyError {}

/// An [`InvalidRequest`](Class::InvalidRequest), whatever the case.
impl Classify for KeyError {
    fn class(&self) -> Class {
        Class::InvalidRequest
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Ids are ASCII; letters are uppercased.
    struct Upper;

    /// An id in canonical form: only `Upper::parse_id` makes one.
    struct UpperId(String);

    impl KeySpace for Upper {
        const VENUE: VenueId = VenueId::from_static("acme");
        const PRODUCT: ProductId = ProductId::from_static("spot");
        const CLASS: ProductClass = ProductClass::EventContract;
        type Id = UpperId;

        fn parse_id(text: &str) -> Result<UpperId, String> {
            if text.is_ascii() {
                Ok(UpperId(text.to_ascii_uppercase()))
            } else {
                Err("an id is ASCII".to_owned())
            }
        }

        fn id_text(id: &UpperId) -> Cow<'_, str> {
            Cow::Borrowed(&id.0)
        }
    }

    /// Ids are unsigned integers, written without leading zeros.
    struct Numbered;

    impl KeySpace for Numbered {
        const VENUE: VenueId = VenueId::from_static("acme");
        const PRODUCT: ProductId = ProductId::from_static("perpetual");
        const CLASS: ProductClass = ProductClass::PerpetualFuture;
        type Id = u64;

        fn parse_id(text: &str) -> Result<u64, String> {
            text.parse().map_err(|e| format!("{e}"))
        }

        fn id_text(id: &u64) -> Cow<'_, str> {
            Cow::Owned(id.to_string())
        }
    }

    /// The key of an ASCII id, canonicalized by `Upper::parse_id` first.
    fn upper(id: &str) -> MarketKey {
        Upper::key(&Upper::parse_id(id).unwrap())
    }

    fn raw(text: &str) -> RawKey {
        RawKey::parse(text).unwrap()
    }

    #[test]
    fn text_splits_at_the_first_dot_and_the_first_colon() {
        let key = raw("acme.spot:abc");
        assert_eq!(key.venue().as_str(), "acme");
        assert_eq!(key.product().as_str(), "spot");
        assert_eq!(key.id(), "abc");

        let dotted = raw("acme.spot:a.b");
        assert_eq!(dotted.product().as_str(), "spot");
        assert_eq!(dotted.id(), "a.b");
    }

    #[test]
    fn a_synthetic_id_holding_a_second_colon_is_kept_whole() {
        let key = raw("acme.events:FED-25DEC:yes");
        assert_eq!(key.id(), "FED-25DEC:yes");
        assert_eq!(key.to_string(), "acme.events:FED-25DEC:yes");
        let parsed = Upper::parse(&raw("acme.spot:fed-25dec:yes")).unwrap();
        assert_eq!(parsed.id(), "FED-25DEC:YES");
    }

    #[test]
    fn malformed_text_names_its_fault() {
        for (text, fault) in [
            ("acme-spot-abc", "no `:`"),
            ("acme:abc", "no `.`"),
            ("Acme.spot:abc", "the venue"),
            (".spot:abc", "the venue"),
            ("acme.Spot:abc", "the product"),
            ("acme.sp.ot:abc", "the product"),
            ("acme.:abc", "the product"),
            ("acme.spot:", "the id is empty"),
            (" acme.spot:abc", "the venue"),
        ] {
            let err = RawKey::parse(text).unwrap_err();
            assert!(
                matches!(&err, KeyError::Malformed { text: t, reason } if t == text && reason.contains(fault)),
                "{text:?}: {err}"
            );
        }
    }

    #[test]
    fn a_venue_and_a_product_may_hold_digits_and_hyphens() {
        let key = raw("acme-2.spot-x:a");
        assert_eq!(key.venue().as_str(), "acme-2");
        assert_eq!(key.product().as_str(), "spot-x");
        assert_eq!(key.id(), "a");
    }

    #[test]
    fn case_canonicalization_makes_two_spellings_one_key() {
        let lower = Upper::parse(&raw("acme.spot:abcusd")).unwrap();
        let upper = Upper::parse(&raw("acme.spot:ABCUSD")).unwrap();
        assert_eq!(lower, upper);
        assert_eq!(lower.id(), "ABCUSD");
        let mut map = std::collections::HashMap::new();
        map.insert(lower, 1);
        assert_eq!(map.get(&upper), Some(&1));
    }

    #[test]
    fn a_numbered_id_loses_its_leading_zeros() {
        let key = Numbered::parse(&raw("acme.perpetual:007")).unwrap();
        assert_eq!(key, Numbered::key(&7));
        assert_eq!(key.id(), "7");
        assert_eq!(Numbered::id(&key), Ok(7));
    }

    #[test]
    fn a_product_refuses_another_products_key_and_an_id_it_cannot_read() {
        let spot = upper("ABC");
        assert_eq!(
            Numbered::id(&spot),
            Err(KeyError::WrongProduct {
                expected: "acme.perpetual".to_owned(),
                found: "acme.spot".to_owned(),
            })
        );
        assert!(matches!(
            Numbered::parse(&raw("other.perpetual:7")),
            Err(KeyError::WrongProduct { .. })
        ));
        let err = Numbered::parse(&raw("acme.perpetual:seven")).unwrap_err();
        assert!(
            matches!(&err, KeyError::InvalidId { product, id, .. } if product == "acme.perpetual" && id == "seven"),
            "{err}"
        );
        assert_eq!(err.class(), Class::InvalidRequest);
    }

    #[test]
    fn a_key_and_a_raw_key_serialize_as_their_text() {
        let key = upper("ABC");
        assert_eq!(serde_json::to_string(&key).unwrap(), r#""acme.spot:ABC""#);
        let raw: RawKey = serde_json::from_str(r#""acme.spot:abc""#).unwrap();
        assert_eq!(raw, RawKey::parse("acme.spot:abc").unwrap());
        assert_eq!(serde_json::to_string(&raw).unwrap(), r#""acme.spot:abc""#);
        assert!(serde_json::from_str::<RawKey>(r#""acme-spot""#).is_err());
        assert_eq!(Upper::parse(&raw).unwrap(), key);
    }

    #[test]
    fn debug_shows_the_text_form() {
        let key = upper("ABC");
        assert_eq!(format!("{key:?}"), "MarketKey(acme.spot:ABC)");
        assert_eq!(
            format!("{:?}", raw("acme.spot:abc")),
            "RawKey(acme.spot:abc)"
        );
        assert_eq!(format!("{:?}", Upper::VENUE), r#"VenueId("acme")"#);
    }

    #[test]
    fn every_key_error_is_an_invalid_request() {
        let errors = [
            RawKey::parse("x").unwrap_err(),
            KeyError::unknown(&raw("acme.spot:abc")),
            Numbered::id(&upper("A")).unwrap_err(),
            Numbered::parse(&raw("acme.perpetual:x")).unwrap_err(),
        ];
        for err in errors {
            assert_eq!(err.class(), Class::InvalidRequest, "{err}");
            assert!(err.is_fault());
            assert!(!err.is_retriable());
        }
    }

    #[test]
    #[should_panic(expected = "an id is a lowercase letter")]
    fn a_static_id_must_be_an_id() {
        let _ = VenueId::from_static("Acme");
    }

    #[test]
    fn a_key_carries_the_class_its_product_declares() {
        assert_eq!(upper("ABC").class(), ProductClass::EventContract);
        let parsed = Numbered::parse(&raw("acme.perpetual:007")).unwrap();
        assert_eq!(parsed.class(), ProductClass::PerpetualFuture);
        assert_eq!(parsed.class(), Numbered::CLASS);
        // The class is not part of the text form.
        assert_eq!(parsed.to_string(), "acme.perpetual:7");
    }

    #[test]
    fn a_class_is_spelled_as_a_registration_spells_it() {
        assert_eq!(ProductClass::EventContract.as_str(), "event-contract");
        assert_eq!(
            ProductClass::PerpetualFuture.to_string(),
            "perpetual-future"
        );
    }
}