Skip to main content

layer_mtproto/
session.rs

1//! MTProto client session state.
2
3use layer_tl_types::RemoteCall;
4
5use crate::message::{Message, MessageId};
6
7/// Tracks per-connection MTProto session state.
8///
9/// A `Session` is cheap to create and can be reset on reconnect.
10///
11/// # Example
12///
13/// ```rust
14/// use layer_mtproto::Session;
15/// use layer_tl_types::functions;
16///
17/// let mut session = Session::new();
18/// // let msg = session.pack(&my_request);
19/// // send(msg.to_plaintext_bytes()).await?;
20/// ```
21pub struct Session {
22    /// Monotonically increasing counter used to generate unique message IDs.
23    msg_counter: u32,
24    /// The sequence number for the next message.
25    /// Even for content-unrelated messages, odd for content-related (RPC calls).
26    seq_no: i32,
27}
28
29impl Session {
30    /// Create a fresh session.
31    pub fn new() -> Self {
32        Self { msg_counter: 0, seq_no: 0 }
33    }
34
35    /// Allocate a new message ID.
36    pub fn next_msg_id(&mut self) -> MessageId {
37        self.msg_counter = self.msg_counter.wrapping_add(1);
38        MessageId::generate(self.msg_counter)
39    }
40
41    /// Return the next sequence number for a content-related message (RPC call).
42    ///
43    /// Increments by 2 after each call so that even slots remain available
44    /// for content-unrelated messages (acks, pings, etc.).
45    pub fn next_seq_no(&mut self) -> i32 {
46        let n = self.seq_no;
47        self.seq_no += 2;
48        n | 1  // odd = content-related
49    }
50
51    /// Return the next sequence number for a content-*un*related message.
52    pub fn next_seq_no_unrelated(&mut self) -> i32 {
53        let n = self.seq_no;
54        n & !1  // even = content-unrelated (don't increment)
55    }
56
57    /// Serialize an RPC function into a [`Message`] ready to send.
58    ///
59    /// The message body is just the TL-serialized `call`; the surrounding
60    /// transport framing (auth_key_id, etc.) is applied in [`Message::to_plaintext_bytes`].
61    pub fn pack<R: RemoteCall>(&mut self, call: &R) -> Message {
62        let id     = self.next_msg_id();
63        let seq_no = self.next_seq_no();
64        let body   = call.to_bytes();
65        Message::plaintext(id, seq_no, body)
66    }
67}
68
69impl Default for Session {
70    fn default() -> Self { Self::new() }
71}