Skip to main content

endpoint_libs/model/
endpoint.rs

1use alloc::format;
2use alloc::string::{String, ToString};
3use alloc::vec::Vec;
4use core::fmt::Write;
5
6use crate::eyre::{ContextCompat, Result};
7use crate::model::{Field, MetaMap, Type};
8use crate::urlencoding;
9use crate::convert_case::{Case, Casing};
10use serde::de::{Error, Unexpected};
11use serde::ser::SerializeStruct;
12use serde::*;
13
14/// `EndpointSchema` is a struct that represents a single endpoint in the API.
15#[derive(Debug, Serialize, Deserialize, Default, Clone)]
16#[non_exhaustive]
17pub struct EndpointSchema {
18    /// The name of the endpoint (e.g. `UserListSymbols`)
19    pub name: String,
20
21    /// The method code of the endpoint (e.g. `10020`)
22    pub code: u32,
23
24    /// A list of parameters that the endpoint accepts (e.g. "symbol" of type `String`)
25    pub parameters: Vec<Field>,
26
27    /// A list of fields that the endpoint returns
28    pub returns: Vec<Field>,
29
30    /// The type of the stream response (if any)
31    #[serde(default)]
32    pub stream_response: Option<Type>,
33
34    /// A description of the endpoint added by `with_description` method
35    #[serde(default)]
36    pub description: String,
37
38    /// The JSON schema of the endpoint (`Default::default()`)
39    #[serde(default)]
40    pub json_schema: serde_json::Value,
41
42    // Allowed roles for this endpoint ["EnumRole::EnumVariant"]
43    pub roles: Vec<String>,
44
45    /// Public error variants that handlers may return for this endpoint.
46    #[serde(default)]
47    pub errors: Vec<EndpointErrorSchema>,
48
49    /// Emitter annotations — see [`MetaMap`](crate::model::MetaMap). Empty in 2.0;
50    /// consumed by the OpenAPI/AsyncAPI emitters in 2.1.
51    #[serde(default, skip_serializing_if = "MetaMap::is_empty")]
52    pub meta: MetaMap,
53}
54
55impl EndpointSchema {
56    /// Creates a new `EndpointSchema` with the given name, method code, parameters and returns.
57    pub fn new(
58        name: impl Into<String>,
59        code: u32,
60        parameters: Vec<Field>,
61        returns: Vec<Field>,
62    ) -> Self {
63        Self {
64            name: name.into(),
65            code,
66            parameters,
67            returns,
68            stream_response: None,
69            description: "".to_string(),
70            json_schema: Default::default(),
71            roles: Vec::new(),
72            errors: Vec::new(),
73            meta: MetaMap::default(),
74        }
75    }
76
77    /// Attach emitter annotations. See [`MetaMap`](crate::model::MetaMap).
78    #[must_use]
79    pub fn with_meta(mut self, meta: MetaMap) -> Self {
80        self.meta = meta;
81        self
82    }
83
84    /// Adds a stream response type field to the endpoint.
85    pub fn with_stream_response_type(mut self, stream_response: Type) -> Self {
86        self.stream_response = Some(stream_response);
87        self
88    }
89
90    /// Adds a description field to the endpoint.
91    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
92        self.description = desc.into();
93        self
94    }
95
96    /// Adds allowed roles to the endpoint.
97    pub fn with_roles(mut self, roles: Vec<String>) -> Self {
98        self.roles = roles;
99        self
100    }
101
102    /// Adds public error variants to the endpoint.
103    pub fn with_errors(mut self, errors: Vec<EndpointErrorSchema>) -> Self {
104        self.errors = errors;
105        self
106    }
107}
108
109#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord)]
110#[non_exhaustive]
111pub struct EndpointErrorSchema {
112    pub name: String,
113    pub code: EndpointErrorCodeRef,
114    #[serde(default)]
115    pub message: String,
116    #[serde(default)]
117    pub fields: Vec<Field>,
118}
119
120impl EndpointErrorSchema {
121    /// Creates an error schema with no message and no fields.
122    ///
123    /// This type is `#[non_exhaustive]`, so out-of-crate callers must build it here
124    /// rather than with a struct literal.
125    pub fn new(name: impl Into<String>, code: EndpointErrorCodeRef) -> Self {
126        Self {
127            name: name.into(),
128            code,
129            message: String::new(),
130            fields: Vec::new(),
131        }
132    }
133
134    /// Sets the human-readable message.
135    #[must_use]
136    pub fn with_message(mut self, message: impl Into<String>) -> Self {
137        self.message = message.into();
138        self
139    }
140
141    /// Sets the structured fields carried by this error.
142    #[must_use]
143    pub fn with_fields(mut self, fields: Vec<Field>) -> Self {
144        self.fields = fields;
145        self
146    }
147}
148
149#[derive(Clone, Debug, Hash, PartialEq, PartialOrd, Eq, Ord)]
150pub struct EndpointErrorCodeRef {
151    pub ty: Type,
152    pub variant: String,
153}
154
155impl EndpointErrorCodeRef {
156    pub const ENUM_NAME: &'static str = "ErrorCode";
157
158    pub fn new(variant: impl Into<String>) -> Self {
159        Self {
160            ty: Type::enum_ref(Self::ENUM_NAME, true),
161            variant: variant.into(),
162        }
163    }
164
165    pub fn variant(&self) -> &str {
166        &self.variant
167    }
168
169    pub fn path(&self) -> String {
170        format!("{}::{}", Self::ENUM_NAME, self.variant)
171    }
172
173    fn validate_ty(ty: Type) -> core::result::Result<Type, String> {
174        match &ty {
175            Type::EnumRef { name, .. } if name == Self::ENUM_NAME => Ok(ty),
176            Type::EnumRef { name, .. } => {
177                Err(format!("expected {} enum ref, got {name}", Self::ENUM_NAME))
178            }
179            _ => Err(format!("expected {} enum ref", Self::ENUM_NAME)),
180        }
181    }
182
183    fn parse_path(path: &str) -> core::result::Result<Self, String> {
184        let (enum_name, variant) = path
185            .split_once("::")
186            .ok_or_else(|| format!("expected {}::Variant", Self::ENUM_NAME))?;
187
188        if enum_name != Self::ENUM_NAME {
189            return Err(format!(
190                "expected {} enum path, got {enum_name}",
191                Self::ENUM_NAME
192            ));
193        }
194
195        if variant.is_empty() || variant.contains("::") {
196            return Err(format!("expected {}::Variant", Self::ENUM_NAME));
197        }
198
199        Ok(Self::new(variant))
200    }
201}
202
203impl core::fmt::Display for EndpointErrorCodeRef {
204    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
205        f.write_str(&self.path())
206    }
207}
208
209impl Serialize for EndpointErrorCodeRef {
210    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
211    where
212        S: Serializer,
213    {
214        let mut state = serializer.serialize_struct("EndpointErrorCodeRef", 2)?;
215        state.serialize_field("ty", &self.ty)?;
216        state.serialize_field("variant", &self.variant)?;
217        state.end()
218    }
219}
220
221impl<'de> Deserialize<'de> for EndpointErrorCodeRef {
222    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
223    where
224        D: Deserializer<'de>,
225    {
226        #[derive(Deserialize)]
227        #[serde(untagged)]
228        enum Helper {
229            Path(String),
230            Structured { ty: Type, variant: String },
231        }
232
233        match Helper::deserialize(deserializer)? {
234            Helper::Path(path) => Self::parse_path(&path)
235                .map_err(|err| D::Error::invalid_value(Unexpected::Str(&path), &err.as_str())),
236            Helper::Structured { ty, variant } => {
237                let ty = Self::validate_ty(ty).map_err(D::Error::custom)?;
238                Ok(Self { ty, variant })
239            }
240        }
241    }
242}
243
244pub fn encode_header<T: Serialize>(v: T, schema: EndpointSchema) -> Result<String> {
245    let mut s = String::new();
246    write!(s, "0{}", schema.name.to_ascii_lowercase())?;
247    let v = serde_json::to_value(&v)?;
248
249    for (i, f) in schema.parameters.iter().enumerate() {
250        let key = f.name.to_case(Case::Camel);
251        let value = v.get(&key).with_context(|| format!("key: {key}"))?;
252        if value.is_null() {
253            continue;
254        }
255        write!(
256            s,
257            ", {}{}",
258            i + 1,
259            urlencoding::encode(&value.to_string().replace('\"', ""))
260        )?;
261    }
262    Ok(s)
263}
264
265#[cfg(test)]
266mod forward_compat_tests {
267    use super::*;
268    use crate::model::MetaMap;
269
270    /// The contract 2.1 depends on: generated code deserializes committed schema JSON
271    /// (`serde_json::from_str`, see endpointgen's rust.rs emitter), so a *newer*
272    /// endpointgen emitting fields this version does not know about must not break an
273    /// older endpoint-libs. If this test ever fails, adding anything to the schema
274    /// model has become a breaking change and OpenAPI support becomes a 3.0.
275    #[test]
276    fn unknown_future_fields_are_ignored() {
277        let json = r#"{
278            "name": "UserListSymbols",
279            "code": 10020,
280            "parameters": [],
281            "returns": [],
282            "roles": ["Admin"],
283            "x_future_openapi_binding": {"path": "/rpc/UserListSymbols"},
284            "some_field_from_2_5": 42
285        }"#;
286        let schema: EndpointSchema =
287            serde_json::from_str(json).expect("unknown fields must not break deserialization");
288        assert_eq!(schema.name, "UserListSymbols");
289        assert_eq!(schema.code, 10020);
290        assert!(schema.meta.is_empty());
291    }
292
293    /// Old committed schema JSON (no `meta` key at all) must still load.
294    #[test]
295    fn absent_meta_defaults_empty() {
296        let json = r#"{"name":"A","code":1,"parameters":[],"returns":[],"roles":[]}"#;
297        let schema: EndpointSchema = serde_json::from_str(json).unwrap();
298        assert!(schema.meta.is_empty());
299    }
300
301    /// `meta` must survive a serialize → deserialize cycle byte-for-byte, including
302    /// keys this version assigns no meaning to. The 2.1 emitters read these.
303    #[test]
304    fn meta_round_trips_including_unknown_keys() {
305        let mut meta = MetaMap::default();
306        meta.insert("example", serde_json::json!({"symbol": "BTC"}));
307        meta.insert("x-openapi-tags", serde_json::json!(["trading"]));
308        meta.insert("deprecated", serde_json::json!(true));
309
310        let schema = EndpointSchema::new("A", 1, vec![], vec![]).with_meta(meta.clone());
311        let text = serde_json::to_string(&schema).unwrap();
312        let back: EndpointSchema = serde_json::from_str(&text).unwrap();
313
314        assert_eq!(back.meta, meta);
315        assert_eq!(
316            back.meta.get("x-openapi-tags"),
317            Some(&serde_json::json!(["trading"]))
318        );
319    }
320
321    /// Empty `meta` must not appear in the output at all, so 2.0 artifacts stay
322    /// byte-identical to 1.9 ones and `endpointgen --check` sees no spurious drift.
323    #[test]
324    fn empty_meta_is_not_serialized() {
325        let schema = EndpointSchema::new("A", 1, vec![], vec![]);
326        let text = serde_json::to_string(&schema).unwrap();
327        assert!(
328            !text.contains("meta"),
329            "empty meta leaked into output: {text}"
330        );
331
332        let field = Field::new("x", Type::String);
333        let text = serde_json::to_string(&field).unwrap();
334        assert!(!text.contains("meta"), "empty field meta leaked: {text}");
335    }
336
337    /// Field-level meta is what carries per-parameter OpenAPI enrichment.
338    #[test]
339    fn field_meta_round_trips_and_preserves_derives() {
340        let mut meta = MetaMap::default();
341        meta.insert("minimum", serde_json::json!(0));
342        let field = Field::new("amount", Type::Int64).with_meta(meta);
343
344        let back: Field = serde_json::from_str(&serde_json::to_string(&field).unwrap()).unwrap();
345        assert_eq!(back.meta.get("minimum"), Some(&serde_json::json!(0)));
346
347        // Field derives Hash/Ord/Eq; MetaMap's manual impls must keep that working.
348        let mut set = std::collections::BTreeSet::new();
349        set.insert(field.clone());
350        assert!(set.contains(&field));
351        assert_ne!(field, Field::new("amount", Type::Int64));
352    }
353}