endpoint-gen 1.4.0

Generate Rust code for websocket API endpoints
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
use crate::rust::ToRust;
use convert_case::{Case, Casing};
use endpoint_gen_macros::DefinitionVariant;
use endpoint_libs::model::{EndpointSchema, Type};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use smart_serde_default::smart_serde_default;

/// Marker trait for types that can be used as Definition variants
/// All types used in Definition must implement this to ensure they are properly validatable
// pub trait DefinitionVariant: GenElement<Self> {}

#[derive(Serialize, Deserialize)]
pub enum Definition {
    EndpointSchema(EndpointSchemaDefinition),
    EndpointSchemaList(EndpointSchemaListDefinition),
    Enum(EnumElement),
    EnumList(Vec<EnumElement>),
    Struct(StructElement),
    StructList(StructListDefinition),
}

impl Definition {
    pub fn validate_self(&self) -> eyre::Result<()> {
        match self {
            Definition::Enum(e) => e.validate_element(),
            Definition::EnumList(list) => {
                for item in list {
                    item.validate_element()?;
                }
                Ok(())
            }
            Definition::Struct(s) => s.validate_element(),
            Definition::StructList(list) => list.validate_element(),
            Definition::EndpointSchema(schema) => schema.validate_element(),
            Definition::EndpointSchemaList(schemas) => schemas.validate_element(),
        }
    }
}

pub trait GenElement<T: ?Sized>
where
    T: GenElement<T>,
{
    fn validate_element(&self) -> eyre::Result<()>;
}

/// Wraps the [Type::Enum] variant with extra config
#[derive(
    Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord, DefinitionVariant,
)]
pub struct EnumElement {
    #[serde(default)]
    pub config: RustGenConfig,
    pub inner: Type,
}

impl GenElement<EnumElement> for EnumElement {
    fn validate_element(&self) -> eyre::Result<()> {
        match &self.inner {
            Type::Enum { .. } => Ok(()),
            _ => eyre::bail!("Expected enum type"),
        }
    }
}

impl ToRust for EnumElement {
    fn to_rust_ref(&self, _serde_with: bool) -> String {
        self.validate_element()
            .unwrap_or_else(|_| panic!("EnumElement is invalid: {self:?}"));

        let name = match &self.inner {
            Type::Enum { name, .. } => name.to_case(Case::Pascal),
            _ => unreachable!("The previous validation ensured that this type is a valid Enum"),
        };

        if self.config.prefix_enum {
            format!("Enum{name}")
        } else {
            name
        }
    }

    fn to_rust_decl(&self, serde_with: bool, add_derives: bool) -> String {
        self.validate_element()
            .unwrap_or_else(|_| panic!("EnumElement is invalid: {self:?}"));

        let code_regex =
            regex::Regex::new(r"=\s*(\d+)").expect("Error building regex to extract endpoint code");

        match &self.inner {
            Type::Enum {
                name: _,
                variants: fields,
            } => {
                let mut fields = fields
                    .iter()
                    .map(|x| {
                        format!(
                            r#"
    /// {}
    {} = {}
"#,
                            x.description,
                            if x.name.chars().last().unwrap().is_lowercase() {
                                x.name.to_case(Case::Pascal)
                            } else {
                                x.name.clone()
                            },
                            x.value
                        )
                    })
                    .sorted_by(|a, b| {
                        // Sort by the endpoint code
                        let code_a = {
                            match code_regex.captures(a) {
                                Some(code) => code[1].parse::<u64>().unwrap_or_else(|err| {
                                    eprintln!(
                                        "Sorting error: {err}: Rust output may not be sorted correctly"
                                    );
                                    0
                                }),
                                None => {
                                    eprintln!(
                                        "Sorting error: Rust output may not be sorted correctly"
                                    );
                                    0
                                }
                            }
                        };

                        let code_b = {
                            match code_regex.captures(b) {
                                Some(code) => {
                                    code[1].parse::<u64>().unwrap_or_else(|err| {
                                        eprintln!(
                                        "Sorting error: {err}: Rust output may not be sorted correctly"
                                    );
                                        0
                                    })
                                }
                                None => {
                                    eprintln!(
                                        "Sorting error: Rust output may not be sorted correctly"
                                    );
                                    0
                                }
                            }
                        };

                        code_a.cmp(&code_b)
                    });
                let enum_content = format!(
                    r#"pub enum {} {{{}}}"#,
                    self.to_rust_ref(serde_with),
                    fields.join(",")
                );

                if add_derives {
                    self.add_derives(enum_content)
                } else {
                    enum_content
                }
            }
            _ => unreachable!(),
        }
    }

    fn add_derives(&self, input: String) -> String {
        if self.config.worktable_support {
            format!(
                r#"#[derive(
                    MemStat,
                    Archive,
                    Clone,
                    Copy,
                    Debug,
                    Display,
                    PartialEq,
                    PartialOrd,
                    Eq,
                    Hash,
                    Ord,
                    EnumString,
                    rkyv::Deserialize,
                    rkyv::Serialize,
                    serde::Serialize,
                    serde::Deserialize,
                    {}
                )]
                #[rkyv(compare(PartialEq), derive(Debug))]
                #[repr(u8)]
                {input}
            "#,
                self.config
                    .json_schema_gen
                    .then(|| "JsonSchema,")
                    .unwrap_or_default()
            )
        } else {
            Type::add_default_enum_derives(input)
        }
    }
}
#[derive(
    Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord, DefinitionVariant,
)]
pub struct StructListDefinition {
    #[serde(default)]
    pub config: RustGenConfig,
    pub struct_elements: Vec<StructElement>,
}

impl GenElement<StructListDefinition> for StructListDefinition {
    fn validate_element(&self) -> eyre::Result<()> {
        if self
            .struct_elements
            .iter()
            .all(|s| matches!(s.inner, Type::Struct { .. }))
        {
            Ok(())
        } else {
            eyre::bail!("Not all elements of the StructListDefinition are Struct types")
        }
    }
}

/// Wraps the [Type::Struct] variant with extra config
#[derive(
    Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord, DefinitionVariant,
)]
pub struct StructElement {
    #[serde(default)]
    pub config: RustGenConfig,
    pub inner: Type,
}

impl GenElement<StructElement> for StructElement {
    fn validate_element(&self) -> eyre::Result<()> {
        match &self.inner {
            Type::Struct { .. } => Ok(()),
            _ => eyre::bail!("Expected struct type"),
        }
    }
}

impl ToRust for StructElement {
    fn to_rust_ref(&self, _serde_with: bool) -> String {
        self.validate_element()
            .unwrap_or_else(|_| panic!("StructElement is invalid: {self:?}"));

        match &self.inner {
            Type::Struct { name, .. } => name.clone(),
            _ => unreachable!("The previous validation ensured that this type is a valid Struct"),
        }
    }

    fn to_rust_decl(&self, serde_with: bool, add_derives: bool) -> String {
        self.validate_element()
            .unwrap_or_else(|_| panic!("StructElement is invalid: {self:?}"));

        let (name, fields) = match &self.inner {
            Type::Struct { name, fields } => (name.to_case(Case::Pascal), fields),
            _ => unreachable!("The previous validation ensured that this type is a valid Struct"),
        };

        let mut fields = fields.iter().map(|x| {
            let opt = matches!(&x.ty, Type::Optional(_));
            let serde_with_opt = match &x.ty {
                Type::BlockchainDecimal => "rust_decimal::serde::str",
                Type::BlockchainAddress if serde_with => "WithBlockchainAddress",
                Type::BlockchainTransactionHash if serde_with => "WithBlockchainTransactionHash",
                // TODO: handle optional decimals
                // Type::Optional(t) if matches!(**t, Type::BlockchainDecimal) => {
                //     "WithBlockchainDecimal"
                // }
                // Type::Optional(t) if matches!(**t, Type::BlockchainAddress) => {
                //     "WithBlockchainAddress"
                // }
                // Type::Optional(t) if matches!(**t, Type::BlockchainTransactionHash) => {
                //     "WithBlockchainTransactionHash"
                // }
                _ => "",
            };
            format!(
                "{} {} pub {}: {}",
                if opt { "#[serde(default)]" } else { "" },
                if serde_with_opt.is_empty() {
                    "".to_string()
                } else {
                    format!("#[serde(with = \"{serde_with_opt}\")]")
                },
                x.name,
                x.ty.to_rust_ref(serde_with)
            )
        });
        let input = format!("pub struct {} {{{}}}", name, fields.join(","));

        if add_derives {
            self.add_derives(input)
        } else {
            input
        }
    }

    fn add_derives(&self, input: String) -> String {
        if self.config.worktable_support {
            // format!(
            //     r#"#[derive(
            //             Clone,
            //             Copy,
            //             Debug,
            //             Default,
            //             Eq,
            //             Hash,
            //             Ord,
            //             PartialEq,
            //             PartialOrd,
            //             derive_more::Display,
            //             derive_more::From,
            //             derive_more::FromStr,
            //             derive_more::Into,
            //             MemStat,
            //             rkyv::Archive,
            //             SizeMeasure,
            //             rkyv::Deserialize,
            //             rkyv::Serialize,
            //             serde::Serialize,
            //             serde::Deserialize,
            //             derive_more::Display,
            //         )]
            //         #[rkyv(compare(PartialEq), derive(Debug, PartialOrd, PartialEq, Eq, Ord))]
            //         {input}
            //     "#

            // TODO: Fix worktable support for structs
            format!(
                r#" #[derive(Serialize, Deserialize, Debug, Clone, {})]
                #[serde(rename_all = "camelCase")]
                {input}
            "#,
                self.config
                    .json_schema_gen
                    .then(|| "JsonSchema,")
                    .unwrap_or_default()
            )
        } else {
            Type::add_default_struct_derives(input)
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Hash, PartialEq, PartialOrd, Eq, Ord, Default)]
pub struct RustGenConfig {
    #[serde(default)]
    pub prefix_enum: bool,
    #[serde(default)]
    pub worktable_support: bool,
    #[serde(default)]
    pub json_schema_gen: bool,
    #[serde(default)]
    pub snake_case_fields: bool,
    #[serde(default)]
    pub override_parent: bool,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct GenService {
    pub name: String,
    pub id: u16,
    pub endpoints: Vec<EndpointSchemaElement>,
}

impl GenService {
    pub fn new(name: String, id: u16, endpoints: Vec<EndpointSchemaElement>) -> Self {
        Self {
            name,
            id,
            endpoints,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct EndpointSchemaDefinition {
    pub service_name: String,
    pub service_id: u16,
    pub schema: EndpointSchemaElement,
}

#[smart_serde_default]
#[derive(Serialize, Deserialize, SmartDefault, Clone)]
pub struct EndpointSchemaElement {
    #[smart_default(true)]
    pub frontend_facing: bool,
    #[serde(default)]
    pub config: RustGenConfig,
    pub schema: EndpointSchema,
}

impl From<EndpointSchemaElement> for EndpointSchema {
    fn from(val: EndpointSchemaElement) -> Self {
        EndpointSchema {
            name: val.schema.name,
            code: val.schema.code,
            parameters: val.schema.parameters,
            returns: val.schema.returns,
            stream_response: val.schema.stream_response,
            description: val.schema.description,
            json_schema: val.schema.json_schema,
            roles: val.schema.roles,
        }
    }
}

impl FromIterator<EndpointSchemaElement> for Vec<EndpointSchema> {
    fn from_iter<T: IntoIterator<Item = EndpointSchemaElement>>(iter: T) -> Self {
        iter.into_iter().map(|element| element.schema).collect()
    }
}

impl GenElement<EndpointSchemaDefinition> for EndpointSchemaDefinition {
    fn validate_element(&self) -> eyre::Result<()> {
        Ok(())
    }
}

#[derive(Serialize, Deserialize, DefinitionVariant)]
pub struct EndpointSchemaListDefinition {
    pub service_name: String,
    pub service_id: u16,
    #[serde(default)]
    pub config: RustGenConfig,
    pub endpoints: Vec<EndpointSchemaElement>,
}

impl GenElement<EndpointSchemaListDefinition> for EndpointSchemaListDefinition {
    fn validate_element(&self) -> eyre::Result<()> {
        Ok(())
    }
}