inline-client 0.6.1

Stateful Rust client foundation for Inline.
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
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![forbid(unsafe_code)]

use std::{fmt, str::FromStr};

use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Backend/store boundary for client runtime operations.
pub mod backend;

/// Async client facade and runner.
pub mod runtime;

/// Realtime connector boundary.
pub mod realtime;

/// SDK-backed backend implementation.
pub mod sdk_backend;

/// Inline-native update discovery and bucket recovery policy.
pub mod sync;

/// Durable store boundary.
pub mod store;

/// Native Inline client request and record types.
pub mod types;

pub use backend::{
    BackendError, BackendResult, ClientBackend, InMemoryBackend, OperationOutcome, SendTextOutcome,
};
pub use inline_sdk::ClientIdentity;
pub use realtime::{
    FakeRealtimeAttempt, FakeRealtimeConnector, RealtimeConnectRequest, RealtimeConnectionInfo,
    RealtimeConnector, SdkRealtimeConnector,
};
pub use runtime::{
    ClientCommandError, ClientRequestError, ClientRunner, DEFAULT_COMMAND_QUEUE_CAPACITY,
    DEFAULT_EVENT_QUEUE_CAPACITY, DEFAULT_LOSSLESS_EVENT_QUEUE_CAPACITY,
    DEFAULT_MAX_CONCURRENT_REQUESTS, InlineClient, InlineClientBuilder, InlineClientRuntime,
    LosslessEventReceiver, ReconnectPolicy,
};
pub use sdk_backend::{SdkBackend, SdkBackendBuildError, SdkBackendBuilder};
pub use store::{
    AccountStateSnapshot, ChatStateSnapshot, ClientStore, InMemoryStore, PendingSyncBatch,
    SqliteStore, StoreError, StoreResult, StoredReaction, StoredReadState, StoredSession,
    StoredTransaction, SyncBucketKey, SyncBucketPeer, SyncBucketState, SyncState,
};
pub use sync::SyncConfig;
pub use types::{
    AddChatParticipantRequest, AuthContactKind, AuthCredential, AuthStartRequest, AuthStartResult,
    AuthToken, AuthVerifyRequest, AuthVerifyResult, ChatCreateParticipant, ChatParticipantRecord,
    ChatParticipantsPage, ChatParticipantsRequest, ClientStatusSnapshot, ConnectRequest,
    CreateDmRequest, CreateReplyThreadRequest, CreateThreadRequest, CreatedChat, DeleteChatRequest,
    DeleteMessageRequest, DialogFollowMode, DialogNotificationMode, DialogRecord, DialogsPage,
    DialogsRequest, EditMessageRequest, HistoryPage, HistoryRequest, MediaKind, MessageContent,
    MessageMutation, MessageRecord, NotificationMode, PeerRef, ReactRequest, ReadRequest,
    RemoveChatParticipantRequest, SendTextRequest, SetMarkedUnreadRequest, SpaceMemberRecord,
    SpaceMemberRole, SpaceRecord, TypingRequest, UpdateChatInfoRequest,
    UpdateDialogNotificationsRequest, UploadHandle, UploadRequest, UserRecord, UserSettingsRecord,
};

/// Published package version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Errors returned by public `inline-client` helper types.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientError {
    /// A required string field was empty or whitespace-only.
    #[error("{field} must not be empty")]
    EmptyField {
        /// Field name.
        field: &'static str,
    },

    /// A string field exceeded its public API limit.
    #[error("{field} is too long ({len} > {max})")]
    FieldTooLong {
        /// Field name.
        field: &'static str,
        /// Actual length in bytes.
        len: usize,
        /// Maximum allowed length in bytes.
        max: usize,
    },

    /// A string field contained ASCII control characters.
    #[error("{field} must not contain ASCII control characters")]
    ControlCharacter {
        /// Field name.
        field: &'static str,
    },
}

fn validate_token<'a>(
    field: &'static str,
    value: &'a str,
    max_len: usize,
) -> Result<&'a str, ClientError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(ClientError::EmptyField { field });
    }
    if trimmed.len() > max_len {
        return Err(ClientError::FieldTooLong {
            field,
            len: trimmed.len(),
            max: max_len,
        });
    }
    if trimmed.chars().any(|ch| ch.is_ascii_control()) {
        return Err(ClientError::ControlCharacter { field });
    }
    Ok(trimmed)
}

/// Opaque Inline ID used by high-level client events.
///
/// Inline server IDs are represented as signed 64-bit integers across existing
/// clients. This wrapper avoids mixing user, chat, and message IDs with other
/// integers in public event structures while keeping serialization simple.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct InlineId(i64);

impl InlineId {
    /// Creates an Inline ID from its raw wire value.
    pub const fn new(value: i64) -> Self {
        Self(value)
    }

    /// Returns the raw wire value.
    pub const fn get(self) -> i64 {
        self.0
    }
}

impl From<i64> for InlineId {
    fn from(value: i64) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for InlineId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Deterministic random ID attached to an Inline mutation.
///
/// Hosts should derive this from their own durable event or operation ID plus
/// message content so retries after restart remain idempotent.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RandomId(i64);

impl RandomId {
    /// Creates a random ID wrapper from a caller-provided deterministic value.
    pub const fn new(value: i64) -> Self {
        Self(value)
    }

    /// Returns the raw random ID.
    pub const fn get(self) -> i64 {
        self.0
    }
}

impl From<i64> for RandomId {
    fn from(value: i64) -> Self {
        Self::new(value)
    }
}

impl fmt::Display for RandomId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Opaque host-provided ID used for idempotency and echo reconciliation.
///
/// Hosts can use their own source namespaces, such as `host-event` or
/// `agent-task`. The core client treats this as metadata and does not depend on
/// host-specific semantics.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ExternalId {
    source: String,
    id: String,
}

impl ExternalId {
    /// Maximum source namespace length in bytes.
    pub const MAX_SOURCE_LEN: usize = 64;

    /// Maximum external ID length in bytes.
    pub const MAX_ID_LEN: usize = 512;

    /// Creates a validated external ID.
    pub fn try_new(source: impl AsRef<str>, id: impl AsRef<str>) -> Result<Self, ClientError> {
        let source = validate_token("source", source.as_ref(), Self::MAX_SOURCE_LEN)?;
        let id = validate_token("id", id.as_ref(), Self::MAX_ID_LEN)?;
        Ok(Self {
            source: source.to_owned(),
            id: id.to_owned(),
        })
    }

    /// Returns the source namespace.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns the source-local external ID.
    pub fn id(&self) -> &str {
        &self.id
    }
}

/// Stable client transaction ID.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TransactionId(String);

impl TransactionId {
    /// Maximum transaction ID length in bytes.
    pub const MAX_LEN: usize = 128;

    /// Creates a validated transaction ID.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, ClientError> {
        Ok(Self(
            validate_token("transaction_id", value.as_ref(), Self::MAX_LEN)?.to_owned(),
        ))
    }

    /// Returns the transaction ID string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for TransactionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for TransactionId {
    type Err = ClientError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::try_new(value)
    }
}

/// Identity data used to reconcile a mutation across host, client, and server.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionIdentity {
    /// Stable client transaction ID.
    pub transaction_id: TransactionId,
    /// Optional host-provided idempotency key.
    pub external_id: Option<ExternalId>,
    /// Inline mutation random ID.
    pub random_id: RandomId,
    /// Temporary local message ID, when the mutation created one.
    pub temporary_message_id: Option<InlineId>,
    /// Final server message ID, when known.
    pub final_message_id: Option<InlineId>,
}

impl TransactionIdentity {
    /// Creates a transaction identity before a temporary or final message ID is known.
    pub fn new(
        transaction_id: TransactionId,
        external_id: Option<ExternalId>,
        random_id: RandomId,
    ) -> Self {
        Self {
            transaction_id,
            external_id,
            random_id,
            temporary_message_id: None,
            final_message_id: None,
        }
    }

    /// Records the temporary message ID assigned by optimistic local state.
    pub fn with_temporary_message_id(mut self, message_id: impl Into<InlineId>) -> Self {
        self.temporary_message_id = Some(message_id.into());
        self
    }

    /// Records the final server message ID.
    pub fn with_final_message_id(mut self, message_id: impl Into<InlineId>) -> Self {
        self.final_message_id = Some(message_id.into());
        self
    }
}

/// High-level connection/auth state for apps, bridges, and agents.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ClientStatus {
    /// Client is not connected.
    Disconnected,
    /// Client is establishing a session.
    Connecting,
    /// Client is connected and able to send/receive realtime updates.
    Connected,
    /// Client lost realtime connectivity and is retrying.
    Reconnecting,
    /// Client needs interactive auth before it can connect.
    AuthRequired,
    /// Client credentials expired and a relogin or refresh is required.
    AuthExpired,
    /// The account was logged out or invalidated elsewhere.
    LoggedOut,
    /// The client is shutting down.
    ShuttingDown,
}

/// Stable error categories exposed to client hosts.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ClientErrorCategory {
    /// Caller supplied invalid input.
    InvalidInput,
    /// Authentication is missing.
    AuthRequired,
    /// Authentication expired and must be refreshed.
    AuthExpired,
    /// The user must relogin interactively.
    ReloginRequired,
    /// Network connectivity failed.
    Network,
    /// Operation timed out.
    Timeout,
    /// Remote server rate limited the operation.
    RateLimited,
    /// Local and remote protocol versions are incompatible.
    ProtocolMismatch,
    /// The target entity was not found.
    NotFound,
    /// The account does not have permission for the operation.
    PermissionDenied,
    /// The operation is unsupported by the current client or server.
    Unsupported,
    /// The operation conflicted with newer state.
    Conflict,
    /// An internal client error occurred.
    Internal,
}

/// Redacted failure value suitable for status endpoints and bridge errors.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientFailure {
    /// Machine-readable category.
    pub category: ClientErrorCategory,
    /// Human-readable message with secrets and message bodies redacted.
    pub message: String,
}

impl ClientFailure {
    /// Creates a redacted failure.
    pub fn new(category: ClientErrorCategory, message: impl Into<String>) -> Self {
        Self {
            category,
            message: message.into(),
        }
    }
}

/// State of a durable client transaction.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum TransactionState {
    /// Transaction is queued locally.
    Queued,
    /// Transaction was sent to the realtime or API transport.
    Sent,
    /// Transport acknowledged receipt, but final server result is not known.
    Acked,
    /// Server result completed and final state was applied.
    Completed,
    /// Transaction failed permanently or exhausted retries.
    Failed,
    /// Transaction was cancelled locally.
    Cancelled,
}

/// Transaction event emitted after client state changes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionEvent {
    /// Mutation identity and reconciliation IDs.
    pub identity: TransactionIdentity,
    /// Current transaction state.
    pub state: TransactionState,
    /// Redacted failure, present for failed transactions.
    pub failure: Option<ClientFailure>,
}

/// Reliability class for events delivered to hosts.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventReliability {
    /// Event must be delivered or recovered from durable state.
    Lossless,
    /// Event may be dropped under backpressure.
    BestEffort,
}

/// Committed client event for apps, bridges, agents, and hosts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ClientEvent {
    /// Connection/auth status changed.
    StatusChanged {
        /// New client status.
        status: ClientStatus,
        /// Optional redacted failure details.
        failure: Option<ClientFailure>,
    },
    /// A durable transaction changed state.
    TransactionChanged(TransactionEvent),
    /// A chat was inserted or updated in the local store.
    ChatUpserted {
        /// Inline chat ID.
        chat_id: InlineId,
    },
    /// A chat was deleted from durable client state.
    ChatDeleted {
        /// Inline chat ID.
        chat_id: InlineId,
    },
    /// The participant snapshot for a chat changed.
    ChatParticipantsChanged {
        /// Inline chat ID.
        chat_id: InlineId,
    },
    /// A user was inserted or updated in the local store.
    UserUpserted {
        /// Inline user ID.
        user_id: InlineId,
    },
    /// A space was inserted or updated in durable client state.
    SpaceUpserted {
        /// Inline space ID.
        space_id: InlineId,
    },
    /// Durable membership for a space changed.
    SpaceMemberChanged {
        /// Inline space ID.
        space_id: InlineId,
        /// Inline user ID.
        user_id: InlineId,
        /// Whether the member was removed.
        removed: bool,
    },
    /// Durable global user settings changed.
    UserSettingsChanged {},
    /// A bot message action was invoked and requires lossless host handling.
    MessageActionInvoked {
        /// Server interaction ID.
        interaction_id: InlineId,
        /// Chat containing the action.
        chat_id: InlineId,
        /// Message containing the action.
        message_id: InlineId,
        /// User who invoked the action.
        actor_user_id: InlineId,
        /// Bot-defined action ID.
        action_id: String,
        /// Opaque bot-defined payload.
        data: Vec<u8>,
    },
    /// A previously invoked message action received a UI response.
    MessageActionAnswered {
        /// Server interaction ID.
        interaction_id: InlineId,
        /// Optional toast text supplied by the bot.
        toast: Option<String>,
    },
    /// A message was inserted or updated in the local store.
    MessageUpserted {
        /// Inline chat ID.
        chat_id: InlineId,
        /// Inline message ID.
        message_id: InlineId,
    },
    /// A message was inserted or updated and the committed record is available.
    MessageStored {
        /// Committed message record.
        message: MessageRecord,
    },
    /// A message was deleted or unsent.
    MessageDeleted {
        /// Inline chat ID.
        chat_id: InlineId,
        /// Inline message ID.
        message_id: InlineId,
    },
    /// Stored history was cleared for a chat, optionally before a timestamp.
    ChatHistoryCleared {
        /// Inline chat ID.
        chat_id: InlineId,
        /// Unix timestamp cutoff; `None` means all history.
        before_date: Option<i64>,
    },
    /// Reactions for a message changed.
    ReactionChanged {
        /// Inline chat ID.
        chat_id: InlineId,
        /// Inline message ID.
        message_id: InlineId,
        /// Inline user ID that changed the reaction.
        user_id: InlineId,
        /// Reaction emoji.
        reaction: String,
        /// Whether the reaction was removed.
        removed: bool,
    },
    /// Read state changed for a chat.
    ReadStateChanged {
        /// Inline chat ID.
        chat_id: InlineId,
    },
    /// Typing state changed.
    Typing {
        /// Inline chat ID.
        chat_id: InlineId,
        /// Inline user ID.
        user_id: InlineId,
        /// Whether the user is typing.
        is_typing: bool,
    },
    /// Transient user presence changed.
    UserStatusChanged {
        /// Inline user ID.
        user_id: InlineId,
        /// `Some(true)` for online, `Some(false)` for offline, or `None` when hidden/unknown.
        is_online: Option<bool>,
        /// Last-online Unix timestamp, when disclosed.
        last_online: Option<i64>,
    },
    /// Transient bot activity/presence changed for a peer.
    BotPresenceChanged {
        /// Inline bot user ID.
        bot_user_id: InlineId,
        /// Resolved chat ID, when available.
        chat_id: Option<InlineId>,
        /// Stable protobuf presence kind name.
        kind: String,
        /// Optional bot-supplied status comment.
        comment: Option<String>,
        /// Whether the bot avatar changed.
        avatar_changed: bool,
    },
    /// A notification-class message update was received.
    NewMessageNotification {
        /// Message referenced by the notification.
        message: MessageRecord,
        /// Stable protobuf notification reason name.
        reason: String,
    },
}

impl ClientEvent {
    /// Returns the event delivery reliability class.
    pub const fn reliability(&self) -> EventReliability {
        match self {
            Self::Typing { .. }
            | Self::UserStatusChanged { .. }
            | Self::BotPresenceChanged { .. }
            | Self::NewMessageNotification { .. } => EventReliability::BestEffort,
            Self::StatusChanged { .. }
            | Self::TransactionChanged(_)
            | Self::ChatUpserted { .. }
            | Self::ChatDeleted { .. }
            | Self::ChatParticipantsChanged { .. }
            | Self::UserUpserted { .. }
            | Self::SpaceUpserted { .. }
            | Self::SpaceMemberChanged { .. }
            | Self::UserSettingsChanged { .. }
            | Self::MessageActionInvoked { .. }
            | Self::MessageActionAnswered { .. }
            | Self::MessageUpserted { .. }
            | Self::MessageStored { .. }
            | Self::MessageDeleted { .. }
            | Self::ChatHistoryCleared { .. }
            | Self::ReactionChanged { .. }
            | Self::ReadStateChanged { .. } => EventReliability::Lossless,
        }
    }
}

/// Convenient imports for common client consumers.
pub mod prelude {
    pub use crate::{
        AddChatParticipantRequest, AuthCredential, AuthToken, BackendError, BackendResult,
        ClientBackend, ClientCommandError, ClientError, ClientErrorCategory, ClientEvent,
        ClientFailure, ClientIdentity, ClientRequestError, ClientRunner, ClientStatus, ClientStore,
        ConnectRequest, DEFAULT_COMMAND_QUEUE_CAPACITY, DEFAULT_EVENT_QUEUE_CAPACITY,
        DEFAULT_LOSSLESS_EVENT_QUEUE_CAPACITY, DeleteChatRequest, DeleteMessageRequest,
        DialogFollowMode, DialogNotificationMode, DialogRecord, DialogsPage, DialogsRequest,
        EditMessageRequest, EventReliability, ExternalId, FakeRealtimeAttempt,
        FakeRealtimeConnector, HistoryPage, HistoryRequest, InMemoryBackend, InMemoryStore,
        InlineClient, InlineClientBuilder, InlineClientRuntime, InlineId, LosslessEventReceiver,
        MessageContent, MessageMutation, MessageRecord, NotificationMode, PeerRef, RandomId,
        ReactRequest, ReadRequest, RealtimeConnectRequest, RealtimeConnectionInfo,
        RealtimeConnector, ReconnectPolicy, RemoveChatParticipantRequest, SdkBackend,
        SdkBackendBuildError, SdkBackendBuilder, SdkRealtimeConnector, SendTextOutcome,
        SendTextRequest, SetMarkedUnreadRequest, SpaceMemberRecord, SpaceMemberRole, SpaceRecord,
        SqliteStore, StoreError, StoreResult, StoredReaction, StoredReadState, StoredSession,
        StoredTransaction, SyncBucketKey, SyncBucketPeer, SyncBucketState, SyncConfig, SyncState,
        TransactionEvent, TransactionId, TransactionIdentity, TransactionState, TypingRequest,
        UpdateChatInfoRequest, UpdateDialogNotificationsRequest, UploadHandle, UploadRequest,
        UserSettingsRecord, VERSION,
    };
}

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

    #[test]
    fn external_id_rejects_empty_values() {
        assert_eq!(
            ExternalId::try_new("host-event", " "),
            Err(ClientError::EmptyField { field: "id" })
        );
    }

    #[test]
    fn transaction_identity_records_message_ids() {
        let identity = TransactionIdentity::new(
            TransactionId::try_new("txn-1").unwrap(),
            Some(ExternalId::try_new("host-event", "event-1").unwrap()),
            RandomId::new(42),
        )
        .with_temporary_message_id(-1)
        .with_final_message_id(100);

        assert_eq!(identity.random_id.get(), 42);
        assert_eq!(identity.temporary_message_id.unwrap().get(), -1);
        assert_eq!(identity.final_message_id.unwrap().get(), 100);
    }

    #[test]
    fn typing_is_best_effort() {
        let event = ClientEvent::Typing {
            chat_id: InlineId::new(1),
            user_id: InlineId::new(2),
            is_typing: true,
        };

        assert_eq!(event.reliability(), EventReliability::BestEffort);
    }
}