Skip to main content

smithy4rs_core/schema/
documents.rs

1use std::{error::Error, fmt::Debug, sync::LazyLock};
2
3use thiserror::Error;
4
5use crate::{
6    BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
7    schema::{
8        SchemaShape, ShapeId, ShapeType,
9        default::{Number, Value},
10        prelude::*,
11    },
12    smithy,
13};
14
15// ============================================================================
16// Base Document Wrapper and trait
17// ============================================================================
18
19/// A Smithy [document](https://smithy.io/2.0/spec/simple-types.html#document) type,
20/// representing untyped data in the Smithy data model.
21///
22/// TODO(doc): Update with dyn doc model
23///
24/// ### Smithy Data Model
25///
26/// The Smithy data model consists of:
27/// - Numbers: `byte`, `short`, `integer`, `long`, `float`, `double`, `bigInteger`, `bigDecimal`.
28///   `IntEnum` shapes are represented as integers in the Smithy data model.
29/// - `boolean`
30/// - `blob`
31/// - `string`: `enum` shapes are represented as strings in the Smithy data model
32/// - `timestamp`: Represented as an [`Instant`]
33/// - `list`: list of Documents
34/// - `map`: map of int|long|string keys to Document values
35/// - `struct`: structure or union
36///
37/// ## Document Properties
38/// 1. Shape Conversion - All generated shapes should be able to be converted to/from a document
39/// 2. Lossless Serialization: Documents created from a shape should serialize exactly the same as the shape they are created from. I.e.
40///
41/// ```rust,ignore
42/// // These two should be equivalent
43/// my_smithy_shape.serialize(serializer)?;
44/// my_smithy_shape.as_document().serialize(serializer)?;
45/// ```
46///
47/// 3. Lossless Deserialization: Deserializing to a document then converting to a shape should be the same as deserializing to that shape. I.e. :
48///
49/// ```rust,ignore
50/// // These two should be equivalent
51/// let my_shape = deserializer::deserialize::<MyShape>::();
52/// let my_shape = deserializer::deserialize::<Document>::().into();
53/// ```
54/// This is particularly important for dealing with errors, events, and over-the-wire polymorphism.
55///
56/// 4. Protocol Smoothing: Documents should try to smooth over any protocol-specific incompatibilities with the smithy data model.
57/// 5. Discriminators - Documents with an encloded type should be able to be (de)serialized with data that identifies their
58///
59/// ### Protocol Smoothing
60/// Because Document types are a protocol-agnostic view of untyped data, Protocol codecs should attempt to smooth over
61/// any protocol-specific incompatibilities with the Smithy data model when deserializing into a document type.
62///
63/// For example, If a protocol represents a blob as a base64 encoded string, then deserializing the value into a
64/// document should base64 decode the value and use the underlying bytes as the blob value in the document.
65/// When the document is re-serialized by the same protocol, the protocol should handle conversion from a byte
66/// buffer back to a base64 encoded string.
67///
68/// ### Lossless serialization
69/// Point two *REQUIRES* that documents created from a shape have the exact same schema as that shape.
70///
71/// A good example of why is to consider the following Smithy Shape:
72///
73/// ```smithy
74/// structure MyStruct {
75///     @jsonName("foo")
76///     bar: String
77/// }
78/// ```
79///
80/// When we go to serialize an instance of this shape with a JSON protocol we would expect that the member `bar`
81/// is renamed to `foo` in the serialized JSON data:
82///
83/// ```rust,ignore
84/// let myStructInstance = MyStruct::builder().bar("my-string").build()?;
85/// myStructInstance.serialize(jsonSerializer);  // -> Yields `{ "foo": "my-string" }`
86/// ```
87///
88/// The JSON protocol will achieve this conversion by discovering the `jsonName` trait on the
89/// schema of the `myStructInstance` `bar` member.
90///
91/// Another good example is the case of a `@sensitive` field on a structure:
92///
93/// ```smithy
94/// structure MyStructRedacted {
95///     @sensitive
96///     password: String
97/// }
98/// ```
99///
100/// `Display`-ing such a structure should result in the `@sensitive` field being redacted:
101/// ```rust,ignore
102/// let myStructInstance = MyStruct::builder().password("Secret".to_string()).build()?;
103/// assert_eq!("MyStruct[password:**REDACTED**]", format!("{myStructInstance}"))
104/// ```
105///
106/// We do _not_ want conversion to a document to suddenly start leaking a sensitive field.
107///
108/// In order to retain trait information, Documents created from a shape MUST retain that shape’s Schema.
109///
110/// ### Discriminators
111/// Document types may have a `ShapeId` that indicates the type they correspond to.
112/// This ID can be serialized to allow consumers to handle over the wire polymorphism (primarily for over-the wire polymorphism).
113/// Typed documents must return the shape ID of the enclosed shape.
114///
115/// For example, let’s say we convert a shape of type `com.example#MyShape` into a document type.
116/// The document would then store the `ShapeID` as its discriminator.
117///
118/// Serializing this document with a JSON protocol might result in a field `__type` being added to the output JSON :
119///
120/// ```json
121/// {
122///     "__type": "com.example#MyShape",
123///     "other": {}
124/// }
125/// ```
126///
127/// <div class="warning">
128/// Discriminators are only really useful for documents (or other structs) being serialized as Structure and Union types.
129/// As such they, are serialized by the [`StructSerializer::serialize_discriminator`] method.
130/// </div>
131///
132///
133/// Similarly, a deserializer might want to pull the `__type` data from a JSON blob when deserializing into a Document type.
134///
135///
136/// ## Lossless Deserialization
137///
138/// Let’s say we want to deserialize an error type that has the schema:
139/// ```smithy
140/// @error("client")
141/// @http
142/// struct MyClientError {
143///     @required
144///     message: String
145///     @jsonName("foo")
146///     bar: String
147/// }
148/// ```
149///
150/// Over the wire we might get a JSON body like:
151///
152/// ```json
153/// {
154///     "__type": "com.example#MyClientError",
155///     "message": "Something broke pretty bad!",
156///     "foo": "quux!"
157/// }
158/// ```
159///
160/// Because the error response _could_ be one of multiple error types, we don't know the type
161/// to deserialize it to in advance.
162/// We deserialize the JSON data to a Document, extract the discriminator, and use it to:
163///
164/// ```rust,ignore
165/// let error_document = Document::deserialize(json_deserializer)?;
166/// let builder = error_document.get_builder(error_document.discriminator());
167/// let output = builder.deserialize(error_document)?.build();
168/// ```
169///
170/// The initial `error_document` has no schema information (beyond the base `Document` schema), so it does not perform any protocol-specific
171/// conversions during deserialization (i.e. it won't convert the field name `foo` to `bar` based on the `@jsonName` trait).
172///
173/// However, when we deserialize the document into the final Error type we need to execute the protocol-specific handling of the `jsonName` trait.
174pub trait Document: SchemaShape + Send + Sync {
175    /// Get the discriminator (type ID) of a type document
176    ///
177    /// The discriminator is primarily used to implement polymorphism using documents in deserialization.
178    ///
179    /// <div class="warning">
180    /// It is expected that protocols set the discriminator on deserialization if applicable
181    /// </div>
182    #[must_use]
183    fn discriminator(&self) -> Option<&ShapeId>;
184
185    // ========== Basic info Methods ==========
186
187    /// Get the Shape Type for the underlying contents of the document.
188    ///
189    /// The type returned from this method will differ from the type of the document (which will
190    /// always be [`ShapeType::Document`]).
191    ///
192    /// NOTE: It is important that `self.get_type()` NEVER return `Document` as the type as that
193    /// will result in infinite loops in serializers.
194    ///
195    /// ### Enums
196    /// - `enum` shapes: Enum shapes are treated as a `string`, and variants can be found in
197    ///   the corresponding schema for the document.
198    ///  - `intEnum` shapes: Enum shapes are treated as an `integer`, and variants can be found in
199    ///    the corresponding schema for the document.
200    #[must_use]
201    fn get_type(&self) -> Option<&ShapeType>;
202
203    /// Get the number of elements in an array document, or the number of key value pairs in a map document.
204    ///
205    /// *NOTE*: Should return `0` for all other
206    #[must_use]
207    fn size(&self) -> usize;
208
209    // ========== Borrowed data conversions ==========
210
211    /// Get the `blob` value of the Document if it is a `blob`.
212    ///
213    /// Returns `None` if the document could not be converted to a
214    /// `blob` ([`ByteBuffer`]) value.
215    #[must_use]
216    fn as_blob(&self) -> Option<&ByteBuffer>;
217
218    /// Get the `boolean` value of the Document if it is a `boolean` or can be converted into one.
219    ///
220    /// Returns `None` if the document could not be converted to a
221    /// `boolean` value.
222    #[must_use]
223    fn as_bool(&self) -> Option<bool>;
224
225    /// Get the `string` value of the Document if it is a `string` or can be converted into one.
226    ///
227    /// Returns `None` if the document could not be converted to a
228    /// `string` value.
229    #[must_use]
230    fn as_string(&self) -> Option<&str>;
231
232    /// Get the `timestamp` value of the Document if it is a `timestamp` or can be converted into one.
233    ///
234    /// Returns `None` if the document could not be converted to a
235    /// `timestamp` ([`Instant`]) value.
236    #[must_use]
237    fn as_timestamp(&self) -> Option<&Instant>;
238
239    /// Get the `byte` value of the Document if it is a `byte` or can be converted into one.
240    ///
241    /// Returns `None` if the document could not be converted to a
242    /// `byte` (`i8`) value.
243    #[must_use]
244    fn as_byte(&self) -> Option<i8>;
245
246    /// Get the `short` value of the Document if it is a `short` or can be converted into one.
247    ///
248    /// Returns `None` if the document could not be converted to a
249    /// `short` (`i16`) value.
250    #[must_use]
251    fn as_short(&self) -> Option<i16>;
252
253    /// Get the `integer` value of the Document if it is an `integer` or can be converted into one.
254    ///
255    /// Returns `None` if the document could not be converted to an
256    /// `integer` (`i32`) value.
257    #[must_use]
258    fn as_integer(&self) -> Option<i32>;
259
260    /// Get the `long` value of the Document if it is a `long` or can be converted into one.
261    ///
262    /// Returns `None` if the document could not be converted to a
263    /// `long` (`i64`) value.
264    #[must_use]
265    fn as_long(&self) -> Option<i64>;
266
267    /// Get the `float` value of the Document if it is a `float` or can be converted into one.
268    ///
269    /// Returns `None` if the document could not be converted to
270    /// `float` (`f32`) value.
271    #[must_use]
272    fn as_float(&self) -> Option<f32>;
273
274    /// Get the `decimal` value of the Document if it is a `decimal` or can be converted into one.
275    ///
276    /// Returns `None` if the document could not be converted to
277    /// `double` (`f64`) value.
278    #[must_use]
279    fn as_double(&self) -> Option<f64>;
280
281    /// Get the `bigInteger` value of the Document if it is a `bigInteger` or can be converted into one.
282    ///
283    /// Returns `None` if the document could not be converted to
284    /// `bigInteger` ([`BigInt`]) value.
285    #[must_use]
286    fn as_big_integer(&self) -> Option<&BigInt>;
287
288    /// Get the `bigDecimal` value of the Document if it is a `bigDecimal` or can be converted into one.
289    ///
290    /// Returns `None` if the document could not be converted to
291    /// `bigDecimal` ([`BigDecimal`]) value.
292    #[must_use]
293    fn as_big_decimal(&self) -> Option<&BigDecimal>;
294
295    /// Get the list contents of the Document if it is a list.
296    ///
297    /// Returns `None` if the document is not a list.
298    #[must_use]
299    fn as_list(&self) -> Option<&Vec<Box<dyn Document>>>;
300
301    /// Get the map contents of the Document if it is a map.
302    ///
303    /// Returns `None` if the document is not a map.
304    #[must_use]
305    fn as_map(&self) -> Option<&IndexMap<String, Box<dyn Document>>>;
306
307    /// Returns true if the document represents a `Null` value.
308    #[must_use]
309    fn is_null(&self) -> bool;
310
311    // ========== Owned data conversions ==========
312
313    /// Convert the [`Document`] to a `blob`.
314    ///
315    /// # Errors
316    /// Returns a [`DocumentError`] if the document could not be converted to a
317    /// `blob` ([`ByteBuffer`]) value.
318    fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError>;
319
320    /// Convert the [`Document`] to a `boolean`.
321    ///
322    /// # Errors
323    /// Returns a [`DocumentError`] if the document could not be converted to a
324    /// `boolean` value.
325    fn into_bool(self: Box<Self>) -> Result<bool, DocumentError>;
326
327    /// Convert the [`Document`] to a `string`.
328    ///
329    /// # Errors
330    /// Returns a [`DocumentError`] if the document could not be converted to a
331    /// `string` value.
332    fn into_string(self: Box<Self>) -> Result<String, DocumentError>;
333
334    /// Convert the [`Document`] to a `timestamp`.
335    ///
336    /// # Errors
337    /// Returns a [`DocumentError`] if the document could not be converted to a
338    /// `timestamp` ([`Instant`]) value.
339    fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError>;
340
341    /// Convert the [`Document`] to a `byte`.
342    ///
343    /// # Errors
344    /// Returns a [`DocumentError`] if the document could not be converted to a
345    /// `byte` (`i8`) value.
346    fn into_byte(self: Box<Self>) -> Result<i8, DocumentError>;
347
348    /// Convert the [`Document`] to a `short`.
349    ///
350    /// # Errors
351    /// Returns a [`DocumentError`] if the document could not be converted to a
352    /// `short` (`i16`) value.
353    fn into_short(self: Box<Self>) -> Result<i16, DocumentError>;
354
355    /// Convert the [`Document`] to an `integer`.
356    ///
357    /// # Errors
358    /// Returns a [`DocumentError`] if the document could not be converted to a
359    /// `integer` (`i32`) value.
360    fn into_integer(self: Box<Self>) -> Result<i32, DocumentError>;
361
362    /// Convert the [`Document`] to a `long`.
363    ///
364    /// # Errors
365    /// Returns a [`DocumentError`] if the document could not be converted to a
366    /// `long` (`i64`) value.
367    fn into_long(self: Box<Self>) -> Result<i64, DocumentError>;
368
369    /// Convert the [`Document`] to a `float`.
370    ///
371    /// # Errors
372    /// Returns a [`DocumentError`] if the document could not be converted to a
373    /// `float` (`f32`) value.
374    fn into_float(self: Box<Self>) -> Result<f32, DocumentError>;
375
376    /// Convert the [`Document`] to a `double`.
377    ///
378    /// # Errors
379    /// Returns a [`DocumentError`] if the document could not be converted to a
380    /// `double` (`f64`) value.
381    fn into_double(self: Box<Self>) -> Result<f64, DocumentError>;
382
383    /// Convert the [`Document`] to a `bigInteger`.
384    ///
385    /// # Errors
386    /// Returns a [`DocumentError`] if the document could not be converted to a
387    /// `bigInteger` ([`BigInt`]) value.
388    fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError>;
389
390    /// Convert the [`Document`] to a `bigDecimal`.
391    ///
392    /// # Errors
393    /// Returns a [`DocumentError`] if the document could not be converted to a
394    /// `bigDecimal` ([`BigDecimal`]) value.
395    fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError>;
396
397    /// Convert the [`Document`] to a `list`.
398    ///
399    /// # Errors
400    /// Returns a [`DocumentError`] if the document is not a list.
401    fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn Document>>, DocumentError>;
402
403    /// Convert the [`Document`] to a `map`.
404    ///
405    /// # Errors
406    /// Returns a [`DocumentError`] if the document is not a map.
407    fn into_map(self: Box<Self>) -> Result<IndexMap<String, Box<dyn Document>>, DocumentError>;
408
409    /// Clone implementation necessary to satisfy the compiler
410    fn box_clone(&self) -> Box<dyn Document>;
411}
412
413// ================================================================
414// Blanket impl for dyn Documents
415// ================================================================
416
417impl PartialEq for dyn Document {
418    fn eq(&self, other: &Self) -> bool {
419        if self.schema() != other.schema() {
420            return false;
421        }
422        if self.discriminator() != other.discriminator() {
423            return false;
424        }
425        // TODO(numerical comparison): We should compare compatible numeric types
426        // if possible. This is just a placeholder to get test working.
427        match (self.get_type(), other.get_type()) {
428            (Some(ShapeType::String), Some(ShapeType::String)) => {
429                self.as_string() == other.as_string()
430            }
431            (Some(ShapeType::Blob), Some(ShapeType::Blob)) => self.as_blob() == other.as_blob(),
432            (Some(ShapeType::Boolean), Some(ShapeType::Boolean)) => {
433                self.as_bool() == other.as_bool()
434            }
435            (Some(ShapeType::Timestamp), Some(ShapeType::Timestamp)) => {
436                self.as_timestamp() == other.as_timestamp()
437            }
438            (Some(ShapeType::Byte), Some(ShapeType::Byte)) => self.as_byte() == other.as_byte(),
439            (Some(ShapeType::Short), Some(ShapeType::Short)) => self.as_short() == other.as_short(),
440            (Some(ShapeType::Integer), Some(ShapeType::Integer)) => {
441                self.as_integer() == other.as_integer()
442            }
443            (Some(ShapeType::Long), Some(ShapeType::Long)) => self.as_long() == other.as_long(),
444            (Some(ShapeType::Float), Some(ShapeType::Float)) => self.as_float() == other.as_float(),
445            (Some(ShapeType::Double), Some(ShapeType::Double)) => {
446                self.as_double() == other.as_double()
447            }
448            (Some(ShapeType::BigInteger), Some(ShapeType::BigInteger)) => {
449                self.as_big_integer() == other.as_big_integer()
450            }
451            (Some(ShapeType::BigDecimal), Some(ShapeType::BigDecimal)) => {
452                self.as_big_decimal() == other.as_big_decimal()
453            }
454            (Some(ShapeType::List), Some(ShapeType::List)) => self.as_list() == other.as_list(),
455            (Some(ShapeType::Map), Some(ShapeType::Map)) => self.as_map() == other.as_map(),
456            (None, None) => true,
457            _ => false,
458        }
459    }
460}
461
462impl Clone for Box<dyn Document> {
463    #[inline]
464    fn clone(&self) -> Self {
465        self.box_clone()
466    }
467}
468
469// ============================================================================
470// Document Errors
471// ============================================================================
472
473/// Errors that can occur when converting to/from a document type.
474#[derive(Error, Debug)]
475pub enum DocumentError {
476    /// Document failed to serialize to a data sink
477    #[error("Failed to convert document to type {0}")]
478    DocumentSerialization(String),
479    /// Could not convert a type _into_ a document
480    #[error("Failed to convert document to type {0}")]
481    DocumentConversion(String),
482    /// An unknown error
483    #[error("Encountered unknown error")]
484    Unknown(#[from] Box<dyn Error>),
485    /// A custom error
486    #[error("Encountered error: {0}")]
487    CustomError(String),
488}
489
490impl crate::serde::de::Error for DocumentError {
491    fn custom<T: std::fmt::Display>(msg: T) -> Self {
492        DocumentError::CustomError(msg.to_string())
493    }
494}
495
496// ============================================================================
497// Convert Document into types
498// ============================================================================
499
500impl TryFrom<Box<dyn Document>> for ByteBuffer {
501    type Error = DocumentError;
502
503    #[inline]
504    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
505        value.into_blob()
506    }
507}
508
509impl TryFrom<Box<dyn Document>> for bool {
510    type Error = DocumentError;
511
512    #[inline]
513    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
514        value.into_bool()
515    }
516}
517
518impl TryFrom<Box<dyn Document>> for String {
519    type Error = DocumentError;
520
521    #[inline]
522    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
523        value.into_string()
524    }
525}
526
527impl TryFrom<Box<dyn Document>> for Instant {
528    type Error = DocumentError;
529
530    #[inline]
531    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
532        value.into_timestamp()
533    }
534}
535
536impl TryFrom<Box<dyn Document>> for i8 {
537    type Error = DocumentError;
538
539    #[inline]
540    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
541        value.into_byte()
542    }
543}
544
545impl TryFrom<Box<dyn Document>> for i16 {
546    type Error = DocumentError;
547
548    #[inline]
549    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
550        value.into_short()
551    }
552}
553
554impl TryFrom<Box<dyn Document>> for i32 {
555    type Error = DocumentError;
556
557    #[inline]
558    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
559        value.into_integer()
560    }
561}
562
563impl TryFrom<Box<dyn Document>> for i64 {
564    type Error = DocumentError;
565
566    #[inline]
567    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
568        value.into_long()
569    }
570}
571
572impl TryFrom<Box<dyn Document>> for f32 {
573    type Error = DocumentError;
574
575    #[inline]
576    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
577        value.into_float()
578    }
579}
580
581impl TryFrom<Box<dyn Document>> for f64 {
582    type Error = DocumentError;
583
584    #[inline]
585    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
586        value.into_double()
587    }
588}
589
590impl TryFrom<Box<dyn Document>> for BigInt {
591    type Error = DocumentError;
592
593    #[inline]
594    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
595        value.into_big_integer()
596    }
597}
598
599impl TryFrom<Box<dyn Document>> for BigDecimal {
600    type Error = DocumentError;
601
602    #[inline]
603    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
604        value.into_big_decimal()
605    }
606}
607
608impl TryFrom<Box<dyn Document>> for Vec<Box<dyn Document>> {
609    type Error = DocumentError;
610
611    #[inline]
612    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
613        value.into_list()
614    }
615}
616
617impl TryFrom<Box<dyn Document>> for IndexMap<String, Box<dyn Document>> {
618    type Error = DocumentError;
619
620    #[inline]
621    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
622        value.into_map()
623    }
624}
625
626impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>> for Vec<T> {
627    type Error = DocumentError;
628
629    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
630        let vec = value.into_list()?;
631        let mut result: Vec<T> = Vec::new();
632        for doc in vec {
633            match T::try_from(doc.clone()) {
634                Ok(val) => result.push(val),
635                Err(e) => return Err(e),
636            }
637        }
638        Ok(result)
639    }
640}
641
642impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
643    for IndexMap<String, T>
644{
645    type Error = DocumentError;
646
647    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
648        let map = value.into_map()?;
649        let mut result: IndexMap<String, T> = IndexMap::new();
650        for (key, val) in map {
651            let _ = match T::try_from(val.clone()) {
652                Ok(val) => result.insert(key.clone(), val),
653                Err(e) => return Err(e),
654            };
655        }
656        Ok(result)
657    }
658}
659
660impl<T: TryFrom<Box<dyn Document>, Error = DocumentError>> TryFrom<Box<dyn Document>>
661    for Option<T>
662{
663    type Error = DocumentError;
664
665    fn try_from(value: Box<dyn Document>) -> Result<Self, Self::Error> {
666        if value.is_null() {
667            return Ok(None);
668        }
669        Ok(Some(value.try_into()?))
670    }
671}
672
673// ============================================================================
674// Default Document Implementation
675// ============================================================================
676
677pub(crate) mod default {
678    use bigdecimal::ToPrimitive;
679
680    use crate::{
681        BigDecimal, BigInt, ByteBuffer, IndexMap, Instant,
682        schema::{DocumentError, SchemaRef, SchemaShape, ShapeId, ShapeType},
683    };
684
685    #[derive(Clone, PartialEq, Debug)]
686    pub struct Document {
687        pub schema: SchemaRef,
688        pub value: Value,
689        pub discriminator: Option<ShapeId>,
690    }
691
692    impl SchemaShape for Document {
693        fn schema(&self) -> &SchemaRef {
694            &self.schema
695        }
696    }
697
698    #[derive(Clone, PartialEq, Debug)]
699    pub enum Value {
700        Null,
701        Number(Number),
702        Boolean(bool),
703        Blob(ByteBuffer),
704        String(String),
705        Timestamp(Instant),
706        List(Vec<Box<dyn super::Document>>),
707        Map(IndexMap<String, Box<dyn super::Document>>),
708    }
709
710    impl super::Document for Document {
711        fn discriminator(&self) -> Option<&ShapeId> {
712            self.discriminator.as_ref()
713        }
714
715        fn get_type(&self) -> Option<&ShapeType> {
716            match &self.value {
717                Value::Number(n) => match n {
718                    Number::Byte(_) => Some(&ShapeType::Byte),
719                    Number::Short(_) => Some(&ShapeType::Short),
720                    Number::Integer(_) => Some(&ShapeType::Integer),
721                    Number::Long(_) => Some(&ShapeType::Long),
722                    Number::BigInt(_) => Some(&ShapeType::BigInteger),
723                    Number::Float(_) => Some(&ShapeType::Float),
724                    Number::Double(_) => Some(&ShapeType::Double),
725                    Number::BigDecimal(_) => Some(&ShapeType::BigDecimal),
726                },
727                Value::Boolean(_) => Some(&ShapeType::Boolean),
728                Value::Blob(_) => Some(&ShapeType::Blob),
729                Value::String(_) => Some(&ShapeType::String),
730                Value::Timestamp(_) => Some(&ShapeType::Timestamp),
731                Value::List(_) => Some(&ShapeType::List),
732                Value::Map(_) => {
733                    if self.schema.shape_type() == &ShapeType::Map {
734                        Some(&ShapeType::Map)
735                    } else {
736                        // If we created the document from a structure schema, treat it as a struct
737                        Some(&ShapeType::Structure)
738                    }
739                }
740                // Null is not representable as a shape type
741                Value::Null => None,
742            }
743        }
744
745        fn size(&self) -> usize {
746            match &self.value {
747                Value::List(v) => v.len(),
748                Value::Map(v) => v.len(),
749                _ => 0,
750            }
751        }
752
753        fn as_blob(&self) -> Option<&ByteBuffer> {
754            if let Value::Blob(b) = &self.value {
755                Some(b)
756            } else {
757                None
758            }
759        }
760
761        fn as_bool(&self) -> Option<bool> {
762            if let Value::Boolean(b) = &self.value {
763                Some(*b)
764            } else {
765                None
766            }
767        }
768
769        fn as_string(&self) -> Option<&str> {
770            if let Value::String(s) = &self.value {
771                Some(s.as_str())
772            } else {
773                None
774            }
775        }
776
777        fn as_timestamp(&self) -> Option<&Instant> {
778            if let Value::Timestamp(t) = &self.value {
779                Some(t)
780            } else {
781                None
782            }
783        }
784
785        fn as_byte(&self) -> Option<i8> {
786            match &self.value {
787                Value::Number(n) => match n {
788                    &Number::Byte(b) => Some(b),
789                    &Number::Short(s) => s.try_into().ok(),
790                    &Number::Integer(i) => i.try_into().ok(),
791                    &Number::Long(l) => l.try_into().ok(),
792                    Number::BigInt(b) => b.to_i8(),
793                    _ => None,
794                },
795                _ => None,
796            }
797        }
798
799        fn as_short(&self) -> Option<i16> {
800            match &self.value {
801                Value::Number(n) => match n {
802                    &Number::Byte(b) => Some(b.into()),
803                    &Number::Short(s) => Some(s),
804                    &Number::Integer(i) => i.try_into().ok(),
805                    &Number::Long(l) => l.try_into().ok(),
806                    Number::BigInt(b) => b.to_i16(),
807                    _ => None,
808                },
809                _ => None,
810            }
811        }
812
813        fn as_integer(&self) -> Option<i32> {
814            match &self.value {
815                Value::Number(n) => match n {
816                    &Number::Byte(b) => Some(b.into()),
817                    &Number::Short(s) => Some(s.into()),
818                    &Number::Integer(i) => Some(i),
819                    &Number::Long(l) => l.try_into().ok(),
820                    Number::BigInt(b) => b.to_i32(),
821                    _ => None,
822                },
823                _ => None,
824            }
825        }
826
827        fn as_long(&self) -> Option<i64> {
828            match &self.value {
829                Value::Number(n) => match n {
830                    &Number::Byte(b) => Some(b.into()),
831                    &Number::Short(s) => Some(s.into()),
832                    &Number::Integer(i) => Some(i.into()),
833                    &Number::Long(l) => Some(l),
834                    Number::BigInt(b) => b.to_i64(),
835                    _ => None,
836                },
837                _ => None,
838            }
839        }
840
841        fn as_float(&self) -> Option<f32> {
842            match &self.value {
843                Value::Number(n) => match n {
844                    &Number::Float(f) => Some(f),
845                    &Number::Double(d) => Some(d as f32),
846                    Number::BigDecimal(b) => b.to_f32(),
847                    _ => None,
848                },
849                _ => None,
850            }
851        }
852
853        fn as_double(&self) -> Option<f64> {
854            match &self.value {
855                Value::Number(n) => match n {
856                    &Number::Float(f) => Some(f.into()),
857                    &Number::Double(d) => Some(d),
858                    Number::BigDecimal(b) => b.to_f64(),
859                    _ => None,
860                },
861                _ => None,
862            }
863        }
864
865        fn as_big_integer(&self) -> Option<&BigInt> {
866            todo!()
867        }
868
869        fn as_big_decimal(&self) -> Option<&BigDecimal> {
870            todo!()
871        }
872
873        fn as_list(&self) -> Option<&Vec<Box<dyn super::Document>>> {
874            if let Value::List(document_list) = &self.value {
875                Some(document_list)
876            } else {
877                None
878            }
879        }
880
881        fn as_map(&self) -> Option<&IndexMap<String, Box<dyn super::Document>>> {
882            if let Value::Map(document_map) = &self.value {
883                Some(document_map)
884            } else {
885                None
886            }
887        }
888
889        fn is_null(&self) -> bool {
890            matches!(self.value, Value::Null)
891        }
892
893        fn into_blob(self: Box<Self>) -> Result<ByteBuffer, DocumentError> {
894            if let Value::Blob(value) = self.value {
895                Ok(value)
896            } else {
897                Err(DocumentError::DocumentConversion(
898                    "Expected blob document".to_string(),
899                ))
900            }
901        }
902
903        fn into_bool(self: Box<Self>) -> Result<bool, DocumentError> {
904            if let Value::Boolean(value) = self.value {
905                Ok(value)
906            } else {
907                Err(DocumentError::DocumentConversion(
908                    "Expected boolean document".to_string(),
909                ))
910            }
911        }
912
913        fn into_string(self: Box<Self>) -> Result<String, DocumentError> {
914            if let Value::String(value) = self.value {
915                Ok(value)
916            } else {
917                Err(DocumentError::DocumentConversion(
918                    "Expected string document".to_string(),
919                ))
920            }
921        }
922
923        fn into_timestamp(self: Box<Self>) -> Result<Instant, DocumentError> {
924            if let Value::Timestamp(value) = self.value {
925                Ok(value)
926            } else {
927                Err(DocumentError::DocumentConversion(
928                    "Expected timestamp document".to_string(),
929                ))
930            }
931        }
932
933        // TODO(numeric conversion): Review these numeric conversions.
934        fn into_byte(self: Box<Self>) -> Result<i8, DocumentError> {
935            self.as_byte().ok_or_else(|| {
936                DocumentError::DocumentConversion("Expected byte document".to_string())
937            })
938        }
939
940        fn into_short(self: Box<Self>) -> Result<i16, DocumentError> {
941            self.as_short().ok_or_else(|| {
942                DocumentError::DocumentConversion("Expected short document".to_string())
943            })
944        }
945
946        fn into_integer(self: Box<Self>) -> Result<i32, DocumentError> {
947            self.as_integer().ok_or_else(|| {
948                DocumentError::DocumentConversion("Expected integer document".to_string())
949            })
950        }
951
952        fn into_long(self: Box<Self>) -> Result<i64, DocumentError> {
953            self.as_long().ok_or_else(|| {
954                DocumentError::DocumentConversion("Expected long document".to_string())
955            })
956        }
957
958        fn into_float(self: Box<Self>) -> Result<f32, DocumentError> {
959            self.as_float().ok_or_else(|| {
960                DocumentError::DocumentConversion("Expected float document".to_string())
961            })
962        }
963
964        fn into_double(self: Box<Self>) -> Result<f64, DocumentError> {
965            self.as_double().ok_or_else(|| {
966                DocumentError::DocumentConversion("Expected double document".to_string())
967            })
968        }
969
970        // TODO(numeric conversion): These shouldnt need to clone.
971        fn into_big_integer(self: Box<Self>) -> Result<BigInt, DocumentError> {
972            self.as_big_integer().cloned().ok_or_else(|| {
973                DocumentError::DocumentConversion("Expected bigInteger document".to_string())
974            })
975        }
976
977        fn into_big_decimal(self: Box<Self>) -> Result<BigDecimal, DocumentError> {
978            self.as_big_decimal().cloned().ok_or_else(|| {
979                DocumentError::DocumentConversion("Expected bigInteger document".to_string())
980            })
981        }
982
983        fn into_list(self: Box<Self>) -> Result<Vec<Box<dyn super::Document>>, DocumentError> {
984            if let Value::List(value) = self.value {
985                Ok(value)
986            } else {
987                Err(DocumentError::DocumentConversion(
988                    "Expected list document".to_string(),
989                ))
990            }
991        }
992
993        fn into_map(
994            self: Box<Self>,
995        ) -> Result<IndexMap<String, Box<dyn super::Document>>, DocumentError> {
996            if let Value::Map(value) = self.value {
997                Ok(value)
998            } else {
999                Err(DocumentError::DocumentConversion(
1000                    "Expected map document".to_string(),
1001                ))
1002            }
1003        }
1004
1005        fn box_clone(&self) -> Box<dyn super::Document> {
1006            Box::new(self.clone())
1007        }
1008    }
1009
1010    /// Represents numbers in the smithy data model
1011    ///
1012    /// Smithy numbers types include: byte, short, integer, long, float, double, bigInteger, bigDecimal.
1013    ///
1014    /// <div class ="note">
1015    /// **NOTE**: `IntEnum` shapes are represented as integers in the Smithy data model.
1016    /// </div>
1017    #[derive(Debug, Clone, PartialEq)]
1018    pub enum Number {
1019        Byte(i8),
1020        Short(i16),
1021        Integer(i32),
1022        Long(i64),
1023        BigInt(BigInt),
1024        Float(f32),
1025        Double(f64),
1026        BigDecimal(BigDecimal),
1027    }
1028}
1029
1030// ============================================================================
1031// Conversions INTO Default Document
1032// ============================================================================
1033
1034impl From<default::Document> for Box<dyn Document> {
1035    #[inline]
1036    fn from(value: default::Document) -> Self {
1037        Box::new(value)
1038    }
1039}
1040
1041impl From<bool> for Box<dyn Document> {
1042    #[inline]
1043    fn from(value: bool) -> Self {
1044        default::Document {
1045            schema: BOOLEAN.clone(),
1046            value: Value::Boolean(value),
1047            discriminator: None,
1048        }
1049        .into()
1050    }
1051}
1052
1053impl From<i8> for Box<dyn Document> {
1054    #[inline]
1055    fn from(value: i8) -> Self {
1056        default::Document {
1057            schema: BYTE.clone(),
1058            value: Value::Number(Number::Byte(value)),
1059            discriminator: None,
1060        }
1061        .into()
1062    }
1063}
1064
1065impl From<i16> for Box<dyn Document> {
1066    #[inline]
1067    fn from(value: i16) -> Self {
1068        default::Document {
1069            schema: SHORT.clone(),
1070            value: Value::Number(Number::Short(value)),
1071            discriminator: None,
1072        }
1073        .into()
1074    }
1075}
1076
1077impl From<i32> for Box<dyn Document> {
1078    #[inline]
1079    fn from(value: i32) -> Self {
1080        default::Document {
1081            schema: INTEGER.clone(),
1082            value: Value::Number(Number::Integer(value)),
1083            discriminator: None,
1084        }
1085        .into()
1086    }
1087}
1088
1089impl From<i64> for Box<dyn Document> {
1090    #[inline]
1091    fn from(value: i64) -> Self {
1092        default::Document {
1093            schema: LONG.clone(),
1094            value: Value::Number(Number::Long(value)),
1095            discriminator: None,
1096        }
1097        .into()
1098    }
1099}
1100
1101impl From<f32> for Box<dyn Document> {
1102    #[inline]
1103    fn from(value: f32) -> Self {
1104        default::Document {
1105            schema: FLOAT.clone(),
1106            value: Value::Number(Number::Float(value)),
1107            discriminator: None,
1108        }
1109        .into()
1110    }
1111}
1112
1113impl From<f64> for Box<dyn Document> {
1114    #[inline]
1115    fn from(value: f64) -> Self {
1116        default::Document {
1117            schema: DOUBLE.clone(),
1118            value: Value::Number(Number::Double(value)),
1119            discriminator: None,
1120        }
1121        .into()
1122    }
1123}
1124
1125impl From<&str> for Box<dyn Document> {
1126    #[inline]
1127    fn from(value: &str) -> Self {
1128        default::Document {
1129            schema: STRING.clone(),
1130            value: Value::String(value.to_string()),
1131            discriminator: None,
1132        }
1133        .into()
1134    }
1135}
1136
1137impl From<BigInt> for Box<dyn Document> {
1138    #[inline]
1139    fn from(value: BigInt) -> Self {
1140        default::Document {
1141            schema: BIG_INTEGER.clone(),
1142            value: Value::Number(Number::BigInt(value)),
1143            discriminator: None,
1144        }
1145        .into()
1146    }
1147}
1148
1149impl From<BigDecimal> for Box<dyn Document> {
1150    #[inline]
1151    fn from(value: BigDecimal) -> Self {
1152        default::Document {
1153            schema: BIG_DECIMAL.clone(),
1154            value: Value::Number(Number::BigDecimal(value)),
1155            discriminator: None,
1156        }
1157        .into()
1158    }
1159}
1160
1161impl From<ByteBuffer> for Box<dyn Document> {
1162    #[inline]
1163    fn from(value: ByteBuffer) -> Self {
1164        default::Document {
1165            schema: BLOB.clone(),
1166            value: Value::Blob(value),
1167            discriminator: None,
1168        }
1169        .into()
1170    }
1171}
1172
1173impl From<String> for Box<dyn Document> {
1174    #[inline]
1175    fn from(value: String) -> Self {
1176        default::Document {
1177            schema: STRING.clone(),
1178            value: Value::String(value),
1179            discriminator: None,
1180        }
1181        .into()
1182    }
1183}
1184
1185impl From<Instant> for Box<dyn Document> {
1186    #[inline]
1187    fn from(value: Instant) -> Self {
1188        default::Document {
1189            schema: TIMESTAMP.clone(),
1190            value: Value::Timestamp(value),
1191            discriminator: None,
1192        }
1193        .into()
1194    }
1195}
1196impl From<&Instant> for Box<dyn Document> {
1197    #[inline]
1198    fn from(value: &Instant) -> Self {
1199        default::Document {
1200            schema: TIMESTAMP.clone(),
1201            value: Value::Timestamp(*value),
1202            discriminator: None,
1203        }
1204        .into()
1205    }
1206}
1207
1208smithy!("smithy.api#Document": {
1209    #[doc(hidden)]
1210    list LIST_DOCUMENT_SCHEMA {
1211        member: DOCUMENT
1212    }
1213});
1214
1215impl<T: Into<Box<dyn Document>>> From<Vec<T>> for Box<dyn Document> {
1216    fn from(value: Vec<T>) -> Self {
1217        let result = value.into_iter().map(Into::into).collect();
1218        default::Document {
1219            schema: LIST_DOCUMENT_SCHEMA.clone(),
1220            value: Value::List(result),
1221            discriminator: None,
1222        }
1223        .into()
1224    }
1225}
1226
1227smithy!("smithy.api#Document": {
1228    #[doc(hidden)]
1229    map MAP_DOCUMENT_SCHEMA {
1230        key: STRING
1231        value: DOCUMENT
1232    }
1233});
1234
1235impl<T: Into<Box<dyn Document>>> From<IndexMap<String, T>> for Box<dyn Document> {
1236    fn from(value: IndexMap<String, T>) -> Self {
1237        let mut result = IndexMap::new();
1238        for (key, value) in value {
1239            result.insert(key, value.into());
1240        }
1241        default::Document {
1242            schema: MAP_DOCUMENT_SCHEMA.clone(),
1243            value: Value::Map(result),
1244            discriminator: None,
1245        }
1246        .into()
1247    }
1248}
1249
1250macro_rules! option_conversion {
1251    ($ty:ty, $schema:ident) => {
1252        impl From<Option<$ty>> for Box<dyn Document> {
1253            fn from(value: Option<$ty>) -> Self {
1254                value.map_or_else(
1255                    || {
1256                        default::Document {
1257                            schema: $schema.clone(),
1258                            value: Value::Null,
1259                            discriminator: None,
1260                        }
1261                        .into()
1262                    },
1263                    Into::into,
1264                )
1265            }
1266        }
1267    };
1268}
1269option_conversion!(String, STRING);
1270option_conversion!(bool, BOOLEAN);
1271option_conversion!(Instant, TIMESTAMP);
1272option_conversion!(ByteBuffer, BLOB);
1273option_conversion!(i8, BYTE);
1274option_conversion!(i16, SHORT);
1275option_conversion!(i32, INTEGER);
1276option_conversion!(i64, LONG);
1277option_conversion!(f32, FLOAT);
1278option_conversion!(BigInt, BIG_INTEGER);
1279option_conversion!(BigDecimal, BIG_DECIMAL);
1280
1281// =========================================================================
1282// Null Document
1283// =========================================================================
1284#[doc(hidden)]
1285pub static NULL: LazyLock<Box<dyn Document>> = LazyLock::new(|| {
1286    default::Document {
1287        schema: DOCUMENT.clone(),
1288        value: Value::Null,
1289        discriminator: None,
1290    }
1291    .into()
1292});
1293
1294#[cfg(test)]
1295mod tests {
1296    use super::*;
1297    use crate::schema::SchemaRef;
1298
1299    #[test]
1300    fn string_document_value() {
1301        let document_str: Box<dyn Document> = "MyStr".into();
1302        let val: &SchemaRef = &STRING;
1303        assert_eq!(document_str.schema(), val);
1304        let output_str: String = document_str.as_string().unwrap().to_string();
1305        assert_eq!(output_str, "MyStr".to_string());
1306
1307        let document_string: Box<dyn Document> = "MyString".into();
1308        assert_eq!(document_string.schema(), val);
1309        let output_string: String = document_string.as_string().unwrap().to_string();
1310        assert_eq!(&output_string, &"MyString");
1311    }
1312
1313    #[test]
1314    fn list_document_value() {
1315        let vec = vec!["a", "b", "c"];
1316        let document_list: Box<dyn Document> = vec.into();
1317        let val: &SchemaRef = &LIST_DOCUMENT_SCHEMA;
1318        assert_eq!(document_list.schema(), val);
1319        assert_eq!(document_list.size(), 3);
1320        let vec_out: Vec<String> = document_list.try_into().unwrap();
1321        assert_eq!(vec_out.len(), 3);
1322        assert_eq!(vec_out[0], "a");
1323        assert_eq!(vec_out[1], "b");
1324        assert_eq!(vec_out[2], "c");
1325    }
1326
1327    #[test]
1328    fn map_document_value() {
1329        let mut map_in: IndexMap<String, String> = IndexMap::new();
1330        map_in.insert("a".to_string(), "b".to_string());
1331        let map_doc: Box<dyn Document> = map_in.into();
1332        let val: &SchemaRef = &MAP_DOCUMENT_SCHEMA;
1333        assert_eq!(map_doc.schema(), val);
1334        assert_eq!(map_doc.size(), 1);
1335
1336        let map_out: IndexMap<String, String> = map_doc.try_into().unwrap();
1337        assert_eq!(map_out.len(), 1);
1338        assert_eq!(map_out["a"], "b");
1339    }
1340
1341    #[test]
1342    fn integer_document_values() {
1343        let byte: Box<dyn Document> = 1i8.into();
1344        let byte_val: &SchemaRef = &BYTE;
1345        assert_eq!(byte.schema(), byte_val);
1346
1347        let short: Box<dyn Document> = 1i16.into();
1348        let short_val: &SchemaRef = &SHORT;
1349
1350        assert_eq!(short.schema(), short_val);
1351
1352        let integer: Box<dyn Document> = 1i32.into();
1353        let integer_val: &SchemaRef = &INTEGER;
1354
1355        assert_eq!(integer.schema(), integer_val);
1356
1357        let long: Box<dyn Document> = 1i64.into();
1358        let long_val: &SchemaRef = &LONG;
1359
1360        assert_eq!(long.schema(), long_val);
1361    }
1362
1363    // TODO(numeric comparisons): Add comparison checks
1364
1365    #[test]
1366    fn float_document_values() {
1367        let float: Box<dyn Document> = 1f32.into();
1368        let float_val: &SchemaRef = &FLOAT;
1369        assert_eq!(float.schema(), float_val);
1370
1371        let double: Box<dyn Document> = 1f64.into();
1372        let double_val: &SchemaRef = &DOUBLE;
1373        assert_eq!(double.schema(), double_val);
1374
1375        let float_value: f32 = float.try_into().unwrap();
1376        assert_eq!(float_value, 1f32);
1377        let double_value: f64 = double.try_into().unwrap();
1378        assert_eq!(double_value, 1f64);
1379    }
1380}