blazegram 0.4.2

Telegram bot framework: clean chats, zero garbage, declarative screens, pure Rust MTProto.
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
//! App — the main entry point for building a Blazegram bot.
//!
//! Uses grammers (pure Rust MTProto) for direct connection to Telegram DC.

use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;

use crate::file_session::FileSession;
use grammers_client::{Client, client::UpdatesConfiguration};
use grammers_mtsender::SenderPool;

use crate::bot_api::BotApi;
use crate::conversation::Conversation;
use crate::ctx::Ctx;
use crate::error::{HandlerError, HandlerResult};
use crate::form::{Form, FormData};
use crate::grammers_adapter::{DEFAULT_API_HASH, DEFAULT_API_ID, GrammersAdapter};
use crate::i18n::{self, I18n};
use crate::metrics::metrics;
use crate::middleware::Middleware;
use crate::router::Router;
use crate::serializer::ChatSerializer;
use crate::state::{InMemoryStore, StateStore};
use crate::types::*;
use crate::update_parser::convert_update;

/// Entry point for building a Blazegram bot. Use [`App::builder`] to start.
pub struct App;

/// Fluent builder for configuring and launching an [`App`].
pub struct AppBuilder {
    token: String,
    api_id: i32,
    api_hash: String,
    session_file: String,
    router: Router,
    store: Option<Arc<dyn StateStore>>,
    middlewares: Vec<Arc<dyn Middleware>>,
    forms: HashMap<String, Form>,
    conversations: HashMap<String, Conversation>,
    rate_limit_rps: Option<u32>,
    on_error: Option<Arc<ErrorHandler>>,
    snapshot_path: Option<String>,
    snapshot_interval: std::time::Duration,
    max_state_keys: usize,
}

type ErrorHandler = dyn Fn(ChatId, HandlerError) + Send + Sync;

impl App {
    /// Create a new bot application builder with the given token.
    pub fn builder(token: impl Into<String>) -> AppBuilder {
        AppBuilder {
            token: token.into(),
            api_id: DEFAULT_API_ID,
            api_hash: DEFAULT_API_HASH.to_string(),
            session_file: "bot.session".to_string(),
            router: Router::new(),
            store: None,
            middlewares: Vec::new(),
            forms: HashMap::new(),
            conversations: HashMap::new(),
            rate_limit_rps: None,
            on_error: None,
            snapshot_path: None,
            snapshot_interval: std::time::Duration::from_secs(300),
            max_state_keys: 1000,
        }
    }
}

impl AppBuilder {
    /// Override Telegram API credentials (default: TDesktop).
    pub fn api_credentials(mut self, api_id: i32, api_hash: impl Into<String>) -> Self {
        self.api_id = api_id;
        self.api_hash = api_hash.into();
        self
    }

    /// Session file path for MTProto auth keys (default: "bot.session").
    pub fn session_file(mut self, path: impl Into<String>) -> Self {
        self.session_file = path.into();
        self
    }

    /// Set the state persistence backend (default: in-memory).
    pub fn store(mut self, store: impl StateStore + 'static) -> Self {
        self.store = Some(Arc::new(store));
        self
    }

    /// Register a middleware that runs before every handler.
    pub fn middleware(mut self, m: impl Middleware + 'static) -> Self {
        self.middlewares.push(Arc::new(m));
        self
    }

    /// Register a handler for a `/command`.
    pub fn command(
        mut self,
        name: &str,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.command(name, handler);
        self
    }

    /// Register a handler for a callback query prefix (e.g. `"pick"` matches `"pick:a"`).
    pub fn callback(
        mut self,
        prefix: &str,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.callback(prefix, handler);
        self
    }

    /// Register a text input handler for a specific screen.
    pub fn on_input(
        mut self,
        screen_id: &str,
        handler: impl Fn(
            &mut Ctx,
            String,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_input(screen_id, handler);
        self
    }

    /// Register a media input handler for a specific screen.
    pub fn on_media_input(
        mut self,
        screen_id: &str,
        handler: impl Fn(
            &mut Ctx,
            ReceivedMedia,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_media_input(screen_id, handler);
        self
    }

    /// Catch-all handler for any text message not matched by screen-specific input handlers.
    pub fn on_any_text(
        mut self,
        handler: impl Fn(
            &mut Ctx,
            String,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_any_text(handler);
        self
    }

    /// Handler for unrecognized commands / messages that match no other route.
    pub fn on_unrecognized(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_unrecognized(handler);
        self
    }

    /// Register a handler for inline queries. The handler receives `(ctx, query, offset)`.
    pub fn on_inline(
        mut self,
        handler: impl Fn(
            &mut Ctx,
            String,
            String,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_inline(handler);
        self
    }

    /// Register a handler for when a user picks one of the inline results.
    pub fn on_chosen_inline(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_chosen_inline(handler);
        self
    }

    /// Register a handler for edited messages.
    pub fn on_message_edited(
        mut self,
        handler: impl Fn(
            &mut Ctx,
            String,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_message_edited(handler);
        self
    }

    /// Handler for pre-checkout queries (payment flow).
    /// The handler should call `ctx.approve_checkout()` or `ctx.decline_checkout(reason)` to approve/decline.
    pub fn on_pre_checkout(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_pre_checkout(handler);
        self
    }

    /// Handler for successful payments.
    pub fn on_successful_payment(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_successful_payment(handler);
        self
    }

    /// Handler for new members joining the chat.
    pub fn on_member_joined(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_member_joined(handler);
        self
    }

    /// Handler for members leaving the chat.
    pub fn on_member_left(
        mut self,
        handler: impl Fn(&mut Ctx) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_member_left(handler);
        self
    }

    /// Handler for [Web App](https://core.telegram.org/bots/webapps) data.
    pub fn on_web_app_data(
        mut self,
        handler: impl Fn(
            &mut Ctx,
            String,
        ) -> std::pin::Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.router.on_web_app_data(handler);
        self
    }

    /// Register a multi-step [`Form`].
    pub fn form(mut self, form: Form) -> Self {
        self.forms.insert(form.id.clone(), form);
        self
    }

    /// Register a [`RouterGroup`](crate::router::RouterGroup) with its own middleware stack.
    pub fn group(mut self, group: crate::router::RouterGroup) -> Self {
        self.router.group(group);
        self
    }

    /// Register a branching [`Conversation`].
    pub fn conversation(mut self, conv: Conversation) -> Self {
        self.conversations.insert(conv.id.clone(), conv);
        self
    }

    /// Set the maximum Telegram API requests per second (wraps BotApi in a rate limiter).
    pub fn rate_limit(mut self, rps: u32) -> Self {
        self.rate_limit_rps = Some(rps);
        self
    }

    /// Control whether unrecognized messages are silently deleted (default: `true`).
    ///
    /// When `true`, messages that match no command, callback, or input handler
    /// are automatically deleted to keep the chat clean. Set to `false` to
    /// leave user messages untouched.
    pub fn delete_unrecognized(mut self, yes: bool) -> Self {
        self.router.delete_unrecognized = yes;
        self
    }

    /// Maximum number of keys in per-chat state data (default: 1000).
    ///
    /// When the limit is reached, `ctx.set()` logs a warning and the oldest
    /// key is evicted. Prevents unbounded memory growth from accidental
    /// state accumulation.
    pub fn max_state_keys(mut self, max: usize) -> Self {
        self.max_state_keys = max;
        self
    }

    /// Set a custom [`I18n`] instance for translations.
    pub fn i18n(self, i: I18n) -> Self {
        i18n::set_i18n(i);
        self
    }

    /// Locales.
    pub fn locales(self, dir: &str, default_lang: &str) -> Self {
        let i = I18n::load(dir, default_lang).unwrap_or_else(|e| {
            panic!("AppBuilder::locales(): failed to load locales from {dir:?}: {e}")
        });
        i18n::set_i18n(i);
        self
    }

    /// Use Redis as the state backend. Requires the `redis` feature.
    #[cfg(feature = "redis")]
    pub fn redis_store(self, url: &str) -> Self {
        let store = crate::redis_store::RedisStore::new(url).unwrap_or_else(|e| {
            panic!("AppBuilder::redis_store(): failed to connect to Redis at {url:?}: {e}")
        });
        self.store(store)
    }

    /// Use redb (pure Rust, ACID) as the persistent state backend.
    #[cfg(feature = "redb")]
    pub fn redb_store(self, path: &str) -> Self {
        let store = crate::redb_store::RedbStore::open(path).unwrap_or_else(|e| {
            panic!("AppBuilder::redb_store(): failed to open redb store at {path:?}: {e}")
        });
        self.store(store)
    }

    /// Register a global error handler, called when any handler returns an error.
    pub fn on_error(
        mut self,
        handler: impl Fn(ChatId, HandlerError) + Send + Sync + 'static,
    ) -> Self {
        self.on_error = Some(Arc::new(handler));
        self
    }

    /// Enable periodic state snapshots to disk (InMemoryStore only).
    pub fn snapshot(mut self, path: impl Into<String>) -> Self {
        self.snapshot_path = Some(path.into());
        self
    }

    /// Set snapshot interval (default: 5 minutes).
    pub fn snapshot_interval(mut self, interval: std::time::Duration) -> Self {
        self.snapshot_interval = interval;
        self
    }

    /// Build and run the bot. Phases: connect → event_loop → shutdown.
    pub async fn run(self) {
        // ━━━ Phase 1: Build state & connect ━━━
        let snapshot_store: Option<Arc<InMemoryStore>>;
        let store: Arc<dyn StateStore> = if let Some(custom) = self.store {
            snapshot_store = None;
            custom
        } else {
            let mem = Arc::new(InMemoryStore::new());
            if let Some(ref snap_path) = self.snapshot_path {
                match mem.restore(snap_path).await {
                    Ok(0) => tracing::info!("No snapshot found, starting fresh"),
                    Ok(n) => tracing::info!(count = n, "Restored state from snapshot"),
                    Err(e) => tracing::error!(error = %e, "Failed to restore snapshot"),
                }
                snapshot_store = Some(Arc::clone(&mem));
            } else {
                snapshot_store = None;
            }
            mem
        };

        let serializer = Arc::new(ChatSerializer::new(store));
        let router = Arc::new(self.router);
        let middlewares = Arc::new(self.middlewares);
        let forms = Arc::new(self.forms);
        let conversations = Arc::new(self.conversations);
        let on_error = self.on_error;

        tracing::info!("Blazegram: connecting via MTProto...");

        // ── Create grammers session & client (pure Rust, no SQLite) ──
        let session = Arc::new(FileSession::open(&self.session_file).await);

        let SenderPool {
            runner,
            updates,
            handle,
        } = SenderPool::new(Arc::clone(&session) as _, self.api_id);
        let client = Client::new(handle.clone());

        // Spawn the sender pool runner
        let pool_task = tokio::spawn(runner.run());

        // ── Bot sign-in ──
        let is_authorized = match client.is_authorized().await {
            Ok(v) => v,
            Err(e) => {
                tracing::error!(error = %e, "Authorization check failed, aborting");
                return;
            }
        };
        if !is_authorized {
            tracing::info!("Signing in as bot...");
            if let Err(e) = client.bot_sign_in(&self.token, &self.api_hash).await {
                tracing::error!(error = %e, "Bot sign-in failed, aborting");
                return;
            }
            tracing::info!("Signed in successfully.");
        } else {
            tracing::info!("Already authorized (session restored).");
        }

        // ── Build adapter ──
        let adapter = GrammersAdapter::new(client.clone());

        // Restore peer cache from disk if snapshot is enabled
        if let Some(ref snap_path) = self.snapshot_path {
            let peers_path = format!("{}.peers", snap_path);
            if let Ok(bytes) = tokio::fs::read(&peers_path).await {
                if let Ok(peers) = postcard::from_bytes::<Vec<(i64, i64, i64)>>(&bytes) {
                    let count = peers.len();
                    adapter.import_peers(&peers);
                    tracing::info!(count, "Restored peer cache from disk");
                }
            }
        }
        // Build adapter + optional rate limiter.
        // Keep typed Arc for GC if rate limiting is enabled.
        let (bot_api, rate_limiter_ref): (
            Arc<dyn BotApi>,
            Option<Arc<crate::rate_limiter::RateLimitedBotApi<_>>>,
        ) = if let Some(rps) = self.rate_limit_rps {
            let rl = Arc::new(crate::rate_limiter::RateLimitedBotApi::new(
                adapter.clone(),
                rps,
            ));
            (rl.clone() as Arc<dyn BotApi>, Some(rl))
        } else {
            (Arc::new(adapter.clone()) as Arc<dyn BotApi>, None)
        };

        // ── Session flush task (persist auth keys + update state every 30s) ──
        session.start_flush_task(std::time::Duration::from_secs(30));

        // ── GC task ──
        let gc_ser = serializer.clone();
        let gc_rl = rate_limiter_ref.clone();
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(std::time::Duration::from_secs(600));
            loop {
                interval.tick().await;
                gc_ser.gc();
                if let Some(ref rl) = gc_rl {
                    rl.gc_idle_buckets();
                }
            }
        });

        // ── Snapshot task ──
        if let (Some(mem_store), Some(snap_path)) = (&snapshot_store, &self.snapshot_path) {
            mem_store.start_snapshot_task(snap_path.clone(), self.snapshot_interval);
            tracing::info!(
                interval_secs = self.snapshot_interval.as_secs(),
                "Snapshot task started"
            );
        }

        // ── Scheduler ──
        let (sched_cb_tx, mut sched_cb_rx) = tokio::sync::mpsc::unbounded_channel();
        let scheduler = crate::scheduler::spawn_scheduler(bot_api.clone(), sched_cb_tx);

        // ── Build shared runtime ──
        let runtime = Runtime {
            bot_api: bot_api.clone(),
            router: router.clone(),
            serializer: serializer.clone(),
            middlewares: middlewares.clone(),
            forms: forms.clone(),
            conversations: conversations.clone(),
            grammers_client: client.clone(),
            peer_cache: adapter.peer_cache(),
            on_error: on_error.clone(),
            max_state_keys: self.max_state_keys,
            scheduler,
        };

        // ━━━ Phase 2: Event loop ━━━
        tracing::info!("Blazegram bot running. Waiting for updates...");
        let mut update_stream = client
            .stream_updates(
                updates,
                UpdatesConfiguration {
                    catch_up: true,
                    ..Default::default()
                },
            )
            .await;

        let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("failed to register SIGTERM");

        loop {
            tokio::select! {
                _ = tokio::signal::ctrl_c() => {
                    tracing::info!("Ctrl+C received, shutting down...");
                    break;
                }
                _ = sigterm.recv() => {
                    tracing::info!("SIGTERM received, shutting down...");
                    break;
                }
                Some((chat_id, kind)) = sched_cb_rx.recv() => {
                    if let crate::scheduler::ScheduledKind::Callback(data) = kind {
                        // Load existing user info from state to avoid overwriting
                        // with fake scheduler UserInfo.
                        let user = match serializer.store.load(chat_id).await {
                            Ok(Some(s)) => s.user,
                            _ => UserInfo {
                                id: UserId(0),
                                first_name: "scheduler".to_string(),
                                last_name: None,
                                username: None,
                                language_code: None,
                            },
                        };
                        let rt = runtime.clone();
                        tokio::spawn(async move {
                            let incoming = IncomingUpdate {
                                chat_id,
                                user,
                                message_id: None,
                                kind: UpdateKind::CallbackQuery {
                                    id: "__scheduled".to_string(),
                                    data: Some(data),
                                    inline_message_id: None,
                                },
                            };
                            process_update(incoming, rt).await;
                        });
                    }
                }
                result = update_stream.next() => {
                    let update = match result {
                        Ok(update) => update,
                        Err(e) => {
                            tracing::error!(error = %e, "update stream error");
                            continue;
                        }
                    };

                    // Convert grammers Update → IncomingUpdate + cache peer
                    if let Some((incoming, peer_ref)) = convert_update(&update).await {
                        adapter.cache_peer(peer_ref);

                        // ── Inline queries & chosen results: fast path (no chat state, no serializer) ──
                        if matches!(&incoming.kind, UpdateKind::InlineQuery { .. } | UpdateKind::ChosenInlineResult { .. }) {
                            let bot = bot_api.clone();
                            let router = router.clone();
                            tokio::spawn(async move {
                                handle_inline_fast(incoming, bot, router).await;
                            });
                            continue;
                        }

                        let rt = runtime.clone();
                        tokio::spawn(async move {
                            process_update(incoming, rt).await;
                        });
                    }
                }
            }
        }

        // ━━━ Phase 3: Graceful shutdown ━━━
        tracing::info!("Syncing update state...");
        update_stream.sync_update_state().await;

        // Flush session (auth keys, update state) to disk
        if let Err(e) = session.flush().await {
            tracing::error!(error = %e, "failed to flush session");
        } else {
            tracing::info!("Session flushed to disk");
        }

        // Final snapshot before exit
        if let (Some(mem_store), Some(snap_path)) = (&snapshot_store, &self.snapshot_path) {
            tracing::info!("Saving final snapshot...");
            if let Err(e) = mem_store.snapshot(snap_path).await {
                tracing::error!(error = %e, "Failed to save final snapshot");
            } else {
                tracing::info!(chats = mem_store.len(), "Snapshot saved");
            }
            // Persist peer cache alongside snapshot
            let peers_path = format!("{}.peers", snap_path);
            let peers = adapter.export_peers();
            if let Ok(bytes) = postcard::to_allocvec(&peers) {
                let tmp = format!("{}.tmp", peers_path);
                let _ = tokio::fs::write(&tmp, bytes).await;
                let _ = tokio::fs::rename(&tmp, &peers_path).await;
                tracing::info!(count = peers.len(), "Peer cache saved");
            }
        }

        handle.quit();
        let _ = pool_task.await;
        tracing::info!("Blazegram bot stopped.");
    }
}

// ── Inline query: fast path (no chat state, no serializer) ──

async fn handle_inline_fast(
    incoming: IncomingUpdate,
    bot_api: Arc<dyn BotApi>,
    router: Arc<Router>,
) {
    let user = incoming.user().clone();
    let chat_id = ChatId(user.id.0 as i64);
    let dummy_state = ChatState::new(chat_id, user);
    let mut ctx = Ctx::new(dummy_state, bot_api.clone(), None);

    match &incoming.kind {
        UpdateKind::InlineQuery { query, offset, id } => {
            ctx.inline_query_id = Some(id.clone());
            tracing::debug!(query_id = %id, query = %query, "dispatching inline query to handler");
            match router
                .dispatch_inline(&mut ctx, query.clone(), offset.clone())
                .await
            {
                Ok(()) => tracing::debug!("inline query handler completed OK"),
                Err(e) => tracing::error!(error = %e, "inline query handler error"),
            }
        }
        UpdateKind::ChosenInlineResult {
            result_id,
            inline_message_id,
            ..
        } => {
            ctx.chosen_inline_result_id = Some(result_id.clone());
            if let Some(imid) = inline_message_id {
                ctx.mode = CtxMode::Inline {
                    inline_message_id: imid.clone(),
                };
            }
            if let Err(e) = router.route(&mut ctx, &incoming).await {
                tracing::error!(error = %e, "chosen inline result handler error");
            }
        }
        _ => {}
    }
}

// ── Shared runtime context (replaces 7+ Arc arguments) ──

#[derive(Clone)]
struct Runtime {
    bot_api: Arc<dyn BotApi>,
    router: Arc<Router>,
    serializer: Arc<ChatSerializer>,
    middlewares: Arc<Vec<Arc<dyn Middleware>>>,
    forms: Arc<HashMap<String, Form>>,
    conversations: Arc<HashMap<String, Conversation>>,
    grammers_client: grammers_client::Client,
    peer_cache: Arc<dashmap::DashMap<i64, grammers_session::types::PeerRef>>,
    on_error: Option<Arc<ErrorHandler>>,
    max_state_keys: usize,
    scheduler: crate::scheduler::SchedulerHandle,
}

// ── Process update ──

#[tracing::instrument(skip_all, fields(chat_id = %incoming.chat_id().0, user_id = %incoming.user().id.0))]
async fn process_update(incoming: IncomingUpdate, rt: Runtime) {
    metrics().inc_updates();
    let _timer = metrics().timer("update");

    let chat_id = incoming.chat_id();
    let user = incoming.user().clone();

    // (inline queries use user_id as pseudo chat_id)

    for mw in rt.middlewares.iter() {
        if !mw.before(chat_id, &user, &incoming).await {
            return;
        }
    }

    rt.serializer
        .serialize(chat_id, &user, |state| {
            let rt = rt.clone();
            let incoming = incoming.clone();

            async move {
                let callback_data = match &incoming.kind {
                    UpdateKind::CallbackQuery { data, .. } => data.clone(),
                    _ => None,
                };

                let mut ctx = Ctx::new(state, rt.bot_api.clone(), callback_data);
                ctx.grammers_client = Some(rt.grammers_client.clone());
                ctx.peer_cache = Some(rt.peer_cache.clone());
                ctx.max_state_keys = rt.max_state_keys;
                ctx.scheduler = Some(rt.scheduler.clone());

                // Determine CtxMode
                let cid = incoming.chat_id;
                if let UpdateKind::CallbackQuery {
                    inline_message_id: Some(ref imid),
                    ..
                } = incoming.kind
                {
                    ctx.mode = CtxMode::Inline {
                        inline_message_id: imid.clone(),
                    };
                    tracing::debug!(imid = %imid, "inline callback detected");
                } else if cid.0 < 0 {
                    let trigger = match &incoming.kind {
                        UpdateKind::CallbackQuery { .. } => incoming.message_id,
                        _ => None,
                    };
                    ctx.mode = CtxMode::Group {
                        trigger_message_id: trigger,
                    };
                }

                if let UpdateKind::CallbackQuery { id, .. } = &incoming.kind {
                    ctx.state.pending_callback_id = Some(id.clone());
                }
                ctx.deep_link = incoming.deep_link().map(String::from);
                ctx.incoming_message_id = incoming.message_id;

                // Set context fields from incoming update
                match &incoming.kind {
                    UpdateKind::Message { text, .. } => {
                        ctx.message_text = text.clone();
                    }
                    UpdateKind::InlineQuery { id, .. } => {
                        ctx.inline_query_id = Some(id.clone());
                    }
                    UpdateKind::ChosenInlineResult {
                        result_id,
                        inline_message_id,
                        ..
                    } => {
                        ctx.chosen_inline_result_id = Some(result_id.clone());
                        if let Some(imid) = inline_message_id {
                            ctx.mode = CtxMode::Inline {
                                inline_message_id: imid.clone(),
                            };
                        }
                    }
                    UpdateKind::PreCheckoutQuery {
                        id,
                        currency,
                        total_amount,
                        payload,
                    } => {
                        ctx.payment = crate::ctx::PaymentContext {
                            query_id: Some(id.clone()),
                            payload: Some(payload.clone()),
                            currency: Some(currency.clone()),
                            total_amount: Some(*total_amount),
                        };
                    }
                    UpdateKind::SuccessfulPayment {
                        currency,
                        total_amount,
                        payload,
                    } => {
                        ctx.payment = crate::ctx::PaymentContext {
                            query_id: None,
                            payload: Some(payload.clone()),
                            currency: Some(currency.clone()),
                            total_amount: Some(*total_amount),
                        };
                    }
                    _ => {}
                }

                // Built-in: dismiss button
                if let UpdateKind::CallbackQuery {
                    data: Some(ref d), ..
                } = incoming.kind
                {
                    if d == "__dismiss" {
                        if let Some(mid) = incoming.message_id {
                            let _ = rt
                                .bot_api
                                .delete_messages(incoming.chat_id, vec![mid])
                                .await;
                            ctx.state
                                .active_bot_messages
                                .retain(|t| t.message_id != mid);
                        }
                        if let Some(cb_id) = ctx.state.pending_callback_id.take() {
                            let _ = rt.bot_api.answer_callback_query(cb_id, None, false).await;
                        }
                        return ctx.state;
                    }
                }

                let result = {
                    let handler_fut = handle_form_or_route(
                        &rt.forms,
                        &rt.conversations,
                        &rt.router,
                        &mut ctx,
                        &incoming,
                    );
                    match tokio::time::timeout(std::time::Duration::from_secs(120), handler_fut)
                        .await
                    {
                        Ok(r) => r,
                        Err(_) => {
                            tracing::error!(chat_id = chat_id.0, "handler timed out (120s)");
                            Err(HandlerError::Timeout(std::time::Duration::from_secs(120)))
                        }
                    }
                };

                if let Some(cb_id) = ctx.state.pending_callback_id.take() {
                    let _ = rt.bot_api.answer_callback_query(cb_id, None, false).await;
                }

                for mw in rt.middlewares.iter() {
                    mw.after(chat_id, &ctx.state.user, &incoming, &result).await;
                }

                if let Err(ref e) = result {
                    metrics().inc_errors();
                    tracing::error!(chat_id = chat_id.0, error = %e, "handler error");
                }
                if let Err(e) = result {
                    if let Some(ref on_err) = rt.on_error {
                        on_err(chat_id, e);
                    }
                }

                // Seal reply — next handler call's reply() will send a new message
                ctx.state.reply_sealed = true;

                ctx.state
            }
        })
        .await;
}

async fn handle_form_or_route(
    forms: &HashMap<String, Form>,
    conversations: &HashMap<String, Conversation>,
    router: &Router,
    ctx: &mut Ctx,
    update: &IncomingUpdate,
) -> HandlerResult {
    // Check conversation first
    let conv_id: Option<String> = ctx.get("__conv_id");
    if let Some(conv_id) = conv_id {
        if let Some(conv) = conversations.get(&conv_id) {
            // If the user sent a /command, the conversation clears itself
            // and returns Ok(()) — fall through to the router below.
            let was_command = matches!(&update.kind,
                UpdateKind::Message { text: Some(t) } if t.starts_with('/'));
            let result = run_conversation_step(conv, ctx, update).await;
            if !was_command {
                return result;
            }
            // /command cancelled the conversation — fall through to router
        } else {
            ctx.remove("__conv_id");
        }
    }

    // Then form
    let form_id: Option<String> = ctx.get("__form_id");
    if let Some(form_id) = form_id {
        if let Some(form) = forms.get(&form_id) {
            // Same logic: /command cancels form, fall through to router.
            let was_command = matches!(&update.kind,
                UpdateKind::Message { text: Some(t) } if t.starts_with('/'));
            let result = run_form_step(form, ctx, update).await;
            if !was_command {
                return result;
            }
        } else {
            ctx.remove("__form_id");
        }
    }
    router.route(ctx, update).await
}

async fn run_form_step(form: &Form, ctx: &mut Ctx, update: &IncomingUpdate) -> HandlerResult {
    let step_idx: usize = ctx.get("__form_step").unwrap_or(0);
    let mut form_data: FormData = ctx.get("__form_data").unwrap_or_default();

    // NOTE: pending_user_messages push is handled by router.route() if we fall through
    // (i.e. /command cancels form). Push here only for messages we handle ourselves.

    match &update.kind {
        UpdateKind::CallbackQuery {
            data: Some(data),
            id,
            ..
        } => {
            ctx.state.pending_callback_id = Some(id.clone());
            ctx.callback_data = Some(data.clone());

            if data == "__form_cancel" {
                ctx.remove("__form_id");
                ctx.remove("__form_step");
                ctx.remove("__form_data");
                if let Some(ref on_cancel) = form.on_cancel {
                    return on_cancel(ctx).await;
                }
                return Ok(());
            }

            if data.starts_with("__form_confirm:") || data.starts_with("__form_choice:") {
                let value = data.split(':').nth(1).unwrap_or("").to_string();
                if step_idx < form.steps.len() {
                    let step = &form.steps[step_idx];
                    match step.parser.validate(&value, ctx.lang()) {
                        Ok(val) => {
                            form_data.insert(step.field.clone(), val);
                            ctx.set("__form_data", &form_data);
                            return advance_form_step(form, ctx, step_idx + 1, form_data).await;
                        }
                        Err(err) => {
                            let _ = ctx.toast(format!("{}", err)).await;
                            return Ok(());
                        }
                    }
                }
            }
        }

        UpdateKind::Message { text: Some(text) } => {
            if text.starts_with('/') {
                // /command cancels form — falls through to router which pushes mid.
                ctx.remove("__form_id");
                ctx.remove("__form_step");
                ctx.remove("__form_data");
                return Ok(());
            }
            // Non-command: we handle it, push mid ourselves.
            if let Some(mid) = update.message_id {
                ctx.state.pending_user_messages.push(mid);
            }
            if step_idx < form.steps.len() {
                let step = &form.steps[step_idx];
                match step.parser.validate(text, ctx.lang()) {
                    Ok(val) => {
                        form_data.insert(step.field.clone(), val);
                        ctx.set("__form_data", &form_data);
                        return advance_form_step(form, ctx, step_idx + 1, form_data).await;
                    }
                    Err(err) => {
                        if let Some(mid) = update.message_id {
                            let _ = ctx.delete_now(mid).await;
                            ctx.state.pending_user_messages.retain(|id| *id != mid);
                        }
                        let _ = ctx
                            .notify_temp(format!("{}", err), std::time::Duration::from_secs(3))
                            .await;
                        return Ok(());
                    }
                }
            }
        }

        UpdateKind::Photo { file_id, .. } => {
            if let Some(mid) = update.message_id {
                ctx.state.pending_user_messages.push(mid);
            }
            if step_idx < form.steps.len() {
                let step = &form.steps[step_idx];
                if matches!(step.parser, crate::form::FieldParser::Photo) {
                    form_data.insert(
                        step.field.clone(),
                        serde_json::Value::String(file_id.clone()),
                    );
                    ctx.set("__form_data", &form_data);
                    return advance_form_step(form, ctx, step_idx + 1, form_data).await;
                }
            }
        }

        _ => {}
    }
    Ok(())
}

async fn advance_form_step(
    form: &Form,
    ctx: &mut Ctx,
    next_step: usize,
    form_data: FormData,
) -> HandlerResult {
    if next_step >= form.steps.len() {
        ctx.remove("__form_id");
        ctx.remove("__form_step");
        ctx.remove("__form_data");
        // Call the completion handler with collected form data.
        return (form.on_complete)(ctx, form_data).await;
    }
    ctx.set("__form_step", &next_step);
    let lang = ctx.lang().to_string();
    let screen = (form.steps[next_step].screen_fn)(&form_data, &lang);
    ctx.navigate(screen).await
}

async fn run_conversation_step(
    conv: &Conversation,
    ctx: &mut Ctx,
    update: &IncomingUpdate,
) -> HandlerResult {
    use crate::conversation::ConversationData;

    let step_idx: usize = ctx.get("__conv_step").unwrap_or(0);
    let mut conv_data: ConversationData = ctx.get("__conv_data").unwrap_or_default();

    // NOTE: pending_user_messages push is handled by router.route() if we fall through
    // (i.e. /command cancels conversation). Push here only for messages we handle ourselves.

    match &update.kind {
        UpdateKind::CallbackQuery {
            data: Some(data),
            id,
            ..
        } => {
            ctx.state.pending_callback_id = Some(id.clone());
            ctx.callback_data = Some(data.clone());

            if data == "__conv_cancel" {
                ctx.remove("__conv_id");
                ctx.remove("__conv_step");
                ctx.remove("__conv_data");
                if let Some(ref on_cancel) = conv.on_cancel {
                    return on_cancel(ctx).await;
                }
                return Ok(());
            }

            // Treat callback data as input for current step
            if step_idx < conv.steps.len() {
                let step = &conv.steps[step_idx];
                if let Some(ref input_fn) = step.input_fn {
                    match input_fn(ctx, data, &conv_data).await {
                        Ok(Some(val)) => {
                            conv_data.insert(step.name.clone(), val);
                            ctx.set("__conv_data", &conv_data);
                            return advance_conversation_step(conv, ctx, step_idx, conv_data).await;
                        }
                        Ok(None) => return Ok(()), // retry
                        Err(msg) => {
                            let _ = ctx.toast(format!("{msg}")).await;
                            return Ok(());
                        }
                    }
                }
                // No custom input fn — store callback data as value
                conv_data.insert(step.name.clone(), serde_json::Value::String(data.clone()));
                ctx.set("__conv_data", &conv_data);
                return advance_conversation_step(conv, ctx, step_idx, conv_data).await;
            }
        }

        UpdateKind::Message { text: Some(text) } => {
            if text.starts_with('/') {
                // /command cancels conversation — falls through to router which pushes mid.
                ctx.remove("__conv_id");
                ctx.remove("__conv_step");
                ctx.remove("__conv_data");
                return Ok(());
            }
            // Non-command: we handle it, push mid ourselves.
            if let Some(mid) = update.message_id {
                ctx.state.pending_user_messages.push(mid);
            }
            if step_idx < conv.steps.len() {
                let step = &conv.steps[step_idx];
                if let Some(ref input_fn) = step.input_fn {
                    match input_fn(ctx, text, &conv_data).await {
                        Ok(Some(val)) => {
                            conv_data.insert(step.name.clone(), val);
                            ctx.set("__conv_data", &conv_data);
                            return advance_conversation_step(conv, ctx, step_idx, conv_data).await;
                        }
                        Ok(None) => return Ok(()),
                        Err(msg) => {
                            if let Some(mid) = update.message_id {
                                let _ = ctx.delete_now(mid).await;
                                ctx.state.pending_user_messages.retain(|id| *id != mid);
                            }
                            let _ = ctx
                                .notify_temp(format!("{msg}"), std::time::Duration::from_secs(3))
                                .await;
                            return Ok(());
                        }
                    }
                }
                // No custom input fn — store text as value
                conv_data.insert(step.name.clone(), serde_json::Value::String(text.clone()));
                ctx.set("__conv_data", &conv_data);
                return advance_conversation_step(conv, ctx, step_idx, conv_data).await;
            }
        }

        _ => {}
    }
    Ok(())
}

async fn advance_conversation_step(
    conv: &Conversation,
    ctx: &mut Ctx,
    current_step: usize,
    conv_data: crate::conversation::ConversationData,
) -> HandlerResult {
    match conv.next_step(current_step, &conv_data) {
        Some(next_idx) => {
            ctx.set("__conv_step", &next_idx);
            let lang = ctx.lang().to_string();
            let screen = (conv.steps[next_idx].screen_fn)(&conv_data, &lang);
            ctx.navigate(screen).await
        }
        None => {
            // Conversation complete
            ctx.remove("__conv_id");
            ctx.remove("__conv_step");
            ctx.remove("__conv_data");
            (conv.on_complete)(ctx, conv_data).await
        }
    }
}