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
//! Branching conversation system — multi-step dialogues with conditional flow.
//!
//! Conversations are a superset of [`Form`](crate::form::Form): they support
//! branching, unconditional jumps, and custom input handlers per step.
//!
//! ```rust,ignore
//! let conv = Conversation::builder("onboarding")
//!     .step("name", |_data, lang| {
//!         Screen::text("conv_name", "What's your name?").build()
//!     }, None)
//!     .step("role", |_data, lang| {
//!         Screen::text("conv_role", "Are you a student or teacher?").build()
//!     }, None)
//!     .branch("role", Arc::new(|data| {
//!         match data.get("role").and_then(|v| v.as_str()) {
//!             Some("student") => "student_year".to_string(),
//!             _ => "done".to_string(),
//!         }
//!     }))
//!     .step("student_year", |_data, lang| {
//!         Screen::text("conv_year", "What year are you in?").build()
//!     }, None)
//!     .step("done", |data, _lang| {
//!         Screen::text("conv_done", "All set!").build()
//!     }, None)
//!     .on_complete(Arc::new(|ctx, data| Box::pin(async move {
//!         ctx.navigate(Screen::text("home", "Welcome!").build()).await
//!     })))
//!     .build()
//!     .unwrap();
//! ```

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

use crate::ctx::Ctx;
use crate::error::HandlerResult;
use crate::screen::Screen;

/// Collected conversation data (same type as FormData).
pub type ConversationData = HashMap<String, serde_json::Value>;

/// A screen-producing function for a conversation step.
pub type StepScreenFn = Arc<dyn Fn(&ConversationData, &str) -> Screen + Send + Sync>;

/// Handler that processes user input for a step and returns the field value, or `None` to retry.
pub type StepInputFn = Arc<
    dyn for<'a> Fn(
            &'a mut Ctx,
            &'a str,
            &'a ConversationData,
        ) -> Pin<
            Box<dyn Future<Output = Result<Option<serde_json::Value>, String>> + Send + 'a>,
        > + Send
        + Sync,
>;

/// Branch function — given collected data, returns the next step name.
pub type BranchFn = Arc<dyn Fn(&ConversationData) -> String + Send + Sync>;

/// Handler called when conversation completes.
pub type ConversationCompleteHandler = Arc<
    dyn Fn(&mut Ctx, ConversationData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync,
>;

/// Handler called when conversation is cancelled.
pub type ConversationCancelHandler =
    Arc<dyn Fn(&mut Ctx) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> + Send + Sync>;

/// A single step in a conversation.
pub struct ConversationStep {
    pub(crate) name: String,
    pub(crate) screen_fn: StepScreenFn,
    pub(crate) input_fn: Option<StepInputFn>,
    pub(crate) next: StepNext,
}

/// How to determine the next step after this one completes.
pub(crate) enum StepNext {
    /// Go to the next step in insertion order.
    Sequential,
    /// Evaluate a branch function to decide.
    Branch(BranchFn),
    /// Go to a specific named step.
    Goto(String),
    /// This is the final step — complete the conversation.
    End,
}

/// A branching multi-step conversation.
pub struct Conversation {
    /// Conversation identifier (used in ctx state as `__conv_id`).
    pub(crate) id: String,
    /// Steps in order.
    pub(crate) steps: Vec<ConversationStep>,
    /// Step name → index mapping.
    pub(crate) step_index: HashMap<String, usize>,
    /// Called when the conversation reaches the end.
    pub(crate) on_complete: ConversationCompleteHandler,
    /// Called when the user cancels.
    pub(crate) on_cancel: Option<ConversationCancelHandler>,
}

/// Builder for constructing a [`Conversation`].
pub struct ConversationBuilder {
    id: String,
    steps: Vec<ConversationStep>,
    step_index: HashMap<String, usize>,
    on_complete: Option<ConversationCompleteHandler>,
    on_cancel: Option<ConversationCancelHandler>,
    /// Pending branch/goto overrides: step_name → StepNext
    overrides: HashMap<String, StepNext>,
}

impl Conversation {
    /// Create a new conversation builder with the given ID.
    pub fn builder(id: impl Into<String>) -> ConversationBuilder {
        ConversationBuilder {
            id: id.into(),
            steps: Vec::new(),
            step_index: HashMap::new(),
            on_complete: None,
            on_cancel: None,
            overrides: HashMap::new(),
        }
    }
}

impl ConversationBuilder {
    /// Add a step to the conversation.
    ///
    /// - `name`: unique step identifier
    /// - `screen_fn`: produces the screen shown at this step
    /// - `input_fn`: optional custom input handler. If `None`, raw text is stored as-is.
    pub fn step(
        mut self,
        name: &str,
        screen_fn: impl Fn(&ConversationData, &str) -> Screen + Send + Sync + 'static,
        input_fn: Option<StepInputFn>,
    ) -> Self {
        if self.step_index.contains_key(name) {
            panic!("duplicate conversation step name: '{}'", name);
        }
        let idx = self.steps.len();
        self.step_index.insert(name.to_string(), idx);
        self.steps.push(ConversationStep {
            name: name.to_string(),
            screen_fn: Arc::new(screen_fn),
            input_fn,
            next: StepNext::Sequential,
        });
        self
    }

    /// After step `step_name` completes, evaluate `branch_fn` to decide the next step.
    pub fn branch(mut self, step_name: &str, branch_fn: BranchFn) -> Self {
        self.overrides
            .insert(step_name.to_string(), StepNext::Branch(branch_fn));
        self
    }

    /// After step `step_name` completes, unconditionally jump to `target`.
    pub fn goto(mut self, step_name: &str, target: &str) -> Self {
        self.overrides
            .insert(step_name.to_string(), StepNext::Goto(target.to_string()));
        self
    }

    /// Mark a step as the final step (completes the conversation after it).
    pub fn end_at(mut self, step_name: &str) -> Self {
        self.overrides.insert(step_name.to_string(), StepNext::End);
        self
    }

    /// Set the completion handler.
    pub fn on_complete(mut self, handler: ConversationCompleteHandler) -> Self {
        self.on_complete = Some(handler);
        self
    }

    /// Set the cancel handler.
    pub fn on_cancel(mut self, handler: ConversationCancelHandler) -> Self {
        self.on_cancel = Some(handler);
        self
    }

    /// Build the conversation. Returns an error if no steps or no on_complete handler.
    pub fn build(mut self) -> Result<Conversation, &'static str> {
        if self.steps.is_empty() {
            return Err("conversation must have at least one step");
        }
        if self.on_complete.is_none() {
            return Err("conversation must have an on_complete handler");
        }

        // Apply overrides
        for (name, next) in self.overrides {
            if let Some(&idx) = self.step_index.get(&name) {
                self.steps[idx].next = next;
            } else {
                return Err("branch/goto/end_at references unknown step");
            }
        }

        Ok(Conversation {
            id: self.id,
            steps: self.steps,
            step_index: self.step_index,
            on_complete: self.on_complete.expect("checked above"),
            on_cancel: self.on_cancel,
        })
    }
}

impl Conversation {
    /// Resolve the next step index from the current step.
    pub(crate) fn next_step(&self, current_idx: usize, data: &ConversationData) -> Option<usize> {
        let step = &self.steps[current_idx];
        match &step.next {
            StepNext::Sequential => {
                let next = current_idx + 1;
                if next < self.steps.len() {
                    Some(next)
                } else {
                    None // end of conversation
                }
            }
            StepNext::Branch(f) => {
                let target = f(data);
                let idx = self.step_index.get(&target).copied();
                if idx.is_none() {
                    tracing::warn!(
                        conv_id = %self.id,
                        step = %step.name,
                        target = %target,
                        "branch returned unknown step name — ending conversation"
                    );
                }
                idx
            }
            StepNext::Goto(target) => self.step_index.get(target).copied(),
            StepNext::End => None,
        }
    }
}

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

    #[test]
    fn build_conversation_basic() {
        let conv = Conversation::builder("test")
            .step(
                "name",
                |_data, _lang| Screen::text("s1", "Name?").build(),
                None,
            )
            .step(
                "age",
                |_data, _lang| Screen::text("s2", "Age?").build(),
                None,
            )
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async move { Ok(()) })))
            .build()
            .unwrap();

        assert_eq!(conv.id, "test");
        assert_eq!(conv.steps.len(), 2);
        assert_eq!(conv.step_index["name"], 0);
        assert_eq!(conv.step_index["age"], 1);
    }

    #[test]
    fn build_conversation_no_steps_fails() {
        let result = Conversation::builder("empty")
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn build_conversation_no_on_complete_fails() {
        let result = Conversation::builder("no_complete")
            .step("s1", |_data, _lang| Screen::text("s1", "?").build(), None)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn next_step_sequential() {
        let conv = Conversation::builder("seq")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .step("b", |_data, _lang| Screen::text("b", "B").build(), None)
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build()
            .unwrap();

        assert_eq!(conv.next_step(0, &HashMap::new()), Some(1));
        assert_eq!(conv.next_step(1, &HashMap::new()), None);
    }

    #[test]
    fn next_step_branch() {
        let conv = Conversation::builder("br")
            .step("q", |_data, _lang| Screen::text("q", "?").build(), None)
            .step(
                "yes",
                |_data, _lang| Screen::text("yes", "Yes").build(),
                None,
            )
            .step("no", |_data, _lang| Screen::text("no", "No").build(), None)
            .branch(
                "q",
                Arc::new(|data| {
                    if data.get("q").and_then(|v| v.as_str()).unwrap_or("") == "yes" {
                        "yes".to_string()
                    } else {
                        "no".to_string()
                    }
                }),
            )
            .end_at("yes")
            .end_at("no")
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build()
            .unwrap();

        let mut data = HashMap::new();
        data.insert("q".into(), serde_json::json!("yes"));
        assert_eq!(conv.next_step(0, &data), Some(1));

        data.insert("q".into(), serde_json::json!("no"));
        assert_eq!(conv.next_step(0, &data), Some(2));

        // end_at: should return None
        assert_eq!(conv.next_step(1, &data), None);
        assert_eq!(conv.next_step(2, &data), None);
    }

    #[test]
    fn next_step_goto() {
        let conv = Conversation::builder("gt")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .step("b", |_data, _lang| Screen::text("b", "B").build(), None)
            .step("c", |_data, _lang| Screen::text("c", "C").build(), None)
            .goto("a", "c")
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build()
            .unwrap();

        assert_eq!(conv.next_step(0, &HashMap::new()), Some(2)); // a → c (skip b)
    }

    #[test]
    fn conversation_with_cancel() {
        let conv = Conversation::builder("cancel")
            .step("s1", |_data, _lang| Screen::text("s1", "?").build(), None)
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .on_cancel(Arc::new(|_ctx| Box::pin(async { Ok(()) })))
            .build()
            .unwrap();

        assert!(conv.on_cancel.is_some());
    }

    #[test]
    fn build_fails_on_unknown_branch_target() {
        let result = Conversation::builder("bad")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .branch("nonexistent", Arc::new(|_| "a".into()))
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn build_fails_on_unknown_goto_target() {
        let result = Conversation::builder("bad")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .goto("typo", "a")
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn build_fails_on_unknown_end_at_target() {
        let result = Conversation::builder("bad")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .end_at("nope")
            .on_complete(Arc::new(|_ctx, _data| Box::pin(async { Ok(()) })))
            .build();
        assert!(result.is_err());
    }

    #[test]
    #[should_panic(expected = "duplicate conversation step name: 'a'")]
    fn duplicate_step_name_panics() {
        Conversation::builder("dup")
            .step("a", |_data, _lang| Screen::text("a", "A").build(), None)
            .step("a", |_data, _lang| Screen::text("a2", "A2").build(), None);
    }
}