tagid 1.2.0

Defines a newtype labeled tagging for different types of ids.
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
use crate::envelope::metadata::MetaData;
use crate::envelope::{Correlation, ReceivedAt};
use crate::id::IdGenerator;
use crate::{Entity, Id, Label, Labeling};
#[cfg(feature = "functional")]
use frunk::{Monoid, Semigroup};
use iso8601_timestamp::Timestamp;
use pretty_type_name::pretty_type_name;
use serde::{Deserialize, Serialize, Serializer, de, ser::SerializeStruct};
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;

pub trait IntoEnvelope {
    type Content: Label;
    type IdGen: IdGenerator;

    fn into_envelope(self) -> Envelope<Self::Content, <Self::IdGen as IdGenerator>::IdType>;
    fn metadata(&self) -> &MetaData<Self::Content, <Self::IdGen as IdGenerator>::IdType>;
}

/// A metadata wrapper for a data set
#[derive(Clone)]
pub struct Envelope<T, ID>
where
    T: ?Sized,
{
    metadata: MetaData<T, ID>,
    content: T,
}

impl<T, ID> fmt::Debug for Envelope<T, ID>
where
    T: fmt::Debug,
    ID: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&format!("[{}]{{ {:?} }}", self.metadata, self.content))
    }
}

impl<T, ID> fmt::Display for Envelope<T, ID>
where
    T: fmt::Display,
    ID: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}]({})", self.metadata, self.content)
    }
}

impl<E> Envelope<E, <<E as Entity>::IdGen as IdGenerator>::IdType>
where
    E: Entity,
{
    pub fn from_entity(content: E) -> Self {
        Self {
            metadata: MetaData::default(),
            content,
        }
    }
}

impl<T, ID> Envelope<T, ID>
where
    T: Label,
{
    /// Create a new enveloped data.
    pub fn new<G>(content: T) -> Self
    where
        G: IdGenerator<IdType = ID>,
    {
        let correlation_id = Id::direct(T::labeler().label(), G::next_id_rep());

        Self {
            metadata: MetaData::from_parts(correlation_id, Timestamp::now_utc(), None),
            content,
        }
    }
}

impl<T, ID> Envelope<T, ID> {
    /// Directly create enveloped data with given metadata.
    pub const fn direct(content: T, metadata: MetaData<T, ID>) -> Self {
        Self { metadata, content }
    }

    /// Get a reference to the sensor data metadata.
    pub const fn metadata(&self) -> &MetaData<T, ID> {
        &self.metadata
    }

    /// Consumes self, returning the data item
    #[allow(clippy::missing_const_for_fn)]
    #[inline]
    pub fn into_inner(self) -> T {
        self.content
    }

    #[allow(clippy::missing_const_for_fn)]
    #[inline]
    pub fn into_parts(self) -> (MetaData<T, ID>, T) {
        (self.metadata, self.content)
    }

    #[inline]
    pub const fn from_parts(metadata: MetaData<T, ID>, content: T) -> Self {
        Self { metadata, content }
    }
}

impl<T, ID> Envelope<T, ID>
where
    T: Label,
    ID: Clone,
{
    pub fn adopt_metadata<U>(&mut self, new_metadata: MetaData<U, ID>) -> MetaData<T, ID>
    where
        U: Label,
    {
        let old_metadata = self.metadata.clone();
        self.metadata = new_metadata.relabel();
        old_metadata
    }

    pub fn map<F, U>(self, f: F) -> Envelope<U, ID>
    where
        U: Label,
        F: FnOnce(T) -> U,
    {
        let metadata = self.metadata.clone().relabel();
        Envelope {
            metadata,
            content: f(self.content),
        }
    }

    pub fn flat_map<F, U>(self, f: F) -> Envelope<U, ID>
    where
        U: Label,
        F: FnOnce(Self) -> U,
    {
        let metadata = self.metadata.clone().relabel();
        Envelope {
            metadata,
            content: f(self),
        }
    }
}

impl<T, ID> Envelope<T, ID>
where
    T: Label + Send,
    ID: Clone + Send,
{
    pub async fn and_then<Op, Fut, U>(self, f: Op) -> Envelope<U, ID>
    where
        U: Label + Send,
        Fut: Future<Output = U> + Send,
        Op: FnOnce(T) -> Fut + Send,
    {
        let metadata = self.metadata.clone().relabel();
        Envelope {
            metadata,
            content: f(self.content).await,
        }
    }
}

impl<E> Correlation for Envelope<E, <<E as Entity>::IdGen as IdGenerator>::IdType>
where
    E: Entity + Sync,
{
    type Correlated = E;
    type IdType = <<E as Entity>::IdGen as IdGenerator>::IdType;

    fn correlation(&self) -> &Id<Self::Correlated, Self::IdType> {
        self.metadata.correlation()
    }
}

impl<T, ID> ReceivedAt for Envelope<T, ID> {
    fn recv_timestamp(&self) -> Timestamp {
        self.metadata.recv_timestamp()
    }
}

impl<T, ID> Label for Envelope<T, ID>
where
    T: Label,
{
    type Labeler = <T as Label>::Labeler;

    fn labeler() -> Self::Labeler {
        <T as Label>::labeler()
    }
}

impl<T, ID> std::ops::Add for Envelope<T, ID>
where
    T: std::ops::Add<Output = T>,
    ID: PartialOrd,
{
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self::from_parts(self.metadata + rhs.metadata, self.content + rhs.content)
    }
}

#[cfg(feature = "functional")]
impl<E> Monoid for Envelope<E, <<E as Entity>::IdGen as IdGenerator>::IdType>
where
    E: Entity + Monoid,
    <<E as Entity>::IdGen as IdGenerator>::IdType: PartialOrd + Clone,
{
    fn empty() -> Self {
        Self::from_parts(
            <MetaData<E, <<E as Entity>::IdGen as IdGenerator>::IdType> as Monoid>::empty(),
            <E as Monoid>::empty(),
        )
    }
}

#[cfg(feature = "functional")]
impl<E> Semigroup for Envelope<E, <<E as Entity>::IdGen as IdGenerator>::IdType>
where
    E: Entity + Semigroup,
    <<E as Entity>::IdGen as IdGenerator>::IdType: PartialOrd + Clone,
{
    fn combine(&self, other: &Self) -> Self {
        Self::from_parts(
            self.metadata().combine(other.metadata()),
            self.content.combine(&other.content),
        )
    }
}

impl<E> IntoEnvelope for Envelope<E, <<E as Entity>::IdGen as IdGenerator>::IdType>
where
    E: Entity,
{
    type Content = E;
    type IdGen = <E as Entity>::IdGen;

    fn into_envelope(self) -> Envelope<Self::Content, <Self::IdGen as IdGenerator>::IdType> {
        self
    }

    fn metadata(&self) -> &MetaData<Self::Content, <Self::IdGen as IdGenerator>::IdType> {
        &self.metadata
    }
}

impl<T, ID> std::ops::Deref for Envelope<T, ID> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.content
    }
}

impl<T, ID> std::ops::DerefMut for Envelope<T, ID> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.content
    }
}

impl<T, ID> AsRef<T> for Envelope<T, ID> {
    fn as_ref(&self) -> &T {
        &self.content
    }
}

impl<T, ID> AsMut<T> for Envelope<T, ID> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.content
    }
}

impl<T, ID> PartialEq for Envelope<T, ID>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.content == other.content
    }
}

impl<T, ID> PartialEq<T> for Envelope<T, ID>
where
    T: PartialEq,
{
    fn eq(&self, other: &T) -> bool {
        &self.content == other
    }
}

impl<T, ID> Envelope<Option<T>, ID>
where
    T: Label,
    ID: Clone,
{
    /// Transposes an `Envelope` of an [`Option`] into an [`Option`] of `Envelope`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tagid::{CuidGenerator, Entity, Label, MakeLabeling};
    /// use tagid::envelope::{Envelope, MetaData};
    ///
    /// #[derive(Debug, Label, PartialEq)]
    /// struct Foo(pub i32);
    /// impl Entity for Foo { type IdGen = CuidGenerator; }
    ///
    /// let meta: MetaData<Foo, String> = MetaData::default();
    ///
    /// let x: Option<Envelope<Foo, String>> = Some(Envelope::from_parts(meta.clone(), Foo(5)));
    /// let y: Envelope<Option<Foo>, String> = Envelope::from_parts(meta.relabel(), Some(Foo(5)));
    /// assert_eq!(x, y.transpose());
    /// ```
    #[inline]
    pub fn transpose(self) -> Option<Envelope<T, ID>> {
        match self.content {
            Some(d) => Some(Envelope {
                content: d,
                metadata: self.metadata.relabel(),
            }),
            None => None,
        }
    }
}

impl<T, E, ID> Envelope<Result<T, E>, ID>
where
    T: Label,
    ID: Clone,
{
    /// Transposes a `Envelope` of a [`Result`] into a [`Result`] of `Envelope`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tagid::{CuidGenerator, Entity, Label, MakeLabeling};
    /// use tagid::envelope::{Envelope, MetaData};
    ///
    /// #[derive(Debug, Label, PartialEq)]
    /// struct Foo(pub i32);
    /// impl Entity for Foo { type IdGen = CuidGenerator; }
    ///
    /// let meta: MetaData<Foo, String> = MetaData::default();
    ///
    /// #[derive(Debug, Eq, PartialEq)]
    /// struct SomeErr;
    ///
    /// let x: Result<Envelope<Foo, String>, SomeErr> = Ok(Envelope::from_parts(meta.clone(), Foo(5)));
    /// let y: Envelope<Result<Foo, SomeErr>, String> = Envelope::from_parts(meta.relabel(), Ok(Foo(5)));
    /// assert_eq!(x, y.transpose());
    /// ```
    #[inline]
    pub fn transpose(self) -> Result<Envelope<T, ID>, E> {
        match self.content {
            Ok(content) => Ok(Envelope {
                content,
                metadata: self.metadata.relabel(),
            }),
            Err(e) => Err(e),
        }
    }
}

const ENV_METADATA: &str = "metadata";
const ENV_CONTENT: &str = "content";
const FIELDS: [&str; 2] = [ENV_METADATA, ENV_CONTENT];

impl<T, ID> Serialize for Envelope<T, ID>
where
    T: Serialize,
    ID: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Envelope", 2)?;
        state.serialize_field(ENV_METADATA, &self.metadata)?;
        state.serialize_field(ENV_CONTENT, &self.content)?;
        state.end()
    }
}

impl<'de, T, ID> Deserialize<'de> for Envelope<T, ID>
where
    T: Label + de::DeserializeOwned,
    ID: de::DeserializeOwned,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        enum Field {
            MetaData,
            Content,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                struct FieldVisitor;

                impl de::Visitor<'_> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str("`metadata` or `content`")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            ENV_METADATA => Ok(Field::MetaData),
                            ENV_CONTENT => Ok(Field::Content),
                            _ => Err(de::Error::unknown_field(value, &FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct EnvelopeVisitor<T0, ID0> {
            marker: PhantomData<(T0, ID0)>,
        }

        impl<T0, ID0> EnvelopeVisitor<T0, ID0> {
            pub const fn new() -> Self {
                Self {
                    marker: PhantomData,
                }
            }
        }

        impl<'de, T0, ID0> de::Visitor<'de> for EnvelopeVisitor<T0, ID0>
        where
            T0: Label + de::DeserializeOwned,
            ID0: de::DeserializeOwned,
        {
            type Value = Envelope<T0, ID0>;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(
                    format!(
                        "struct Envelope<{}, {}>",
                        pretty_type_name::<T0>(),
                        pretty_type_name::<ID0>(),
                    )
                    .as_str(),
                )
            }

            fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
            where
                V: de::SeqAccess<'de>,
            {
                let metadata: MetaData<T0, ID0> = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let content: T0 = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                Ok(Envelope::from_parts(metadata, content))
            }

            fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
            where
                V: de::MapAccess<'de>,
            {
                let mut metadata = None;
                let mut content = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::MetaData => {
                            if metadata.is_some() {
                                return Err(de::Error::duplicate_field(ENV_METADATA));
                            }
                            metadata = Some(map.next_value()?);
                        }
                        Field::Content => {
                            if content.is_some() {
                                return Err(de::Error::duplicate_field(ENV_CONTENT));
                            }
                            content = Some(map.next_value()?);
                        }
                    }
                }

                let metadata: MetaData<T0, ID0> =
                    metadata.ok_or_else(|| de::Error::missing_field(ENV_METADATA))?;
                let content: T0 = content.ok_or_else(|| de::Error::missing_field(ENV_CONTENT))?;
                Ok(Envelope::from_parts(metadata, content))
            }
        }

        deserializer.deserialize_struct("Envelope", &FIELDS, EnvelopeVisitor::<T, ID>::new())
    }
}