rustigram-api 0.12.0

Telegram Bot API method builders and HTTP client for rustigram
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! A media option reaches Telegram whichever send path the file takes.
//!
//! Every media builder has two paths. Given a `file_id` or a URL the parameters
//! go out as a JSON body, which serde builds from the params struct, so an
//! option that has a setter necessarily arrives. Given raw bytes they go out as
//! `multipart/form-data`, which is assembled field by field in hand-written
//! code — and that is where five settable options were silently dropped:
//! `reply_parameters`, `reply_markup`, `message_effect_id`,
//! `allow_paid_broadcast`, and `suggested_post_parameters`. A bot could call
//! `.reply_to(id)` on a byte upload and Telegram would never see it.
//!
//! Nothing in the type system can catch that: both paths compile, both send a
//! valid request, and both return a `Message`. The only way to see it is to set
//! an option, send it both ways, and compare what actually left the process.
//!
//! # The property
//!
//! The two paths must carry the *same field names*. Not the same encoding —
//! JSON nests `reply_parameters` as an object where multipart sends it as one
//! serialised part — but the same set of things sent. That is exactly what
//! drifted, and it is checkable without reimplementing either encoder.

mod mock;

use mock::fixtures;
use rustigram_api::BotClient;
use serde_json::Value;
use std::collections::BTreeSet;
use wiremock::Request;

/// The field names a request carries, whichever encoding it used.
fn field_names(request: &Request) -> BTreeSet<String> {
    match serde_json::from_slice::<Value>(&request.body) {
        Ok(Value::Object(body)) => body.keys().cloned().collect(),
        _ => mock::multipart_field_names(request).into_iter().collect(),
    }
}

/// Sends one call twice — as a byte upload and by `file_id` — and returns the
/// field names each path produced.
///
/// The two calls go to separate servers so neither sees the other's request.
macro_rules! both_paths {
    (|$client:ident, $file:ident| $call:expr) => {{
        async fn run(upload: bool) -> BTreeSet<String> {
            let (server, $client) = mock::spawn().await;
            mock::mount_catch_all(&server).await;
            let $file = if upload {
                fixtures::uploaded_file()
            } else {
                fixtures::input_file()
            };
            let _ = $call.await;
            field_names(&mock::only_request(&server).await)
        }
        (run(true).await, run(false).await)
    }};
}

/// Records how the two paths differ for one method, if at all.
fn difference(
    method: &str,
    multipart: &BTreeSet<String>,
    json: &BTreeSet<String>,
) -> Option<String> {
    let dropped: Vec<&String> = json.difference(multipart).collect();
    let extra: Vec<&String> = multipart.difference(json).collect();
    (!dropped.is_empty() || !extra.is_empty()).then(|| {
        format!(
            "  {method}:\n                 never reaches Telegram on a byte upload: {dropped:?}\n                 never reaches Telegram by file_id:      {extra:?}"
        )
    })
}

/// Every media builder carries the same options on both paths.
///
/// One case per builder that accepts an `InputFile`, each setting the options
/// that builder actually has. `upload_sticker_file` is absent on purpose: it
/// takes no options at all, so there is nothing to drop.
#[tokio::test]
async fn media_builders_send_the_same_options_on_both_paths() {
    let mut differences = Vec::new();
    let (multipart, json) = both_paths!(|c, f| c
        .send_photo(1_i64, f)
        .caption("cap")
        .protect_content(true)
        .message_effect_id("effect")
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7)));
    differences.extend(difference("sendPhoto", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_audio(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .caption("cap")
        .parse_mode(rustigram_types::message::ParseMode::HTML)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendAudio", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_document(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .caption("cap")
        .parse_mode(rustigram_types::message::ParseMode::HTML)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendDocument", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_video(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .caption("cap")
        .parse_mode(rustigram_types::message::ParseMode::HTML)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendVideo", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_animation(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .caption("cap")
        .parse_mode(rustigram_types::message::ParseMode::HTML)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendAnimation", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_voice(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .caption("cap")
        .parse_mode(rustigram_types::message::ParseMode::HTML)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendVoice", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_video_note(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendVideoNote", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_sticker(1_i64, f)
        .business_connection_id("bc")
        .message_thread_id(3)
        .direct_messages_topic_id(4)
        .disable_notification(true)
        .message_effect_id("effect")
        .protect_content(true)
        .allow_paid_broadcast(true)
        .reply_parameters(fixtures::reply_to(7))
        .receiver_user_id(9)
        .callback_query_id("cq"));
    differences.extend(difference("sendSticker", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c
        .send_live_photo(1_i64, f, fixtures::input_file())
        .caption("cap")
        .has_spoiler(true)
        .show_caption_above_media(true)
        .protect_content(true)
        .message_effect_id("effect")
        .reply_parameters(fixtures::reply_to(7)));
    differences.extend(difference("sendLivePhoto", &multipart, &json));

    let (multipart, json) = both_paths!(|c, f| c.set_chat_photo(1_i64, f));
    differences.extend(difference("setChatPhoto", &multipart, &json));

    assert!(
        differences.is_empty(),
        "{} media builder(s) send different options depending on how the file \
         travels. An option accepted by the builder and absent from one path is \
         silently lost — the call still succeeds:\n{}",
        differences.len(),
        differences.join("\n")
    );
}

/// The exact bug: a reply set on a byte upload reaches the form.
///
/// Pinned on its own because it is the one a user reported behaviour for — the
/// photo arrived, and it was not a reply. Everything about the call looked
/// correct from the outside.
#[tokio::test]
async fn a_reply_survives_a_byte_upload() {
    let (server, client) = mock::spawn().await;
    mock::mount_catch_all(&server).await;

    let _ = client
        .send_photo(42_i64, fixtures::uploaded_file())
        .reply_parameters(fixtures::reply_to(7))
        .await;

    let request = mock::only_request(&server).await;
    let fields = mock::multipart_field_names(&request);
    assert!(
        fields.iter().any(|f| f == "reply_parameters"),
        "the reply was dropped from the multipart form; Telegram would send the \
         photo as a new message instead of a reply. Fields sent: {fields:?}"
    );
}

/// Every option the shared multipart helper is supposed to carry is carried.
///
/// The five that were dropped, asserted by name. The parity test above would
/// catch a regression in any of them too, but only as a set difference — this
/// states which options the helper exists to handle, so a reader of a failure
/// knows what was lost rather than inferring it from a diff.
#[tokio::test]
async fn the_shared_multipart_options_all_reach_the_form() {
    let (server, client) = mock::spawn().await;
    mock::mount_catch_all(&server).await;

    let _ = client
        .send_photo(42_i64, fixtures::uploaded_file())
        .reply_parameters(fixtures::reply_to(7))
        .message_effect_id("effect")
        .allow_paid_broadcast(true)
        .caption("cap")
        .protect_content(true)
        .await;

    let fields = mock::multipart_field_names(&mock::only_request(&server).await);
    for option in [
        "reply_parameters",
        "message_effect_id",
        "allow_paid_broadcast",
        "caption",
        "protect_content",
    ] {
        assert!(
            fields.iter().any(|f| f == option),
            "`{option}` was set on the builder and never reached the form. \
             Fields sent: {fields:?}"
        );
    }
}

/// A byte upload really does take the multipart path, and a `file_id` does not.
///
/// The premise every test above rests on. If both paths quietly became JSON the
/// parity assertions would pass while checking one encoder twice.
#[tokio::test]
async fn the_two_paths_use_the_encodings_they_are_named_for() {
    async fn content_type(file: rustigram_types::file::InputFile) -> String {
        let (server, client) = mock::spawn().await;
        mock::mount_catch_all(&server).await;
        let _ = client.send_photo(1_i64, file).await;
        mock::only_request(&server)
            .await
            .headers
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_owned()
    }

    let upload = content_type(fixtures::uploaded_file()).await;
    assert!(
        upload.starts_with("multipart/form-data"),
        "a byte upload must go out as multipart, got `{upload}`"
    );

    let by_id = content_type(fixtures::input_file()).await;
    assert!(
        by_id.starts_with("application/json"),
        "a file_id send must go out as JSON, got `{by_id}`"
    );
}

/// The client's `BotClient` type is what the sweep exercises.
///
/// A compile-time assertion that the fixtures build the argument types the
/// builders expect; if a signature changes, this file fails to compile rather
/// than silently testing a different call.
#[allow(dead_code)]
fn fixtures_match_the_builder_signatures(client: &BotClient) {
    let _ = client.send_photo(1_i64, fixtures::uploaded_file());
    let _ = client.send_photo(1_i64, fixtures::input_file());
}

/// Every media builder exposes exactly the options its method takes.
///
/// Two failures this catches, both invisible to the coverage suite — that
/// resolves a builder's parameters through `MediaSendOptions`, so a field there
/// counts as covered whether or not any setter reaches it:
///
/// - A setter for a parameter the spec does not define is surface the caller can
///   reach and Telegram will not honour.
/// - A parameter the spec *does* define with no setter is a feature the crate
///   claims to support and cannot.
///
/// Driven by the committed snapshot, and covering the hand-written builders as
/// well as the seven the macro generates. An earlier version parsed only
/// `media_sender!` invocations and asserted exactly seven, which excluded
/// `SendPhoto` and `SendLivePhoto` *by construction* — and both were missing
/// setters for parameters the Bot API defines.
#[test]
fn every_media_builder_exposes_exactly_the_options_its_method_takes() {
    let source = include_str!("../src/methods/sending.rs");
    let spec: SpecMethods = serde_json::from_str(SNAPSHOT).expect("the snapshot parses");
    let mut wrong = Vec::new();

    for (builder, api_method, exposed) in media_builders(source) {
        let Some(params) = spec.methods.get(&api_method) else {
            wrong.push(format!("  {builder}: `{api_method}` is not in the spec"));
            continue;
        };
        for option in &exposed {
            if !params.contains_key(option.as_str()) {
                wrong.push(format!(
                    "  {api_method}: exposes `{option}`, which the spec does not \
                     define for it — a caller can set it and Telegram ignores it"
                ));
            }
        }
        // Only the shared options are the builder's to expose; the rest are
        // constructor arguments or per-method extras held as their own fields.
        for option in SHARED_OPTIONS {
            if params.contains_key(*option) && !exposed.iter().any(|e| e == option) {
                wrong.push(format!(
                    "  {api_method}: the spec takes `{option}` and no setter reaches it"
                ));
            }
        }
    }

    assert!(
        wrong.is_empty(),
        "{} media builder surface mismatch(es) against the Bot API spec:\n{}",
        wrong.len(),
        wrong.join("\n")
    );
}

/// The options that live in `MediaSendOptions` and vary by method.
const SHARED_OPTIONS: &[&str] = &[
    "business_connection_id",
    "message_thread_id",
    "direct_messages_topic_id",
    "caption",
    "parse_mode",
    "caption_entities",
    "show_caption_above_media",
    "has_spoiler",
    "disable_notification",
    "protect_content",
    "allow_paid_broadcast",
    "message_effect_id",
    "reply_parameters",
    "reply_markup",
    "suggested_post_parameters",
    "receiver_user_id",
    "callback_query_id",
];

const SNAPSHOT: &str = include_str!("../../rustigram-types/tests/spec/bot-api-10.2.json");

#[derive(serde::Deserialize)]
struct SpecMethods {
    methods:
        std::collections::BTreeMap<String, std::collections::BTreeMap<String, serde_json::Value>>,
}

/// Every media builder, as (builder, API method, shared options it exposes).
///
/// Two sources, because the crate has two kinds: seven generated by
/// `media_sender!`, and two written out. Missing either is how a gap hides.
fn media_builders(source: &str) -> Vec<(String, String, Vec<String>)> {
    /// Shared options the macro gives every builder it generates.
    const MACRO_UNIVERSAL: &[&str] = &[
        "business_connection_id",
        "message_thread_id",
        "direct_messages_topic_id",
        "disable_notification",
        "message_effect_id",
        "protect_content",
        "allow_paid_broadcast",
        "reply_parameters",
        "reply_markup",
        "suggested_post_parameters",
        "receiver_user_id",
        "callback_query_id",
    ];

    let mut found = Vec::new();

    // ── The generated seven ────────────────────────────────────────────────
    for block in source.split("media_sender!(").skip(1) {
        let head = block.split(");").next().unwrap_or_default();
        let Some(builder) = head
            .split(|c: char| !c.is_alphanumeric() && c != '_')
            .find(|token| token.starts_with("Send"))
            .map(str::to_owned)
        else {
            continue;
        };
        let quoted: Vec<&str> = head.split('"').skip(1).step_by(2).collect();
        let Some(api_method) = quoted.get(1) else {
            continue;
        };
        let caption_opts: Vec<String> = head
            .rsplit_once('[')
            .and_then(|(_, tail)| tail.split(']').next())
            .map(|list| {
                list.split(',')
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        let exposed = MACRO_UNIVERSAL
            .iter()
            .map(|s| (*s).to_owned())
            .chain(caption_opts)
            .collect();
        found.push((builder, (*api_method).to_owned(), exposed));
    }
    let generated = found.len();
    assert_eq!(
        generated, 7,
        "expected seven macro-generated builders, parsed {generated}"
    );

    // ── The hand-written ones ──────────────────────────────────────────────
    //
    // Identified by holding a `MediaSendOptions`, so a third one added later is
    // picked up without editing this list. Their setters are read from the impl
    // block, and the API method from the call that actually sends the request.
    for block in source.split("\npub struct ").skip(1) {
        let builder = block
            .split_whitespace()
            .next()
            .unwrap_or_default()
            .to_owned();
        let Some(body) = block.split("\n}").next() else {
            continue;
        };
        if !body.contains("opts: MediaSendOptions") || !builder.starts_with("Send") {
            continue;
        }
        if found.iter().any(|(name, _, _)| *name == builder) {
            continue;
        }
        let Some(start) = source.find(&format!("impl {builder} {{")) else {
            continue;
        };
        let impl_block = &source[start
            ..source[start + 5..]
                .find("\nimpl ")
                .map_or(source.len(), |o| start + 5 + o)];

        let mut exposed = Vec::new();
        let mut rest = impl_block;
        while let Some(at) = rest.find("pub fn ") {
            rest = &rest[at + 7..];
            let name: String = rest
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect();
            // A setter takes `mut self`; `new` and `into_future` do not.
            let after = &rest[name.len()..];
            if after.trim_start().starts_with('(')
                && after[..after.find(')').unwrap_or(0).max(1)].contains("mut self")
            {
                exposed.push(name);
            }
        }

        // The API method is named in the `IntoFuture` impl, which is a separate
        // block from the setters — reading it from the send call rather than
        // deriving it from the struct name keeps the two from drifting.
        let api_method = source
            .find(&format!("impl IntoFuture for {builder} "))
            .and_then(|at| {
                let tail = &source[at..];
                ["post_multipart(\"", "post_json(\""]
                    .iter()
                    .filter_map(|marker| tail.find(marker).map(|o| (o, *marker)))
                    .min_by_key(|(o, _)| *o)
                    .and_then(|(o, marker)| {
                        tail[o + marker.len()..]
                            .split('"')
                            .next()
                            .map(str::to_owned)
                    })
            })
            .unwrap_or_default();
        found.push((builder, api_method, exposed));
    }

    assert!(
        found.len() > generated,
        "no hand-written media builders were found — they were invisible to this \
         test once already, and both had spec gaps"
    );
    found
}

/// No media builder keeps its own copy of a shared option.
///
/// `SendLivePhoto` declared `has_spoiler` and `message_effect_id` as builder
/// fields while `MediaSendOptions` already held both. The two shared encoders
/// only ever see `opts`, so each send path had to remember to hand-patch the
/// locals in — and the multipart one remembered only one of the two. The result
/// was `.has_spoiler(true)` silently dropped on byte uploads.
///
/// Every other check in this file was blind to it by construction: the parity
/// sweep had no `sendLivePhoto` case, the source scan enumerates
/// `MediaSendOptions` and so cannot see a field that is not in it, and
/// [`each_media_builder_exposes_exactly_the_options_its_method_takes`] parses
/// only `media_sender!` invocations. A shadowed field is invisible to all three,
/// which is what makes this worth checking directly.
#[test]
fn no_media_builder_shadows_a_shared_option() {
    let source = include_str!("../src/methods/sending.rs");

    let shared: Vec<&str> = source
        .split("pub struct MediaSendOptions {")
        .nth(1)
        .and_then(|s| s.split("\n}").next())
        .expect("the MediaSendOptions declaration")
        .lines()
        .filter_map(|l| l.trim().strip_prefix("pub "))
        .filter_map(|l| l.split(':').next())
        .collect();
    assert!(
        shared.len() > 10,
        "parsed only {} shared options — the struct's shape changed and this \
         test would check almost nothing",
        shared.len()
    );

    // Builders are the structs that hold a `MediaSendOptions`.
    let mut shadowed = Vec::new();
    for block in source.split("\npub struct ").skip(1) {
        let name = block.split_whitespace().next().unwrap_or_default();
        let Some(body) = block.split("\n}").next() else {
            continue;
        };
        if !body.contains("opts: MediaSendOptions") {
            continue;
        }
        for line in body.lines() {
            let Some((field, _)) = line.trim().trim_start_matches("pub ").split_once(':') else {
                continue;
            };
            let field = field.trim();
            if shared.contains(&field) {
                shadowed.push(format!("  {name}.{field} shadows MediaSendOptions.{field}"));
            }
        }
    }

    assert!(
        shadowed.is_empty(),
        "{} builder field(s) duplicate a shared option. The shared encoders read \
         `opts` only, so a local copy reaches the wire only where some send path \
         remembers to add it by hand — route it through `self.opts` \
         instead:\n{}",
        shadowed.len(),
        shadowed.join("\n")
    );
}