eq-network 0.1.2

Native EverQuest login, world, and zone client
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
//! Blocking, cancellable session engine for native applications and the CLI.
//!
//! The host supplies credentials and validation metadata, starts a worker, and
//! consumes events on its UI thread. It owns credential persistence and logs.
//! This example stops on a full or closed queue rather than dropping records.
//!
//! ```no_run
//! use eq_network::{chat::OutboundChat, client::{CancellationToken,
//!     Client, ClientCommand, ClientConfig, ClientIdentity, RunOptions}};
//! use std::{sync::mpsc, thread};
//!
//! # fn example() -> anyhow::Result<()> {
//! let config = ClientConfig::new("EXAMPLE_ACCOUNT", "EXAMPLE_PASSWORD",
//!     "Project 1999: Green (Velious, PvE)", "ExampleCharacter");
//! // Supply short metadata chosen by the host app (1 to 15 bytes per field).
//! let identity = ClientIdentity::new("example-device", "example-user");
//! let client = Client::new(config, identity)?;
//! let cancel = CancellationToken::default();
//! let worker_cancel = cancel.clone();
//! let (events, receiver) = mpsc::sync_channel(512);
//! let (commands, command_queue) = mpsc::sync_channel(32);
//! let worker = thread::spawn(move || {
//!     client.run_with_commands(&worker_cancel, RunOptions::default(), &command_queue, |event| {
//!         events.try_send(event).map_err(|_| anyhow::anyhow!("UI event queue unavailable"))
//!     })
//! });
//! // After observing ConnectionStage::Ready, this is equivalent to `/say ok`.
//! commands.try_send(ClientCommand::SendChat(OutboundChat::Say("ok".into())))?;
//! // During the UI event loop, drain receiver.try_iter() and render the events.
//! // On Disconnect or app shutdown, cancel and await worker completion.
//! cancel.cancel();
//! worker.join().expect("session worker panicked")?;
//! # drop(receiver);
//! # Ok(())
//! # }
//! ```

mod quarm;
mod session;

use crate::{
    assets::Assets,
    chat::{ChannelName, ChatEvent},
};
use anyhow::{ensure, Context, Result};
use eq_network_game::GameDialect;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    fmt,
    str::FromStr,
    sync::{
        atomic::{AtomicBool, Ordering},
        mpsc::Receiver,
        Arc,
    },
    time::{Duration, Instant},
};
use zeroize::Zeroizing;

/// Typed work submitted by the host while a character is connected.
pub use eq_network_game::command::GameCommand as ClientCommand;

/// Wire protocol and client family used by a server.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ServerProtocol {
    /// Project 1999's Titanium/P99-V62 protocol.
    #[default]
    #[serde(alias = "p99", alias = "project_1999")]
    Project1999,
    /// Project Quarm's Windows TAKP/EQMac protocol.
    Quarm,
}

impl ServerProtocol {
    /// Return the public login endpoint normally used by this protocol.
    #[must_use]
    pub const fn default_endpoint(self) -> (&'static str, u16) {
        match self {
            Self::Project1999 => ("login.eqemulator.net", 5998),
            Self::Quarm => ("loginserver.takproject.net", 6000),
        }
    }
}

impl From<ServerProtocol> for GameDialect {
    fn from(protocol: ServerProtocol) -> Self {
        match protocol {
            ServerProtocol::Project1999 => Self::TitaniumP99,
            ServerProtocol::Quarm => Self::EqMac,
        }
    }
}

impl FromStr for ServerProtocol {
    type Err = anyhow::Error;

    fn from_str(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "p99" | "project1999" | "project_1999" => Ok(Self::Project1999),
            "quarm" => Ok(Self::Quarm),
            _ => anyhow::bail!("unknown server protocol {value:?}"),
        }
    }
}

/// Login secrets retained only for the lifetime of a client configuration.
#[derive(Clone)]
pub struct Credentials {
    account: Zeroizing<String>,
    password: Zeroizing<String>,
}

impl Credentials {
    /// Store an account name and password with zeroization on drop.
    pub fn new(account: impl Into<String>, password: impl Into<String>) -> Self {
        Self {
            account: Zeroizing::new(account.into()),
            password: Zeroizing::new(password.into()),
        }
    }

    /// Return the account name for packet encoding.
    #[must_use]
    pub fn account(&self) -> &str {
        self.account.as_str()
    }

    fn password(&self) -> &str {
        self.password.as_str()
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Credentials")
            .field("account", &"[REDACTED]")
            .field("password", &"[REDACTED]")
            .finish()
    }
}

/// Connection and logging preferences.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ClientConfig {
    /// Server family and protocol generation.
    pub protocol: ServerProtocol,
    /// Login server hostname or address.
    pub host: String,
    /// Login server UDP port.
    pub port: u16,
    /// Login credentials, redacted from diagnostics and zeroized on drop.
    pub credentials: Credentials,
    /// World-server display name selected after login.
    pub server: String,
    /// Character selected on the world server.
    pub character: String,
    /// Whether decoded records retain raw packet representations.
    pub include_raw: bool,
    /// None logs every channel; an empty set logs no decoded chat.
    pub channels: Option<HashSet<ChannelName>>,
    /// Delay before starting a fresh session after a recoverable failure.
    pub reconnect_delay: Duration,
}

impl ClientConfig {
    /// Configure a character with the default login endpoint and all chat channels.
    pub fn new(
        user: impl Into<String>,
        pass: impl Into<String>,
        server: impl Into<String>,
        character: impl Into<String>,
    ) -> Self {
        Self::for_protocol(ServerProtocol::Project1999, user, pass, server, character)
    }

    /// Configure a character with a protocol's normal login endpoint.
    pub fn for_protocol(
        protocol: ServerProtocol,
        user: impl Into<String>,
        pass: impl Into<String>,
        server: impl Into<String>,
        character: impl Into<String>,
    ) -> Self {
        let (host, port) = protocol.default_endpoint();
        Self {
            protocol,
            host: host.into(),
            port,
            credentials: Credentials::new(user, pass),
            server: server.into(),
            character: character.into(),
            include_raw: false,
            channels: None,
            reconnect_delay: Duration::from_secs(30),
        }
    }

    fn validate(&self) -> Result<()> {
        for value in [&self.host, &self.server, &self.character] {
            ensure!(
                !value.is_empty() && !value.contains('\0'),
                "required connection fields must be nonempty and contain no NUL"
            );
        }
        for value in [self.credentials.account(), self.credentials.password()] {
            ensure!(
                !value.is_empty() && !value.contains('\0'),
                "required credentials must be nonempty and contain no NUL"
            );
        }
        ensure!(self.port != 0, "login port must be nonzero");
        if self.protocol == ServerProtocol::Quarm {
            ensure!(
                self.credentials.account().len() < 20 && self.credentials.password().len() < 20,
                "Quarm login fields must fit in 19 bytes"
            );
        }
        ensure!(
            self.character.len() < 64,
            "character name exceeds protocol field size"
        );
        ensure!(
            self.reconnect_delay >= Duration::from_secs(10),
            "reconnect delay must be at least 10 seconds"
        );
        Ok(())
    }

    /// Return whether a decoded communication should be delivered to the caller.
    #[must_use]
    pub fn logs(&self, event: &ChatEvent) -> bool {
        self.channels
            .as_ref()
            .is_none_or(|channels| channels.contains(&event.channel_name))
    }
}

/// Host-provided metadata for the V62 validation packet. Each field must fit
/// within 15 UTF-8 bytes; the engine uppercases hostname before checking its size.
#[derive(Clone)]
#[non_exhaustive]
pub struct ClientIdentity {
    /// Short device hostname announced during P99 validation.
    pub hostname: String,
    /// Short operating-system username announced during P99 validation.
    pub username: String,
}

impl ClientIdentity {
    /// Construct host metadata for the P99 validation packet.
    pub fn new(hostname: impl Into<String>, username: impl Into<String>) -> Self {
        Self {
            hostname: hostname.into(),
            username: username.into(),
        }
    }
}

/// Cooperative shutdown, shared between the session worker and its owner.
#[derive(Clone, Debug, Default)]
pub struct CancellationToken(Arc<AtomicBool>);

impl CancellationToken {
    /// Request shutdown. A cancelled token remains cancelled; use a new one to reconnect.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Relaxed);
    }

    #[must_use]
    /// Return whether cooperative shutdown has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Relaxed)
    }

    fn flag(&self) -> &AtomicBool {
        &self.0
    }
}

impl From<Arc<AtomicBool>> for CancellationToken {
    /// Adopt an existing shutdown flag, for example one registered with a signal handler.
    fn from(flag: Arc<AtomicBool>) -> Self {
        Self(flag)
    }
}

/// A confirmed login rejection that cannot be resolved by reconnecting.
/// Hosts can downcast the error returned by `Client::run` to present a specific message.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LoginError {
    /// The login server rejected the account/password pair.
    InvalidCredentials,
}

impl fmt::Display for LoginError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidCredentials => f.write_str("Login account or password was rejected"),
        }
    }
}

impl std::error::Error for LoginError {}

/// Limits for one run; transient failures reconnect until cancellation by default.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct RunOptions {
    /// Reconnect after transient session failures.
    pub reconnect: bool,
    /// Stop after character selection without opening the zone connection.
    pub world_only: bool,
    /// Optional maximum time in the zone, including zone admission.
    pub zone_duration: Option<Duration>,
}

impl Default for RunOptions {
    fn default() -> Self {
        Self {
            reconnect: true,
            world_only: false,
            zone_duration: None,
        }
    }
}

/// Coarse connection state for health checks and user interfaces.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ConnectionState {
    /// A fresh login attempt is in progress.
    Connecting,
    /// The character is active in a zone.
    Connected,
    /// A zone handoff is in progress.
    Zoning,
    /// The current network session ended.
    Disconnected,
    /// The client stopped after cancellation or a non-reconnecting run.
    Stopped,
}

/// Periodic session state suitable for a UI status indicator or health adapter.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct SessionStatus {
    /// Current coarse connection state.
    pub state: ConnectionState,
    /// Unix timestamp when the status was emitted.
    pub timestamp: i64,
    /// Unique identifier for the current process-level session.
    pub session_id: String,
    /// Current short zone name, if known.
    pub zone: String,
    /// Number of communication records received in this attempt.
    pub messages: u64,
    /// Number of application packets received in this attempt.
    pub packets: u64,
    /// Seconds since the last valid server datagram, if a session is active.
    pub last_received_seconds: Option<u64>,
}

impl SessionStatus {
    /// Create an empty status snapshot for a connection state and session.
    #[must_use]
    pub fn new(state: ConnectionState, session_id: impl Into<String>) -> Self {
        Self {
            state,
            timestamp: chrono::Utc::now().timestamp(),
            session_id: session_id.into(),
            zone: String::new(),
            messages: 0,
            packets: 0,
            last_received_seconds: None,
        }
    }

    /// Replace the timestamp, primarily for imported or synthetic events.
    #[must_use]
    pub const fn with_timestamp(mut self, timestamp: i64) -> Self {
        self.timestamp = timestamp;
        self
    }

    /// Attach the current short zone name.
    #[must_use]
    pub fn with_zone(mut self, zone: impl Into<String>) -> Self {
        self.zone = zone.into();
        self
    }

    /// Attach current communication and application-packet counters.
    #[must_use]
    pub const fn with_counters(mut self, messages: u64, packets: u64) -> Self {
        self.messages = messages;
        self.packets = packets;
        self
    }

    /// Attach whole seconds since the last valid server datagram.
    #[must_use]
    pub const fn with_last_received(mut self, seconds: Option<u64>) -> Self {
        self.last_received_seconds = seconds;
        self
    }
}

/// A recognized communication opcode whose body could not be decoded.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct DecodeError {
    #[serde(rename = "type")]
    kind: &'static str,
    /// Raw application opcode.
    pub opcode: u16,
    /// Hex-encoded packet body retained for diagnosis.
    pub payload_hex: String,
    /// Decoder error without credentials or packet secrets.
    pub error: String,
}

impl DecodeError {
    /// Create a structured failure for one recognized communication packet.
    #[must_use]
    pub fn new(opcode: u16, payload_hex: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            kind: "decode_error",
            opcode,
            payload_hex: payload_hex.into(),
            error: error.into(),
        }
    }
}

/// Preserves the existing flat `chat/decode_error` JSON representation.
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum RecordEvent {
    /// Successfully decoded communication.
    Chat(ChatEvent),
    /// Communication packet that failed validation or decoding.
    DecodeError(DecodeError),
}

/// An owned communication record that can cross a thread or UI boundary.
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct Record {
    /// RFC 3339 receive timestamp.
    pub timestamp: String,
    /// Selected world-server display name.
    pub server: String,
    /// Logged-in character name.
    pub character: String,
    /// Current short zone name.
    pub zone: String,
    /// Process-level session identifier.
    pub session_id: String,
    /// Monotonic record number within the session.
    pub message_id: u64,
    /// Decoded communication or decode failure.
    #[serde(flatten)]
    pub event: RecordEvent,
}

impl Record {
    /// Create a communication record with the current UTC receive time.
    #[must_use]
    pub fn new(
        server: impl Into<String>,
        character: impl Into<String>,
        zone: impl Into<String>,
        session_id: impl Into<String>,
        message_id: u64,
        event: RecordEvent,
    ) -> Self {
        Self {
            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
            server: server.into(),
            character: character.into(),
            zone: zone.into(),
            session_id: session_id.into(),
            message_id,
            event,
        }
    }

    /// Replace the receive timestamp, primarily for imported or synthetic records.
    #[must_use]
    pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
        self.timestamp = timestamp.into();
        self
    }
}

/// Ordered connection milestones, from the start of an attempt to zone admission.
/// These describe completed protocol work, not elapsed time or packet counts.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ConnectionStage {
    /// Opening the login-server transport.
    ConnectingLogin,
    /// Sending credentials and waiting for authentication.
    Authenticating,
    /// Requesting and selecting the configured world.
    SelectingServer,
    /// Opening and authenticating the world-server transport.
    ConnectingWorld,
    /// Requesting and selecting the configured character.
    SelectingCharacter,
    /// Opening the assigned zone-server transport.
    ConnectingZone,
    /// Receiving character and zone initialization data.
    LoadingCharacter,
    /// Completing final zone admission acknowledgements.
    EnteringWorld,
    /// Character is active and chat commands can be sent.
    Ready,
}

/// Owned output produced by the native session engine.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ClientEvent {
    /// Periodic health and connection status.
    Status(SessionStatus),
    /// Completed connection milestone.
    Progress(ConnectionStage),
    /// Decoded communication record.
    Record(Box<Record>),
    /// Credential-safe operational diagnostic.
    Diagnostic(String),
    /// Transient failure followed by a scheduled fresh session.
    Reconnecting {
        /// Credential-safe failure text.
        error: String,
        /// Delay before the next attempt.
        delay_seconds: u64,
    },
}

/// A reusable native client. The caller owns the worker thread and event storage.
pub struct Client {
    config: ClientConfig,
    identity: ClientIdentity,
    assets: Assets,
}

impl Client {
    /// Validate settings and use the checksum inventory bundled with the crate.
    ///
    /// # Errors
    ///
    /// Returns an error when configuration, identity metadata, or the bundled
    /// asset inventory is invalid.
    pub fn new(config: ClientConfig, mut identity: ClientIdentity) -> Result<Self> {
        config.validate()?;
        identity.hostname = identity.hostname.to_uppercase();
        for value in [&identity.hostname, &identity.username] {
            ensure!(
                !value.is_empty() && value.len() < 16 && !value.contains('\0'),
                "client identity fields must contain 1 to 15 bytes and no NUL"
            );
        }
        Ok(Self {
            config,
            identity,
            assets: Assets::bundled()?,
        })
    }

    /// Replace the bundled checksum inventory with an application-supplied one.
    ///
    /// # Errors
    ///
    /// Returns an error when the supplied inventory lacks required spell data.
    pub fn with_assets(mut self, assets: Assets) -> Result<Self> {
        assets.spells()?;
        self.assets = assets;
        Ok(self)
    }

    /// Connect and deliver events synchronously until completion or cancellation.
    /// Run on a worker thread and keep the handler fast (typically enqueue events).
    /// A confirmed credential rejection returns `LoginError` without reconnecting.
    /// A handler error terminates the run, without reconnecting or invoking it again.
    /// Network waits and retry delays observe cancellation; system DNS resolution
    /// remains a blocking platform call. Sessions close when the run unwinds.
    ///
    /// # Errors
    ///
    /// Returns a [`LoginError`] for rejected credentials and otherwise returns
    /// transport, protocol, cancellation, or event-handler errors.
    pub fn run(
        &self,
        cancel: &CancellationToken,
        options: RunOptions,
        mut handler: impl FnMut(ClientEvent) -> Result<()>,
    ) -> Result<()> {
        self.run_inner(cancel, options, None, &mut handler)
    }

    /// Connect and process commands from a nonblocking host-owned queue.
    /// Commands are consumed only after zone admission and may remain queued
    /// while a reconnect is in progress. Dropping every sender disables input.
    ///
    /// # Errors
    ///
    /// Returns a [`LoginError`] for rejected credentials and otherwise returns
    /// transport, protocol, cancellation, command, or event-handler errors.
    pub fn run_with_commands(
        &self,
        cancel: &CancellationToken,
        options: RunOptions,
        commands: &Receiver<ClientCommand>,
        mut handler: impl FnMut(ClientEvent) -> Result<()>,
    ) -> Result<()> {
        self.run_inner(cancel, options, Some(commands), &mut handler)
    }

    fn run_inner(
        &self,
        cancel: &CancellationToken,
        options: RunOptions,
        commands: Option<&Receiver<ClientCommand>>,
        handler: &mut dyn FnMut(ClientEvent) -> Result<()>,
    ) -> Result<()> {
        let mut events = Events::new(&self.config, handler);
        loop {
            if cancel.is_cancelled() {
                return events.status(ConnectionState::Stopped, 0, None);
            }
            events.reset();
            events.status(ConnectionState::Connecting, 0, None)?;
            events.send(ClientEvent::Progress(ConnectionStage::ConnectingLogin))?;
            let result = session::run(
                &self.config,
                &self.identity,
                &self.assets,
                cancel,
                &options,
                commands,
                &mut events,
            );
            if result
                .as_ref()
                .is_err_and(anyhow::Error::is::<EventDeliveryError>)
            {
                return result;
            }
            if result.is_ok() || cancel.is_cancelled() {
                return events.status(ConnectionState::Stopped, 0, None);
            }
            events.status(ConnectionState::Disconnected, 0, None)?;
            if !options.reconnect || result.as_ref().is_err_and(anyhow::Error::is::<LoginError>) {
                return result;
            }
            events.send(ClientEvent::Reconnecting {
                error: format!("{:#}", result.unwrap_err()),
                delay_seconds: self.config.reconnect_delay.as_secs(),
            })?;
            let retry = Instant::now()
                .checked_add(self.config.reconnect_delay)
                .context("reconnect delay exceeds clock range")?;
            while Instant::now() < retry && !cancel.is_cancelled() {
                std::thread::sleep(
                    retry
                        .saturating_duration_since(Instant::now())
                        .min(Duration::from_millis(200)),
                );
            }
        }
    }
}

#[derive(Debug)]
struct EventDeliveryError(anyhow::Error);

impl fmt::Display for EventDeliveryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "deliver client event: {}", self.0)
    }
}

impl std::error::Error for EventDeliveryError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.0.as_ref())
    }
}

struct Events<'a> {
    config: &'a ClientConfig,
    handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
    session_id: String,
    zone: String,
    messages: u64,
}

impl<'a> Events<'a> {
    fn new(
        config: &'a ClientConfig,
        handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
    ) -> Self {
        Self {
            config,
            handler,
            session_id: String::new(),
            zone: String::new(),
            messages: 0,
        }
    }

    fn reset(&mut self) {
        self.session_id = format!("{:016x}", rand::random::<u64>());
        self.zone.clear();
        self.messages = 0;
    }

    fn send(&mut self, event: ClientEvent) -> Result<()> {
        (self.handler)(event).map_err(|error| EventDeliveryError(error).into())
    }

    fn diagnostic(&mut self, message: String) -> Result<()> {
        self.send(ClientEvent::Diagnostic(message))
    }

    fn status(
        &mut self,
        state: ConnectionState,
        packets: u64,
        last_received_seconds: Option<u64>,
    ) -> Result<()> {
        self.send(ClientEvent::Status(SessionStatus {
            state,
            timestamp: chrono::Utc::now().timestamp(),
            session_id: self.session_id.clone(),
            zone: self.zone.clone(),
            messages: self.messages,
            packets,
            last_received_seconds,
        }))
    }

    fn record(&mut self, zone: &str, event: RecordEvent) -> Result<()> {
        if let RecordEvent::Chat(chat) = &event {
            if !self.config.logs(chat) {
                return Ok(());
            }
        }
        self.messages += 1;
        self.send(ClientEvent::Record(Box::new(Record {
            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
            server: self.config.server.clone(),
            character: self.config.character.clone(),
            zone: zone.to_owned(),
            session_id: self.session_id.clone(),
            message_id: self.messages,
            event,
        })))
    }
}

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

    #[test]
    fn protocol_names_are_stable_and_p99_aliases_remain_readable() {
        assert_eq!(
            serde_json::to_string(&ServerProtocol::Project1999).unwrap(),
            r#""project1999""#
        );
        for name in [r#""project1999""#, r#""p99""#, r#""project_1999""#] {
            assert_eq!(
                serde_json::from_str::<ServerProtocol>(name).unwrap(),
                ServerProtocol::Project1999
            );
        }
        assert_eq!(
            "QUARM".parse::<ServerProtocol>().unwrap(),
            ServerProtocol::Quarm
        );
    }

    fn chat(channel: u32) -> ChatEvent {
        let mut packet = vec![0; 148];
        packet[64..70].copy_from_slice(b"Sender");
        packet[132..136].copy_from_slice(&channel.to_le_bytes());
        packet.extend(b"Example message\0");
        chat::parse(0x1004, &packet, false).unwrap().unwrap()
    }

    #[test]
    fn records_preserve_flat_json_filtering_and_per_session_ids() {
        let mut config = ClientConfig::new(
            "EXAMPLE_ACCOUNT",
            "EXAMPLE_PASSWORD",
            "Test Server",
            "ExampleCharacter",
        );
        config.channels = Some(HashSet::from([ChannelName::Auction]));
        let mut received = Vec::new();
        let mut handler = |event| {
            received.push(event);
            Ok(())
        };
        let mut events = Events::new(&config, &mut handler);
        events.reset();
        events
            .record("testzone", RecordEvent::Chat(chat(8)))
            .unwrap();
        events
            .record("testzone", RecordEvent::Chat(chat(4)))
            .unwrap();
        events
            .record(
                "testzone",
                RecordEvent::DecodeError(DecodeError {
                    kind: "decode_error",
                    opcode: 0x1004,
                    payload_hex: "00".into(),
                    error: "synthetic truncation".into(),
                }),
            )
            .unwrap();
        assert_eq!(events.messages, 2);
        events.reset();
        events
            .record("testzone", RecordEvent::Chat(chat(4)))
            .unwrap();

        let records: Vec<_> = received
            .into_iter()
            .map(|event| match event {
                ClientEvent::Record(record) => serde_json::to_value(record).unwrap(),
                _ => panic!("unexpected event"),
            })
            .collect();
        assert_eq!(records.len(), 3);
        let record = &records[0];
        assert_eq!(record["type"], "chat");
        assert_eq!(record["channel_name"], "auction");
        assert_eq!(record["channel"], 4);
        assert_eq!(record["text"], "Example message");
        assert_eq!(record["sender"], "Sender");
        assert_eq!(record["server"], "Test Server");
        assert_eq!(record["character"], "ExampleCharacter");
        assert_eq!(record["zone"], "testzone");
        assert_eq!(record["message_id"], 1);
        assert!(record.get("event").is_none() && record.get("payload_hex").is_none());
        assert!(
            chrono::DateTime::parse_from_rfc3339(record["timestamp"].as_str().unwrap()).is_ok()
        );
        assert_eq!(records[1]["type"], "decode_error");
        assert_eq!(records[1]["message_id"], 2);
        assert_eq!(records[1]["payload_hex"], "00");
        assert_eq!(records[1]["session_id"], record["session_id"]);
        assert_eq!(records[2]["message_id"], 1);
        assert_ne!(records[2]["session_id"], record["session_id"]);
        let serialized = serde_json::to_string(&records).unwrap();
        assert!(
            !serialized.contains("EXAMPLE_ACCOUNT") && !serialized.contains("EXAMPLE_PASSWORD")
        );
    }

    #[test]
    fn default_channels_include_unknown_and_empty_filter_suppresses_chat() {
        let mut config = ClientConfig::new(
            "EXAMPLE_ACCOUNT",
            "EXAMPLE_PASSWORD",
            "Test Server",
            "ExampleCharacter",
        );
        assert!(config.logs(&chat(999)));
        config.channels = Some(HashSet::new());
        assert!(!config.logs(&chat(999)) && !config.logs(&chat(4)));
    }
}