polyoxide-venue 0.43.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
//! Facts only one venue has, carried on a shared record without a field of
//! their own.

use std::any::{Any, TypeId};
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;

use crate::{Class, Classify};

/// The object-safe face of an extension value.
trait Extension: Any + Send + Sync {
    fn clone_box(&self) -> Box<dyn Extension>;
    fn eq_dyn(&self, other: &dyn Extension) -> bool;
    fn fmt_dyn(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
    fn type_name_dyn(&self) -> &'static str;
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn into_any(self: Box<Self>) -> Box<dyn Any>;
}

impl<T> Extension for T
where
    T: Clone + fmt::Debug + PartialEq + Send + Sync + 'static,
{
    fn clone_box(&self) -> Box<dyn Extension> {
        Box::new(self.clone())
    }

    fn eq_dyn(&self, other: &dyn Extension) -> bool {
        other
            .as_any()
            .downcast_ref::<T>()
            .is_some_and(|other| self == other)
    }

    fn fmt_dyn(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }

    fn type_name_dyn(&self) -> &'static str {
        std::any::type_name::<T>()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

/// Facts only one venue has, carried on a shared record: at most one value of
/// each type, read back by its type.
///
/// Each product defines one `<Record>Ext` type per record it fills, such as a
/// quote's update id, and inserts one value of it. A value's type is
/// `Clone + Debug + PartialEq + Send + Sync + 'static`, so a record that
/// carries extensions stays `Clone`, `Debug` and `PartialEq`, and two records
/// are equal only when their extensions hold equal values of the same types.
/// There is no serde support: a value's type is known only to the crate that
/// defines it.
///
/// ```
/// use polyoxide_venue::Extensions;
///
/// #[derive(Debug, Clone, PartialEq)]
/// struct QuoteExt {
///     update_id: u64,
/// }
///
/// let mut ext = Extensions::new();
/// ext.insert(QuoteExt { update_id: 7 })?;
/// assert_eq!(ext.get::<QuoteExt>(), Some(&QuoteExt { update_id: 7 }));
/// assert!(ext.insert(QuoteExt { update_id: 8 }).is_err(), "one value per type");
/// assert_ne!(ext, Extensions::of(QuoteExt { update_id: 8 }));
/// # Ok::<(), polyoxide_venue::DuplicateExtension>(())
/// ```
///
/// A value whose type cannot be compared is refused when the program is
/// built:
///
/// ```compile_fail
/// use polyoxide_venue::Extensions;
///
/// #[derive(Debug, Clone)]
/// struct Uncomparable;
///
/// let mut ext = Extensions::new();
/// ext.insert(Uncomparable).unwrap();
/// ```
///
/// Nor does it serialize, since a value's type is known only to the crate that
/// defines it:
///
/// ```compile_fail
/// fn serializes<T: serde::Serialize>() {}
/// serializes::<polyoxide_venue::Extensions>();
/// ```
///
/// ```compile_fail
/// fn deserializes<T: serde::de::DeserializeOwned>() {}
/// deserializes::<polyoxide_venue::Extensions>();
/// ```
#[derive(Default)]
pub struct Extensions {
    values: BTreeMap<TypeId, Box<dyn Extension>>,
}

impl Extensions {
    /// No extensions.
    pub fn new() -> Self {
        Self::default()
    }

    /// Extensions holding `value` alone.
    pub fn of<T>(value: T) -> Self
    where
        T: Clone + fmt::Debug + PartialEq + Send + Sync + 'static,
    {
        let mut ext = Self::new();
        ext.values.insert(TypeId::of::<T>(), Box::new(value));
        ext
    }

    /// Adds `value`.
    ///
    /// # Errors
    ///
    /// [`DuplicateExtension`] when a value of `T` is already held, which is
    /// kept unchanged.
    pub fn insert<T>(&mut self, value: T) -> Result<(), DuplicateExtension>
    where
        T: Clone + fmt::Debug + PartialEq + Send + Sync + 'static,
    {
        let id = TypeId::of::<T>();
        if self.values.contains_key(&id) {
            return Err(DuplicateExtension {
                type_name: std::any::type_name::<T>(),
            });
        }
        self.values.insert(id, Box::new(value));
        Ok(())
    }

    /// The value of `T`, when one is held.
    pub fn get<T: 'static>(&self) -> Option<&T> {
        self.values
            .get(&TypeId::of::<T>())
            .and_then(|value| value.as_ref().as_any().downcast_ref())
    }

    /// The value of `T`, to change in place, when one is held.
    pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.values
            .get_mut(&TypeId::of::<T>())
            .and_then(|value| value.as_mut().as_any_mut().downcast_mut())
    }

    /// Takes the value of `T` out, when one is held.
    pub fn remove<T: 'static>(&mut self) -> Option<T> {
        self.values
            .remove(&TypeId::of::<T>())
            .and_then(|value| value.into_any().downcast().ok())
            .map(|value: Box<T>| *value)
    }

    /// Whether a value of `T` is held.
    pub fn contains<T: 'static>(&self) -> bool {
        self.values.contains_key(&TypeId::of::<T>())
    }

    /// The types of the values held, one each.
    pub fn type_ids(&self) -> impl Iterator<Item = TypeId> + '_ {
        self.values.keys().copied()
    }

    /// How many values are held.
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Whether no value is held.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Checks that every value held is of a type in `declared`, the option
    /// types a venue reads.
    ///
    /// A request carries the venue's own options as extensions, and a venue
    /// that reads only some option types refuses the rest rather than ignoring
    /// them. An empty set always passes.
    ///
    /// # Errors
    ///
    /// [`UndeclaredExtension`] naming the first value held, in `TypeId` order,
    /// whose type is not in `declared`.
    ///
    /// ```
    /// use std::any::TypeId;
    ///
    /// use polyoxide_venue::Extensions;
    ///
    /// #[derive(Debug, Clone, PartialEq)]
    /// struct Options;
    ///
    /// #[derive(Debug, Clone, PartialEq)]
    /// struct Other;
    ///
    /// let ext = Extensions::of(Options);
    /// assert!(ext.ensure_declared(&[TypeId::of::<Options>()]).is_ok());
    /// assert!(ext.ensure_declared(&[TypeId::of::<Other>()]).is_err());
    /// assert!(Extensions::new().ensure_declared(&[]).is_ok());
    /// ```
    pub fn ensure_declared(&self, declared: &[TypeId]) -> Result<(), UndeclaredExtension> {
        match self.values.iter().find(|(id, _)| !declared.contains(id)) {
            Some((_, value)) => Err(UndeclaredExtension {
                type_name: value.as_ref().type_name_dyn(),
            }),
            None => Ok(()),
        }
    }
}

impl Clone for Extensions {
    fn clone(&self) -> Self {
        Self {
            values: self
                .values
                .iter()
                .map(|(id, value)| (*id, value.as_ref().clone_box()))
                .collect(),
        }
    }
}

impl PartialEq for Extensions {
    fn eq(&self, other: &Self) -> bool {
        self.values.len() == other.values.len()
            && self.values.iter().all(|(id, value)| {
                other
                    .values
                    .get(id)
                    .is_some_and(|theirs| value.as_ref().eq_dyn(theirs.as_ref()))
            })
    }
}

impl fmt::Debug for Extensions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Value<'a>(&'a dyn Extension);

        impl fmt::Debug for Value<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt_dyn(f)
            }
        }

        f.debug_set()
            .entries(self.values.values().map(|value| Value(value.as_ref())))
            .finish()
    }
}

/// A value was inserted into [`Extensions`] that already held one of its type.
/// An [`InvalidRequest`](Class::InvalidRequest): the caller's misuse.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateExtension {
    /// The type both values have.
    pub type_name: &'static str,
}

impl fmt::Display for DuplicateExtension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the record already holds an extension of type {}",
            self.type_name
        )
    }
}

impl Error for DuplicateExtension {}

impl Classify for DuplicateExtension {
    fn class(&self) -> Class {
        Class::InvalidRequest
    }
}

/// A request carried an extension of a type its venue does not declare
/// ([`Extensions::ensure_declared`]). An
/// [`InvalidRequest`](Class::InvalidRequest): the caller's misuse, refused
/// before anything is sent.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UndeclaredExtension {
    /// The type the venue does not declare.
    pub type_name: &'static str,
}

impl fmt::Display for UndeclaredExtension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the request carries `{}`, an extension this venue does not declare",
            self.type_name
        )
    }
}

impl Error for UndeclaredExtension {}

impl Classify for UndeclaredExtension {
    fn class(&self) -> Class {
        Class::InvalidRequest
    }
}

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

    #[derive(Debug, Clone, PartialEq)]
    struct QuoteExt {
        update_id: u64,
    }

    #[derive(Debug, Clone, PartialEq)]
    struct BookExt {
        sequence: u64,
    }

    #[test]
    fn extensions_are_clone_debug_default_partial_eq_send_and_sync() {
        fn holds<T: Clone + fmt::Debug + Default + PartialEq + Send + Sync>() {}
        holds::<Extensions>();
    }

    #[test]
    fn a_value_is_read_back_by_its_type() {
        let mut ext = Extensions::new();
        assert!(ext.is_empty());
        ext.insert(QuoteExt { update_id: 7 }).unwrap();
        ext.insert(BookExt { sequence: 9 }).unwrap();
        assert_eq!(ext.len(), 2);
        assert_eq!(ext.get::<QuoteExt>(), Some(&QuoteExt { update_id: 7 }));
        assert_eq!(ext.get::<BookExt>(), Some(&BookExt { sequence: 9 }));
        assert_eq!(ext.get::<u64>(), None);
        assert!(ext.contains::<QuoteExt>());
        assert!(!ext.contains::<String>());
    }

    #[test]
    fn inserting_a_type_already_held_is_an_error_and_keeps_the_first() {
        let mut ext = Extensions::of(QuoteExt { update_id: 7 });
        let err = ext.insert(QuoteExt { update_id: 8 }).unwrap_err();
        assert!(err.type_name.ends_with("QuoteExt"), "{err}");
        assert_eq!(err.class(), Class::InvalidRequest);
        assert_eq!(ext.get::<QuoteExt>(), Some(&QuoteExt { update_id: 7 }));
        assert_eq!(ext.len(), 1);
    }

    #[test]
    fn equality_compares_the_values_not_just_the_types() {
        let a = Extensions::of(QuoteExt { update_id: 7 });
        assert_eq!(a, Extensions::of(QuoteExt { update_id: 7 }));
        assert_ne!(a, Extensions::of(QuoteExt { update_id: 8 }));
        assert_ne!(a, Extensions::of(BookExt { sequence: 7 }));
        assert_ne!(a, Extensions::new());
        assert_ne!(Extensions::new(), a);
        let mut both = a.clone();
        both.insert(BookExt { sequence: 1 }).unwrap();
        assert_ne!(a, both);
        assert_ne!(both, a);
        assert_eq!(Extensions::new(), Extensions::default());
    }

    #[test]
    fn a_clone_holds_its_own_copies() {
        let original = Extensions::of(QuoteExt { update_id: 7 });
        let mut copy = original.clone();
        assert_eq!(copy, original);
        copy.get_mut::<QuoteExt>().unwrap().update_id = 8;
        assert_eq!(original.get::<QuoteExt>(), Some(&QuoteExt { update_id: 7 }));
        assert_ne!(copy, original);
    }

    #[test]
    fn the_type_ids_held_are_exposed() {
        let mut ext = Extensions::of(QuoteExt { update_id: 7 });
        ext.insert(BookExt { sequence: 9 }).unwrap();
        let mut ids: Vec<TypeId> = ext.type_ids().collect();
        let mut expected = vec![TypeId::of::<QuoteExt>(), TypeId::of::<BookExt>()];
        ids.sort();
        expected.sort();
        assert_eq!(ids, expected);
    }

    #[test]
    fn a_removed_value_comes_back_whole() {
        let mut ext = Extensions::of(QuoteExt { update_id: 7 });
        assert_eq!(ext.remove::<QuoteExt>(), Some(QuoteExt { update_id: 7 }));
        assert_eq!(ext.remove::<QuoteExt>(), None);
        assert!(ext.is_empty());
        ext.insert(QuoteExt { update_id: 8 }).unwrap();
        assert_eq!(ext.get::<QuoteExt>(), Some(&QuoteExt { update_id: 8 }));
    }

    #[test]
    fn debug_shows_each_value() {
        let ext = Extensions::of(QuoteExt { update_id: 7 });
        assert_eq!(format!("{ext:?}"), "{QuoteExt { update_id: 7 }}");
        assert_eq!(format!("{:?}", Extensions::new()), "{}");
    }

    #[test]
    fn declared_extensions_and_an_empty_set_pass() {
        let ext = Extensions::of(QuoteExt { update_id: 7 });
        assert_eq!(ext.ensure_declared(&[TypeId::of::<QuoteExt>()]), Ok(()));
        assert_eq!(
            ext.ensure_declared(&[TypeId::of::<BookExt>(), TypeId::of::<QuoteExt>()]),
            Ok(())
        );
        assert_eq!(Extensions::new().ensure_declared(&[]), Ok(()));
        assert_eq!(
            Extensions::new().ensure_declared(&[TypeId::of::<QuoteExt>()]),
            Ok(())
        );
    }

    #[test]
    fn an_undeclared_value_is_refused_by_its_type_name_as_invalid_request() {
        let mut ext = Extensions::of(QuoteExt { update_id: 7 });
        ext.insert(BookExt { sequence: 9 }).unwrap();

        let err = ext
            .ensure_declared(&[TypeId::of::<QuoteExt>()])
            .unwrap_err();
        assert!(err.type_name.ends_with("BookExt"), "{err}");
        assert_eq!(err.class(), Class::InvalidRequest);
        assert_eq!(
            err.to_string(),
            format!(
                "the request carries `{}`, an extension this venue does not declare",
                err.type_name
            )
        );

        let err = ext.ensure_declared(&[]).unwrap_err();
        assert_eq!(err.class(), Class::InvalidRequest);
    }

    #[test]
    fn the_first_undeclared_value_in_type_id_order_is_the_one_named() {
        let mut ext = Extensions::of(QuoteExt { update_id: 7 });
        ext.insert(BookExt { sequence: 9 }).unwrap();

        let first = if TypeId::of::<QuoteExt>() < TypeId::of::<BookExt>() {
            "QuoteExt"
        } else {
            "BookExt"
        };
        let err = ext.ensure_declared(&[]).unwrap_err();
        assert!(err.type_name.ends_with(first), "{err}");
    }

    #[test]
    fn declaring_a_type_the_request_lacks_does_not_excuse_one_it_has() {
        let ext = Extensions::of(QuoteExt { update_id: 7 });
        let err = ext.ensure_declared(&[TypeId::of::<BookExt>()]).unwrap_err();
        assert!(err.type_name.ends_with("QuoteExt"), "{err}");
    }
}