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