Skip to main content

endpoint_libs/model/
types.rs

1use alloc::boxed::Box;
2use alloc::collections::BTreeMap;
3use alloc::format;
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6use core::hash::{Hash, Hasher};
7use serde::*;
8
9/// Emitter-facing annotations attached to a [`Field`] or
10/// [`EndpointSchema`](crate::model::EndpointSchema).
11///
12/// Unused by endpoint-libs itself. It exists so that later releases can carry
13/// examples, JSON Schema constraints, tags, deprecation markers and
14/// protocol-binding hints into the OpenAPI/AsyncAPI emitters **without a breaking
15/// change to the schema model**. Unknown keys must round-trip untouched.
16///
17/// This is a newtype rather than a bare `BTreeMap` because `Field` derives `Hash`,
18/// `Ord` and `Eq`, which `serde_json::Value` does not implement. The manual impls
19/// below compare and hash values by their canonical JSON text.
20#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
21#[serde(transparent)]
22pub struct MetaMap(pub BTreeMap<String, serde_json::Value>);
23
24impl MetaMap {
25    pub fn is_empty(&self) -> bool {
26        self.0.is_empty()
27    }
28
29    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
30        self.0.get(key)
31    }
32
33    pub fn insert(&mut self, key: impl Into<String>, value: serde_json::Value) {
34        self.0.insert(key.into(), value);
35    }
36}
37
38/// Deterministic because `BTreeMap` iterates in key order and `Value`'s `Display`
39/// is a canonical JSON rendering.
40impl Hash for MetaMap {
41    fn hash<H: Hasher>(&self, state: &mut H) {
42        for (key, value) in &self.0 {
43            key.hash(state);
44            value.to_string().hash(state);
45        }
46    }
47}
48
49impl Ord for MetaMap {
50    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
51        self.0
52            .iter()
53            .map(|(k, v)| (k, v.to_string()))
54            .cmp(other.0.iter().map(|(k, v)| (k, v.to_string())))
55    }
56}
57
58impl PartialOrd for MetaMap {
59    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
60        Some(self.cmp(other))
61    }
62}
63
64/// `Field` is a struct that represents the parameters and returns in an endpoint schema.
65#[derive(Clone, Debug, Hash, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
66#[non_exhaustive]
67pub struct Field {
68    /// The name of the field (e.g. `user_id`)
69    pub name: String,
70
71    /// The description of the field
72    #[serde(skip)]
73    pub description: String,
74
75    /// The type of the field (e.g. `Type::BigInt`)
76    pub ty: Type,
77
78    /// Emitter annotations — see [`MetaMap`]. Empty in 2.0.
79    #[serde(default, skip_serializing_if = "MetaMap::is_empty")]
80    pub meta: MetaMap,
81}
82
83impl Field {
84    /// Creates a new `Field` with the given name and type.
85    /// `description` is set to `""`.
86    pub fn new(name: impl Into<String>, ty: Type) -> Self {
87        Self {
88            name: name.into(),
89            description: "".into(),
90            ty,
91            meta: MetaMap::default(),
92        }
93    }
94
95    /// Creates a new `Field` with the given name, type and description.
96    pub fn new_with_description(
97        name: impl Into<String>,
98        description: impl Into<String>,
99        ty: Type,
100    ) -> Self {
101        Self {
102            name: name.into(),
103            description: description.into(),
104            ty,
105            meta: MetaMap::default(),
106        }
107    }
108
109    /// Attach emitter annotations. See [`MetaMap`].
110    #[must_use]
111    pub fn with_meta(mut self, meta: MetaMap) -> Self {
112        self.meta = meta;
113        self
114    }
115}
116
117/// `EnumVariant` is a struct that represents the variants of an enum.
118#[derive(Clone, Debug, Hash, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq)]
119#[non_exhaustive]
120pub struct EnumVariant {
121    /// The name of the variant (e.g. `UniSwap`)
122    pub name: String,
123
124    /// A description added by `new_with_description` method
125    pub description: String,
126
127    /// The value of the variant (e.g. 1)
128    pub value: i64,
129}
130
131impl EnumVariant {
132    /// Creates a new `EnumVariant` with the given name and value.
133    /// `description` is set to `""`.
134    pub fn new(name: impl Into<String>, value: i64) -> Self {
135        Self {
136            name: name.into(),
137            description: "".into(),
138            value,
139        }
140    }
141
142    /// Creates a new `EnumVariant` with the given name, value and description.
143    pub fn new_with_description(
144        name: impl Into<String>,
145        description: impl Into<String>,
146        value: i64,
147    ) -> Self {
148        Self {
149            name: name.into(),
150            description: description.into(),
151            value,
152        }
153    }
154}
155
156/// `Type` is an enum that represents the types of the fields in an endpoint schema.
157#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord)]
158#[non_exhaustive]
159pub enum Type {
160    UInt32,
161    Int32,
162    Int64,
163    Float64,
164    Boolean,
165    String,
166    Bytea,
167    UUID,
168    NanoId {
169        len: usize,
170    },
171    IpAddr,
172    Struct {
173        name: String,
174        fields: Vec<Field>,
175    },
176    StructRef(String),
177    Object,
178    // DataTable {
179    //     name: String,
180    //     fields: Vec<Field>,
181    // },
182    StructTable {
183        struct_ref: String,
184    },
185    Vec(Box<Type>),
186    Unit,
187    Optional(Box<Type>),
188    Enum {
189        name: String,
190        variants: Vec<EnumVariant>,
191    },
192    EnumRef {
193        name: String,
194        #[serde(default, skip_serializing)]
195        prefixed_name: bool,
196    },
197    TimeStampMs,
198    BlockchainDecimal,
199    BlockchainAddress,
200    BlockchainTransactionHash,
201}
202
203impl Type {
204    /// Creates a new `Type::Struct` with the given name and fields.
205    pub fn struct_(name: impl Into<String>, fields: Vec<Field>) -> Self {
206        Self::Struct {
207            name: name.into(),
208            fields,
209        }
210    }
211
212    /// Creates a new `Type::StructRef` with the given name.
213    pub fn struct_ref(name: impl Into<String>) -> Self {
214        Self::StructRef(name.into())
215    }
216
217    // /// Creates a new `Type::DataTable` with the given name and fields.
218    // pub fn datatable(name: impl Into<String>, fields: Vec<Field>) -> Self {
219    //     Self::DataTable {
220    //         name: name.into(),
221    //         fields,
222    //     }
223    // }
224
225    /// Creates a new `Type::StructTable` with the given struct reference.
226    pub fn struct_table(struct_ref: impl Into<String>) -> Self {
227        Self::StructTable {
228            struct_ref: struct_ref.into(),
229        }
230    }
231
232    /// Creates a new `Type::Vec` with the given type.
233    pub fn vec(ty: Type) -> Self {
234        Self::Vec(Box::new(ty))
235    }
236
237    /// Creates a new `Type::Optional` with the given type.
238    pub fn optional(ty: Type) -> Self {
239        Self::Optional(Box::new(ty))
240    }
241
242    /// Creates a new `Type::EnumRef` with the given name.
243    pub fn enum_ref(name: impl Into<String>, prefixed_name: bool) -> Self {
244        Self::EnumRef {
245            name: name.into(),
246            prefixed_name,
247        }
248    }
249
250    /// Creates a new `Type::Enum` with the given name and fields/variants.
251    pub fn enum_(name: impl Into<String>, fields: Vec<EnumVariant>) -> Self {
252        Self::Enum {
253            name: name.into(),
254            variants: fields,
255        }
256    }
257    pub fn try_unwrap(self) -> Option<Self> {
258        match self {
259            Self::Vec(v) => Some(*v),
260            // Self::DataTable { .. } => None,
261            Self::StructTable { .. } => None,
262            _ => Some(self),
263        }
264    }
265
266    pub fn add_default_enum_derives(input: String) -> String {
267        format!(
268            r#"#[derive(Debug, Clone, Copy, Serialize, Deserialize, FromPrimitive, PartialEq, Eq, PartialOrd, Ord, EnumString, Display, Hash)]{input}"#
269        )
270    }
271
272    pub fn add_default_struct_derives(input: String) -> String {
273        format!(
274            r#" #[derive(Serialize, Deserialize, Debug, Clone)]
275                #[serde(rename_all = "camelCase")]
276                {input}
277            "#
278        )
279    }
280}