ronami-core 1.5.0

Core part of the `ronami` library — Telegram Bot API client
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use crate::codegen::{patch::escape_kw, schema, schema_check::api_schema::*};
use derive_more::derive::Display;

#[derive(Debug, Display)]
enum ApiCheckError {
    #[display("Method `{method}` does not exist")]
    MethodDoesNotExist { method: String },
    #[display("Method `{method}` does not have `{param}` parameter")]
    ParamDoesNotExist { method: String, param: String },
    #[display(
        "Method `{method}` and sibling `{sibling}` have something different in `{param}` param."
    )]
    SiblingParamsDontMatch { method: String, sibling: String, param: String },
    #[display(
        "Method `{method}` has a sibling `{fake_sibling}`, but `{fake_sibling}` doesn't have \
         `{method}` as a sibling."
    )]
    SiblingsDontMatch { method: String, fake_sibling: String },
    #[display("Method `{method}` has required `{param}` parameter, when it is not required")]
    ParamIsNotRequired { method: String, param: String },
    #[display("Method `{method}` has optional `{param}` parameter, when it is not optional")]
    ParamIsNotOptional { method: String, param: String },
    #[display(
        "`{param}` parameter of method `{method}` has a number type that can't fit all the \
         possible values. The limit is `{param_limit}`, but values go up to `{actual_limit}`"
    )]
    ParamIsTooRestrictive { method: String, param: String, param_limit: i64, actual_limit: i64 }, /* Limit can't be higher than i64 ever */
    #[display(
        "`{param}` parameter of method `{method}` is of type `{raw_type}`, but the actual type is \
         `{actual_type}`"
    )]
    ParamRawTyDoesNotMatch { method: String, param: String, raw_type: String, actual_type: String },
    #[display(
        "`{param}` parameter of method `{method}` is of type [{raw_type:?}], but the actual type \
         is [{actual_type:?}]"
    )]
    ParamTyDoesNotMatch { method: String, param: String, raw_type: schema::Type, actual_type: Kind },
    #[display(
        "Method `{method}` has a link to TBA {doc_link}, but the actual link is {actual_doc_link}"
    )]
    MethodDocLinkDoesNotMatch { method: String, doc_link: String, actual_doc_link: String },
    #[display(
        "Method `{method}` has two params `{param1}` and `{param2}` that are usually split up \
         into siblings"
    )]
    ParamsShouldBeSiblings { method: String, param1: String, param2: String },
}

#[derive(Debug, Clone, PartialEq)]
enum Exception {
    MethodField { method: String, param: String },
    FieldType { ron_raw_type: String, actual_type: String },
    SiblingParam { param: String },
}

#[derive(Debug, Clone, PartialEq)]
struct Exceptions {
    exceptions: Vec<Exception>,
}

impl Exceptions {
    fn new(exceptions: Vec<Exception>) -> Self {
        Self { exceptions }
    }

    fn extend(&mut self, exceptions: Vec<Exception>) {
        self.exceptions.extend(exceptions);
    }

    fn is_method_field_exception(&self, method: String, param: String) -> bool {
        self.exceptions.contains(&Exception::MethodField { method, param })
    }

    fn is_field_type_exception(&self, ron_raw_type: String, actual_type: String) -> bool {
        self.exceptions.contains(&Exception::FieldType { ron_raw_type, actual_type })
    }

    fn is_sibling_param_exception(&self, param: String) -> bool {
        self.exceptions.contains(&Exception::SiblingParam { param })
    }
}

#[derive(Debug, Clone, PartialEq)]
struct UsuallySiblings {
    params: Vec<(String, String)>,
}

impl UsuallySiblings {
    fn new(params: Vec<(String, String)>) -> Self {
        Self { params }
    }
}

fn find_ron_method_by_name(name: &str, schema: &schema::Schema) -> Option<schema::Method> {
    schema.methods.iter().find(|x| x.names.0 == name).cloned()
}

fn find_ron_param_by_name(name: &str, method: &schema::Method) -> Option<schema::Param> {
    method.params.iter().find(|x| x.name == name).cloned()
}

// This function checks both sibling methods and insures that the sibling status
// is correct
fn check_ron_siblings(
    ron_method: &schema::Method,
    ron_sibling_method: &schema::Method,
    method: &ApiMethod,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    check_ron_method_meta(ron_method, method, errors, exceptions);
    check_ron_method_meta(ron_sibling_method, method, errors, exceptions);

    for param in &method.arguments {
        let mut param_name = param.name.clone();
        escape_kw(&mut param_name); // Converts type to type_. Will think field is missing
        // otherwise.

        // Try to find both parameters
        let maybe_ron_param = find_ron_param_by_name(&param_name, ron_method);
        let maybe_ron_sibling_param = find_ron_param_by_name(&param_name, ron_sibling_method);

        match (maybe_ron_param.clone(), maybe_ron_sibling_param.clone()) {
            (Some(ron_param), Some(ron_sibling_param)) => check_ron_siblings_field(
                ron_method,
                ron_sibling_method,
                &ron_param,
                &ron_sibling_param,
                param,
                errors,
                exceptions,
            ),
            (Some(ron_param), None) => check_ron_siblings_only_one_field(
                &ron_param,
                ron_method.names.0.clone(),
                ron_sibling_method.names.0.clone(),
                param,
                errors,
                exceptions,
            ),
            (None, Some(ron_sibling_param)) => check_ron_siblings_only_one_field(
                &ron_sibling_param,
                ron_sibling_method.names.0.clone(),
                ron_method.names.0.clone(),
                param,
                errors,
                exceptions,
            ),
            (None, None) => {
                if !exceptions.is_method_field_exception(method.name.clone(), param_name) {
                    errors.push(ApiCheckError::ParamDoesNotExist {
                        method: method.name.clone(),
                        param: param.name.clone(),
                    });
                }
            }
        }
    }
}

fn check_ron_siblings_field(
    ron_method: &schema::Method,
    ron_sibling_method: &schema::Method,
    ron_param: &schema::Param,
    ron_sibling_param: &schema::Param,
    param: &Argument,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    // Sibling parameters must match exactly, down to the docs
    if ron_param != ron_sibling_param {
        errors.push(ApiCheckError::SiblingParamsDontMatch {
            method: ron_method.names.0.clone(),
            sibling: ron_sibling_method.names.0.clone(),
            param: param.name.clone(),
        });
    } else {
        check_param(ron_param, param, ron_method.names.0.clone(), false, errors, exceptions);
    }
}

// This function will add an error if the field is not an exception. Will check
// normally otherwise.
fn check_ron_siblings_only_one_field(
    ron_param: &schema::Param,
    ron_method_name: String,
    ron_method_without_param_name: String,
    param: &Argument,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    let mut param_name = param.name.clone();
    escape_kw(&mut param_name);

    // Some fields are common to have siblings. For example, message_id and
    // inline_message_id.
    if (!exceptions.is_sibling_param_exception(param_name.clone()))
        && (!exceptions
            .is_method_field_exception(ron_method_without_param_name.clone(), param_name))
    {
        errors.push(ApiCheckError::ParamDoesNotExist {
            method: ron_method_without_param_name,
            param: param.name.clone(),
        });
    } else {
        // It is in some exceptions. We don't care about optional fields, since its an
        // exception.
        check_param(ron_param, param, ron_method_name, true, errors, exceptions);
    }
}

fn check_ron_params(
    ron_method: &schema::Method,
    method: &ApiMethod,
    errors: &mut Vec<ApiCheckError>,
    usually_siblings: &UsuallySiblings,
    exceptions: &Exceptions,
) {
    let all_params: Vec<&String> = ron_method.params.iter().map(|a| &a.name).collect();
    for (param1, param2) in &usually_siblings.params {
        if all_params.contains(&param1) && all_params.contains(&param2) {
            if let Some(ron_param1) = find_ron_param_by_name(param1, ron_method) {
                if let Some(ron_param2) = find_ron_param_by_name(param2, ron_method) {
                    // If they arent optional then its like chat_id and user_id in getChatMember
                    if let schema::Type::Option(_) = ron_param1.ty {
                        if let schema::Type::Option(_) = ron_param2.ty {
                            errors.push(ApiCheckError::ParamsShouldBeSiblings {
                                method: ron_method.names.0.clone(),
                                param1: param1.to_owned(),
                                param2: param2.to_owned(),
                            })
                        }
                    }
                }
            } // No need to error if they dont exist, it is checked next
        }
    }

    for param in &method.arguments {
        let mut param_name = param.name.clone();
        escape_kw(&mut param_name);

        if let Some(ron_param) = find_ron_param_by_name(&param_name, ron_method) {
            check_param(&ron_param, param, method.name.clone(), false, errors, exceptions);
        } else if !exceptions.is_method_field_exception(method.name.clone(), param_name) {
            errors.push(ApiCheckError::ParamDoesNotExist {
                method: ron_method.names.0.clone(),
                param: param.name.clone(),
            });
        }
    }
}

// Because webarchive links like https://web.archive.org/web/20250817052931/https://core.telegram.org/bots/api should work too
fn extract_original_url(s: &str) -> &str {
    s.find("https://core.telegram.org")
        .map(|idx| &s[idx..])
        .expect("Documentation link doesnt have https://core.telegram.org")
}

// Checks everything about the method that is not params
fn check_ron_method_meta(
    ron_method: &schema::Method,
    method: &ApiMethod,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    check_type(
        &ron_method.return_ty,
        &method.return_type.0,
        "return_ty".to_owned(),
        method.name.clone(),
        errors,
        exceptions,
    );

    // Some docs are for some reason like api/#something, not api#something.
    if ron_method.tg_doc.replace("/#", "#")
        != extract_original_url(&method.documentation_link.replace("/#", "#"))
    {
        errors.push(ApiCheckError::MethodDocLinkDoesNotMatch {
            method: ron_method.names.0.clone(),
            doc_link: ron_method.tg_doc.clone(),
            actual_doc_link: method.documentation_link.clone(),
        });
    }
}

fn check_ron_method(
    ron_method: &schema::Method,
    method: &ApiMethod,
    errors: &mut Vec<ApiCheckError>,
    usually_siblings: &UsuallySiblings,
    exceptions: &Exceptions,
) {
    check_ron_method_meta(ron_method, method, errors, exceptions);
    check_ron_params(ron_method, method, errors, usually_siblings, exceptions);
}

fn check_param(
    ron_param: &schema::Param,
    param: &Argument,
    method_name: String,
    // If it is a method with a sibling, some optional fields could be required in our
    // schema
    ignore_optional: bool,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    let mut ron_param = ron_param.clone();

    if let schema::Type::Option(ron_param_type) = &ron_param.ty {
        if param.required {
            errors.push(ApiCheckError::ParamIsNotOptional {
                method: method_name.clone(),
                param: param.name.clone(),
            });
        }
        ron_param.ty = *ron_param_type.clone()
    } else if !param.required && !ignore_optional {
        errors.push(ApiCheckError::ParamIsNotRequired {
            method: method_name.clone(),
            param: param.name.clone(),
        });
    }

    check_type(
        &ron_param.ty,
        &param.kind.0,
        param.name.clone(),
        method_name.clone(),
        errors,
        exceptions,
    );
}

fn check_type(
    ron_type: &schema::Type,
    api_type: &Kind,
    param_name: String,
    method_name: String,
    errors: &mut Vec<ApiCheckError>,
    exceptions: &Exceptions,
) {
    // Assumes that the ron_type is not Option, since api_type has `required` field
    // instead
    assert!(!matches!(ron_type, &schema::Type::Option(_)), "ron_type can't be Option");

    // If it matches, do nothing
    match (ron_type, api_type) {
        (schema::Type::bool, Kind::Bool { default: _ }) => {}
        (
            schema::Type::u8
            | schema::Type::u16
            | schema::Type::u32
            | schema::Type::u64
            | schema::Type::i32
            | schema::Type::i64
            | schema::Type::DateTime, // DateTime is always an int timestamp in the TBA
            Kind::Integer { default: _, min, max, enumeration: _ },
        ) => {
            let (ron_min, ron_max) = match ron_type {
                schema::Type::u8 => (u8::MIN as i64, u8::MAX as i64),
                schema::Type::u16 => (u16::MIN as i64, u16::MAX as i64),
                schema::Type::u32 => (u32::MIN as i64, u32::MAX as i64),
                schema::Type::u64 => (u64::MIN as i64, i64::MAX), // u64::MAX will
                // overflow. And the TBA will never return something bigger than i64.
                schema::Type::i32 => (i32::MIN as i64, i32::MAX as i64),
                schema::Type::i64 => (i64::MIN, i64::MAX),
                schema::Type::DateTime => (i64::MIN, i64::MAX),
                _ => unreachable!("Other types are not in the match statement"),
            };

            if min.is_some() && ron_min > min.unwrap() {
                errors.push(ApiCheckError::ParamIsTooRestrictive {
                    method: method_name.clone(),
                    param: param_name.clone(),
                    param_limit: ron_min,
                    actual_limit: min.unwrap(),
                })
            }
            if max.is_some() && ron_max < max.unwrap() {
                errors.push(ApiCheckError::ParamIsTooRestrictive {
                    method: method_name.clone(),
                    param: param_name.clone(),
                    param_limit: ron_max,
                    actual_limit: max.unwrap(),
                })
            }
        }
        (
            schema::Type::String | schema::Type::Url,
            Kind::String { default: _, min_len: _, max_len: _, enumeration: _ },
        ) => {}
        (schema::Type::f64, Kind::Float) => {}
        (schema::Type::True, Kind::Bool { default: Some(true) }) => {}
        (schema::Type::ArrayOf(ron_type), Kind::Array { array: api_type }) => {
            check_type(ron_type, &api_type.0, param_name, method_name, errors, exceptions);
        }
        (schema::Type::RawTy(ron_raw_type), Kind::Reference { reference: raw_type }) => {
            if ron_raw_type != raw_type
                && !exceptions.is_field_type_exception(ron_raw_type.to_owned(), raw_type.to_owned())
            {
                errors.push(ApiCheckError::ParamRawTyDoesNotMatch {
                    method: method_name.clone(),
                    param: param_name.clone(),
                    raw_type: ron_raw_type.to_owned(),
                    actual_type: raw_type.to_owned(),
                })
            }
        }
        (schema::Type::RawTy(_), Kind::AnyOf { any_of: _ }) => {} // If it's AnyOf, we have to
        // have our own type like `Recipient`
        (schema::Type::True, Kind::AnyOf { any_of: _ }) => {} // Or with AnyOf there could be
        // either `True` or `Message`, like with `editMessageMedia`
        (schema::Type::RawTy(_), _) => {} // Any other is fine, we can't check if
        // our type like `PollId` is actually String or Integer
        _ => errors.push(ApiCheckError::ParamTyDoesNotMatch {
            method: method_name.clone(),
            param: param_name.clone(),
            raw_type: ron_type.clone(),
            actual_type: api_type.clone(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_ron_schema() {
        let ron_schema = schema::get();
        let api_schema = get_api_schema();
        let mut errors = vec![];

        // Here you can set exceptions for fields that don't exist in our schema for
        // some reason
        let mut exceptions = Exceptions::new(vec![
            // The Inline methods can't set these values
            Exception::MethodField {
                method: "editMessageTextInline".to_owned(),
                param: "link_preview_options".to_owned(),
            },
            Exception::MethodField {
                method: "editMessageCaptionInline".to_owned(),
                param: "link_preview_options".to_owned(),
            },
            Exception::MethodField {
                method: "editMessageCaptionInline".to_owned(),
                param: "show_caption_above_media".to_owned(),
            },
            Exception::MethodField {
                method: "editMessageLiveLocationInline".to_owned(),
                param: "live_period".to_owned(),
            },
            // getGameHighScores has `target` field for that
            Exception::MethodField {
                method: "getGameHighScores".to_owned(),
                param: "chat_id".to_owned(),
            },
            Exception::MethodField {
                method: "getGameHighScores".to_owned(),
                param: "message_id".to_owned(),
            },
            Exception::MethodField {
                method: "getGameHighScores".to_owned(),
                param: "inline_message_id".to_owned(),
            },
            Exception::MethodField {
                method: "getBusinessAccountGifts".to_owned(),
                param: "exclude_limited".to_owned(),
            },
        ]);

        // Some types can be more narrow in ronami, e.g. `Me` is a subset of `User`
        exceptions.extend(vec![
            Exception::FieldType {
                ron_raw_type: "ReplyMarkup".to_owned(),
                actual_type: "InlineKeyboardMarkup".to_owned(),
            },
            Exception::FieldType { ron_raw_type: "Me".to_owned(), actual_type: "User".to_owned() },
        ]);

        // If checker finds that one sibling has that field name, while the other
        // doesn't, it will consider it normal. To add a one-time exception,
        // refer to `missing_field_exceptions` argument.
        exceptions.extend(vec![
            Exception::SiblingParam { param: "inline_message_id".to_owned() },
            Exception::SiblingParam { param: "user_id".to_owned() },
            Exception::SiblingParam { param: "chat_id".to_owned() },
            Exception::SiblingParam { param: "message_id".to_owned() },
        ]);

        // Some params are usually siblings, and if they are not, its an error.
        let usually_siblings = UsuallySiblings::new(vec![
            ("inline_message_id".to_owned(), "message_id".to_owned()),
            ("user_id".to_owned(), "chat_id".to_owned()),
        ]);

        let api_version = format!("{}.{}", api_schema.version.major, api_schema.version.minor);
        let ron_version = ron_schema.api_version.ver.clone();
        if api_version != ron_version {
            panic!(
                "schema.ron is of api version {ron_version}, while the checking schema is \
                 {api_version}. Please update the checking schema."
            );
        }

        for method in api_schema.methods {
            if let Some(ron_method) = find_ron_method_by_name(&method.name, &ron_schema) {
                if let Some(ref sibling) = ron_method.sibling {
                    let ron_sibling_method = find_ron_method_by_name(sibling, &ron_schema)
                        .unwrap_or_else(|| {
                            panic!(
                                "{}",
                                format!("Sibling method of {} does not exist", method.name)
                            )
                        });

                    if ron_sibling_method.sibling != Some(ron_method.names.0.clone()) {
                        errors.push(ApiCheckError::SiblingsDontMatch {
                            method: ron_method.names.0.clone(),
                            fake_sibling: ron_sibling_method.names.0.clone(),
                        });
                        // No point in checking corrupt method
                        continue;
                    }

                    check_ron_siblings(
                        &ron_method,
                        &ron_sibling_method,
                        &method,
                        &mut errors,
                        &exceptions,
                    );
                } else {
                    check_ron_method(
                        &ron_method,
                        &method,
                        &mut errors,
                        &usually_siblings,
                        &exceptions,
                    );
                }
            } else {
                errors.push(ApiCheckError::MethodDoesNotExist { method: method.name });
            };
        }

        if !errors.is_empty() {
            let mut errors_string = String::new();
            for (i, error) in errors.iter().enumerate() {
                errors_string = format!("{errors_string}\n\n{}. {error}", i + 1);
            }
            panic!(
                "schema.ron does not match the check schema. The errors are:\n\n{errors_string}",
            );
        }
    }
}