Skip to main content

eq_network/
client.rs

1//! Blocking, cancellable session engine for native applications and the CLI.
2//!
3//! The host supplies credentials and validation metadata, starts a worker, and
4//! consumes events on its UI thread. It owns credential persistence and logs.
5//! This example stops on a full or closed queue rather than dropping records.
6//!
7//! ```no_run
8//! use eq_network::{chat::OutboundChat, client::{CancellationToken,
9//!     Client, ClientCommand, ClientConfig, ClientIdentity, RunOptions}};
10//! use std::{sync::mpsc, thread};
11//!
12//! # fn example() -> anyhow::Result<()> {
13//! let config = ClientConfig::new("EXAMPLE_ACCOUNT", "EXAMPLE_PASSWORD",
14//!     "Project 1999: Green (Velious, PvE)", "ExampleCharacter");
15//! // Supply short metadata chosen by the host app (1 to 15 bytes per field).
16//! let identity = ClientIdentity::new("example-device", "example-user");
17//! let client = Client::new(config, identity)?;
18//! let cancel = CancellationToken::default();
19//! let worker_cancel = cancel.clone();
20//! let (events, receiver) = mpsc::sync_channel(512);
21//! let (commands, command_queue) = mpsc::sync_channel(32);
22//! let worker = thread::spawn(move || {
23//!     client.run_with_commands(&worker_cancel, RunOptions::default(), &command_queue, |event| {
24//!         events.try_send(event).map_err(|_| anyhow::anyhow!("UI event queue unavailable"))
25//!     })
26//! });
27//! // After observing ConnectionStage::Ready, this is equivalent to `/say ok`.
28//! commands.try_send(ClientCommand::SendChat(OutboundChat::Say("ok".into())))?;
29//! // During the UI event loop, drain receiver.try_iter() and render the events.
30//! // On Disconnect or app shutdown, cancel and await worker completion.
31//! cancel.cancel();
32//! worker.join().expect("session worker panicked")?;
33//! # drop(receiver);
34//! # Ok(())
35//! # }
36//! ```
37
38mod quarm;
39mod session;
40
41use crate::{
42    assets::Assets,
43    chat::{ChannelName, ChatEvent},
44};
45use anyhow::{ensure, Context, Result};
46use eq_network_game::GameDialect;
47use serde::{Deserialize, Serialize};
48use std::{
49    collections::HashSet,
50    fmt,
51    str::FromStr,
52    sync::{
53        atomic::{AtomicBool, Ordering},
54        mpsc::Receiver,
55        Arc,
56    },
57    time::{Duration, Instant},
58};
59use zeroize::Zeroizing;
60
61/// Typed work submitted by the host while a character is connected.
62pub use eq_network_game::command::GameCommand as ClientCommand;
63
64/// Wire protocol and client family used by a server.
65#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
66#[serde(rename_all = "snake_case")]
67#[non_exhaustive]
68pub enum ServerProtocol {
69    /// Project 1999's Titanium/P99-V62 protocol.
70    #[default]
71    #[serde(alias = "p99", alias = "project_1999")]
72    Project1999,
73    /// Project Quarm's Windows TAKP/EQMac protocol.
74    Quarm,
75}
76
77impl ServerProtocol {
78    /// Return the public login endpoint normally used by this protocol.
79    #[must_use]
80    pub const fn default_endpoint(self) -> (&'static str, u16) {
81        match self {
82            Self::Project1999 => ("login.eqemulator.net", 5998),
83            Self::Quarm => ("loginserver.takproject.net", 6000),
84        }
85    }
86}
87
88impl From<ServerProtocol> for GameDialect {
89    fn from(protocol: ServerProtocol) -> Self {
90        match protocol {
91            ServerProtocol::Project1999 => Self::TitaniumP99,
92            ServerProtocol::Quarm => Self::EqMac,
93        }
94    }
95}
96
97impl FromStr for ServerProtocol {
98    type Err = anyhow::Error;
99
100    fn from_str(value: &str) -> Result<Self> {
101        match value.to_ascii_lowercase().as_str() {
102            "p99" | "project1999" | "project_1999" => Ok(Self::Project1999),
103            "quarm" => Ok(Self::Quarm),
104            _ => anyhow::bail!("unknown server protocol {value:?}"),
105        }
106    }
107}
108
109/// Login secrets retained only for the lifetime of a client configuration.
110#[derive(Clone)]
111pub struct Credentials {
112    account: Zeroizing<String>,
113    password: Zeroizing<String>,
114}
115
116impl Credentials {
117    /// Store an account name and password with zeroization on drop.
118    pub fn new(account: impl Into<String>, password: impl Into<String>) -> Self {
119        Self {
120            account: Zeroizing::new(account.into()),
121            password: Zeroizing::new(password.into()),
122        }
123    }
124
125    /// Return the account name for packet encoding.
126    #[must_use]
127    pub fn account(&self) -> &str {
128        self.account.as_str()
129    }
130
131    fn password(&self) -> &str {
132        self.password.as_str()
133    }
134}
135
136impl fmt::Debug for Credentials {
137    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138        formatter
139            .debug_struct("Credentials")
140            .field("account", &"[REDACTED]")
141            .field("password", &"[REDACTED]")
142            .finish()
143    }
144}
145
146/// Connection and logging preferences.
147#[derive(Clone, Debug)]
148#[non_exhaustive]
149pub struct ClientConfig {
150    /// Server family and protocol generation.
151    pub protocol: ServerProtocol,
152    /// Login server hostname or address.
153    pub host: String,
154    /// Login server UDP port.
155    pub port: u16,
156    /// Login credentials, redacted from diagnostics and zeroized on drop.
157    pub credentials: Credentials,
158    /// World-server display name selected after login.
159    pub server: String,
160    /// Character selected on the world server.
161    pub character: String,
162    /// Whether decoded records retain raw packet representations.
163    pub include_raw: bool,
164    /// None logs every channel; an empty set logs no decoded chat.
165    pub channels: Option<HashSet<ChannelName>>,
166    /// Delay before starting a fresh session after a recoverable failure.
167    pub reconnect_delay: Duration,
168}
169
170impl ClientConfig {
171    /// Configure a character with the default login endpoint and all chat channels.
172    pub fn new(
173        user: impl Into<String>,
174        pass: impl Into<String>,
175        server: impl Into<String>,
176        character: impl Into<String>,
177    ) -> Self {
178        Self::for_protocol(ServerProtocol::Project1999, user, pass, server, character)
179    }
180
181    /// Configure a character with a protocol's normal login endpoint.
182    pub fn for_protocol(
183        protocol: ServerProtocol,
184        user: impl Into<String>,
185        pass: impl Into<String>,
186        server: impl Into<String>,
187        character: impl Into<String>,
188    ) -> Self {
189        let (host, port) = protocol.default_endpoint();
190        Self {
191            protocol,
192            host: host.into(),
193            port,
194            credentials: Credentials::new(user, pass),
195            server: server.into(),
196            character: character.into(),
197            include_raw: false,
198            channels: None,
199            reconnect_delay: Duration::from_secs(30),
200        }
201    }
202
203    fn validate(&self) -> Result<()> {
204        for value in [&self.host, &self.server, &self.character] {
205            ensure!(
206                !value.is_empty() && !value.contains('\0'),
207                "required connection fields must be nonempty and contain no NUL"
208            );
209        }
210        for value in [self.credentials.account(), self.credentials.password()] {
211            ensure!(
212                !value.is_empty() && !value.contains('\0'),
213                "required credentials must be nonempty and contain no NUL"
214            );
215        }
216        ensure!(self.port != 0, "login port must be nonzero");
217        if self.protocol == ServerProtocol::Quarm {
218            ensure!(
219                self.credentials.account().len() < 20 && self.credentials.password().len() < 20,
220                "Quarm login fields must fit in 19 bytes"
221            );
222        }
223        ensure!(
224            self.character.len() < 64,
225            "character name exceeds protocol field size"
226        );
227        ensure!(
228            self.reconnect_delay >= Duration::from_secs(10),
229            "reconnect delay must be at least 10 seconds"
230        );
231        Ok(())
232    }
233
234    /// Return whether a decoded communication should be delivered to the caller.
235    #[must_use]
236    pub fn logs(&self, event: &ChatEvent) -> bool {
237        self.channels
238            .as_ref()
239            .is_none_or(|channels| channels.contains(&event.channel_name))
240    }
241}
242
243/// Host-provided metadata for the V62 validation packet. Each field must fit
244/// within 15 UTF-8 bytes; the engine uppercases hostname before checking its size.
245#[derive(Clone)]
246#[non_exhaustive]
247pub struct ClientIdentity {
248    /// Short device hostname announced during P99 validation.
249    pub hostname: String,
250    /// Short operating-system username announced during P99 validation.
251    pub username: String,
252}
253
254impl ClientIdentity {
255    /// Construct host metadata for the P99 validation packet.
256    pub fn new(hostname: impl Into<String>, username: impl Into<String>) -> Self {
257        Self {
258            hostname: hostname.into(),
259            username: username.into(),
260        }
261    }
262}
263
264/// Cooperative shutdown, shared between the session worker and its owner.
265#[derive(Clone, Debug, Default)]
266pub struct CancellationToken(Arc<AtomicBool>);
267
268impl CancellationToken {
269    /// Request shutdown. A cancelled token remains cancelled; use a new one to reconnect.
270    pub fn cancel(&self) {
271        self.0.store(true, Ordering::Relaxed);
272    }
273
274    #[must_use]
275    /// Return whether cooperative shutdown has been requested.
276    pub fn is_cancelled(&self) -> bool {
277        self.0.load(Ordering::Relaxed)
278    }
279
280    fn flag(&self) -> &AtomicBool {
281        &self.0
282    }
283}
284
285impl From<Arc<AtomicBool>> for CancellationToken {
286    /// Adopt an existing shutdown flag, for example one registered with a signal handler.
287    fn from(flag: Arc<AtomicBool>) -> Self {
288        Self(flag)
289    }
290}
291
292/// A confirmed login rejection that cannot be resolved by reconnecting.
293/// Hosts can downcast the error returned by `Client::run` to present a specific message.
294#[derive(Clone, Copy, Debug, Eq, PartialEq)]
295#[non_exhaustive]
296pub enum LoginError {
297    /// The login server rejected the account/password pair.
298    InvalidCredentials,
299}
300
301impl fmt::Display for LoginError {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        match self {
304            Self::InvalidCredentials => f.write_str("Login account or password was rejected"),
305        }
306    }
307}
308
309impl std::error::Error for LoginError {}
310
311/// Limits for one run; transient failures reconnect until cancellation by default.
312#[derive(Clone, Copy, Debug)]
313#[non_exhaustive]
314pub struct RunOptions {
315    /// Reconnect after transient session failures.
316    pub reconnect: bool,
317    /// Stop after character selection without opening the zone connection.
318    pub world_only: bool,
319    /// Optional maximum time in the zone, including zone admission.
320    pub zone_duration: Option<Duration>,
321}
322
323impl Default for RunOptions {
324    fn default() -> Self {
325        Self {
326            reconnect: true,
327            world_only: false,
328            zone_duration: None,
329        }
330    }
331}
332
333/// Coarse connection state for health checks and user interfaces.
334#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
335#[serde(rename_all = "snake_case")]
336#[non_exhaustive]
337pub enum ConnectionState {
338    /// A fresh login attempt is in progress.
339    Connecting,
340    /// The character is active in a zone.
341    Connected,
342    /// A zone handoff is in progress.
343    Zoning,
344    /// The current network session ended.
345    Disconnected,
346    /// The client stopped after cancellation or a non-reconnecting run.
347    Stopped,
348}
349
350/// Periodic session state suitable for a UI status indicator or health adapter.
351#[derive(Clone, Debug, Serialize)]
352#[non_exhaustive]
353pub struct SessionStatus {
354    /// Current coarse connection state.
355    pub state: ConnectionState,
356    /// Unix timestamp when the status was emitted.
357    pub timestamp: i64,
358    /// Unique identifier for the current process-level session.
359    pub session_id: String,
360    /// Current short zone name, if known.
361    pub zone: String,
362    /// Number of communication records received in this attempt.
363    pub messages: u64,
364    /// Number of application packets received in this attempt.
365    pub packets: u64,
366    /// Seconds since the last valid server datagram, if a session is active.
367    pub last_received_seconds: Option<u64>,
368}
369
370impl SessionStatus {
371    /// Create an empty status snapshot for a connection state and session.
372    #[must_use]
373    pub fn new(state: ConnectionState, session_id: impl Into<String>) -> Self {
374        Self {
375            state,
376            timestamp: chrono::Utc::now().timestamp(),
377            session_id: session_id.into(),
378            zone: String::new(),
379            messages: 0,
380            packets: 0,
381            last_received_seconds: None,
382        }
383    }
384
385    /// Replace the timestamp, primarily for imported or synthetic events.
386    #[must_use]
387    pub const fn with_timestamp(mut self, timestamp: i64) -> Self {
388        self.timestamp = timestamp;
389        self
390    }
391
392    /// Attach the current short zone name.
393    #[must_use]
394    pub fn with_zone(mut self, zone: impl Into<String>) -> Self {
395        self.zone = zone.into();
396        self
397    }
398
399    /// Attach current communication and application-packet counters.
400    #[must_use]
401    pub const fn with_counters(mut self, messages: u64, packets: u64) -> Self {
402        self.messages = messages;
403        self.packets = packets;
404        self
405    }
406
407    /// Attach whole seconds since the last valid server datagram.
408    #[must_use]
409    pub const fn with_last_received(mut self, seconds: Option<u64>) -> Self {
410        self.last_received_seconds = seconds;
411        self
412    }
413}
414
415/// A recognized communication opcode whose body could not be decoded.
416#[derive(Clone, Debug, Serialize)]
417#[non_exhaustive]
418pub struct DecodeError {
419    #[serde(rename = "type")]
420    kind: &'static str,
421    /// Raw application opcode.
422    pub opcode: u16,
423    /// Hex-encoded packet body retained for diagnosis.
424    pub payload_hex: String,
425    /// Decoder error without credentials or packet secrets.
426    pub error: String,
427}
428
429impl DecodeError {
430    /// Create a structured failure for one recognized communication packet.
431    #[must_use]
432    pub fn new(opcode: u16, payload_hex: impl Into<String>, error: impl Into<String>) -> Self {
433        Self {
434            kind: "decode_error",
435            opcode,
436            payload_hex: payload_hex.into(),
437            error: error.into(),
438        }
439    }
440}
441
442/// Preserves the existing flat `chat/decode_error` JSON representation.
443#[derive(Clone, Debug, Serialize)]
444#[serde(untagged)]
445#[non_exhaustive]
446pub enum RecordEvent {
447    /// Successfully decoded communication.
448    Chat(ChatEvent),
449    /// Communication packet that failed validation or decoding.
450    DecodeError(DecodeError),
451}
452
453/// An owned communication record that can cross a thread or UI boundary.
454#[derive(Clone, Debug, Serialize)]
455#[non_exhaustive]
456pub struct Record {
457    /// RFC 3339 receive timestamp.
458    pub timestamp: String,
459    /// Selected world-server display name.
460    pub server: String,
461    /// Logged-in character name.
462    pub character: String,
463    /// Current short zone name.
464    pub zone: String,
465    /// Process-level session identifier.
466    pub session_id: String,
467    /// Monotonic record number within the session.
468    pub message_id: u64,
469    /// Decoded communication or decode failure.
470    #[serde(flatten)]
471    pub event: RecordEvent,
472}
473
474impl Record {
475    /// Create a communication record with the current UTC receive time.
476    #[must_use]
477    pub fn new(
478        server: impl Into<String>,
479        character: impl Into<String>,
480        zone: impl Into<String>,
481        session_id: impl Into<String>,
482        message_id: u64,
483        event: RecordEvent,
484    ) -> Self {
485        Self {
486            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
487            server: server.into(),
488            character: character.into(),
489            zone: zone.into(),
490            session_id: session_id.into(),
491            message_id,
492            event,
493        }
494    }
495
496    /// Replace the receive timestamp, primarily for imported or synthetic records.
497    #[must_use]
498    pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
499        self.timestamp = timestamp.into();
500        self
501    }
502}
503
504/// Ordered connection milestones, from the start of an attempt to zone admission.
505/// These describe completed protocol work, not elapsed time or packet counts.
506#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
507#[serde(rename_all = "snake_case")]
508#[non_exhaustive]
509pub enum ConnectionStage {
510    /// Opening the login-server transport.
511    ConnectingLogin,
512    /// Sending credentials and waiting for authentication.
513    Authenticating,
514    /// Requesting and selecting the configured world.
515    SelectingServer,
516    /// Opening and authenticating the world-server transport.
517    ConnectingWorld,
518    /// Requesting and selecting the configured character.
519    SelectingCharacter,
520    /// Opening the assigned zone-server transport.
521    ConnectingZone,
522    /// Receiving character and zone initialization data.
523    LoadingCharacter,
524    /// Completing final zone admission acknowledgements.
525    EnteringWorld,
526    /// Character is active and chat commands can be sent.
527    Ready,
528}
529
530/// Owned output produced by the native session engine.
531#[derive(Clone, Debug, Serialize)]
532#[serde(tag = "type", content = "data", rename_all = "snake_case")]
533#[non_exhaustive]
534pub enum ClientEvent {
535    /// Periodic health and connection status.
536    Status(SessionStatus),
537    /// Completed connection milestone.
538    Progress(ConnectionStage),
539    /// Decoded communication record.
540    Record(Box<Record>),
541    /// Credential-safe operational diagnostic.
542    Diagnostic(String),
543    /// Transient failure followed by a scheduled fresh session.
544    Reconnecting {
545        /// Credential-safe failure text.
546        error: String,
547        /// Delay before the next attempt.
548        delay_seconds: u64,
549    },
550}
551
552/// A reusable native client. The caller owns the worker thread and event storage.
553pub struct Client {
554    config: ClientConfig,
555    identity: ClientIdentity,
556    assets: Assets,
557}
558
559impl Client {
560    /// Validate settings and use the checksum inventory bundled with the crate.
561    ///
562    /// # Errors
563    ///
564    /// Returns an error when configuration, identity metadata, or the bundled
565    /// asset inventory is invalid.
566    pub fn new(config: ClientConfig, mut identity: ClientIdentity) -> Result<Self> {
567        config.validate()?;
568        identity.hostname = identity.hostname.to_uppercase();
569        for value in [&identity.hostname, &identity.username] {
570            ensure!(
571                !value.is_empty() && value.len() < 16 && !value.contains('\0'),
572                "client identity fields must contain 1 to 15 bytes and no NUL"
573            );
574        }
575        Ok(Self {
576            config,
577            identity,
578            assets: Assets::bundled()?,
579        })
580    }
581
582    /// Replace the bundled checksum inventory with an application-supplied one.
583    ///
584    /// # Errors
585    ///
586    /// Returns an error when the supplied inventory lacks required spell data.
587    pub fn with_assets(mut self, assets: Assets) -> Result<Self> {
588        assets.spells()?;
589        self.assets = assets;
590        Ok(self)
591    }
592
593    /// Connect and deliver events synchronously until completion or cancellation.
594    /// Run on a worker thread and keep the handler fast (typically enqueue events).
595    /// A confirmed credential rejection returns `LoginError` without reconnecting.
596    /// A handler error terminates the run, without reconnecting or invoking it again.
597    /// Network waits and retry delays observe cancellation; system DNS resolution
598    /// remains a blocking platform call. Sessions close when the run unwinds.
599    ///
600    /// # Errors
601    ///
602    /// Returns a [`LoginError`] for rejected credentials and otherwise returns
603    /// transport, protocol, cancellation, or event-handler errors.
604    pub fn run(
605        &self,
606        cancel: &CancellationToken,
607        options: RunOptions,
608        mut handler: impl FnMut(ClientEvent) -> Result<()>,
609    ) -> Result<()> {
610        self.run_inner(cancel, options, None, &mut handler)
611    }
612
613    /// Connect and process commands from a nonblocking host-owned queue.
614    /// Commands are consumed only after zone admission and may remain queued
615    /// while a reconnect is in progress. Dropping every sender disables input.
616    ///
617    /// # Errors
618    ///
619    /// Returns a [`LoginError`] for rejected credentials and otherwise returns
620    /// transport, protocol, cancellation, command, or event-handler errors.
621    pub fn run_with_commands(
622        &self,
623        cancel: &CancellationToken,
624        options: RunOptions,
625        commands: &Receiver<ClientCommand>,
626        mut handler: impl FnMut(ClientEvent) -> Result<()>,
627    ) -> Result<()> {
628        self.run_inner(cancel, options, Some(commands), &mut handler)
629    }
630
631    fn run_inner(
632        &self,
633        cancel: &CancellationToken,
634        options: RunOptions,
635        commands: Option<&Receiver<ClientCommand>>,
636        handler: &mut dyn FnMut(ClientEvent) -> Result<()>,
637    ) -> Result<()> {
638        let mut events = Events::new(&self.config, handler);
639        loop {
640            if cancel.is_cancelled() {
641                return events.status(ConnectionState::Stopped, 0, None);
642            }
643            events.reset();
644            events.status(ConnectionState::Connecting, 0, None)?;
645            events.send(ClientEvent::Progress(ConnectionStage::ConnectingLogin))?;
646            let result = session::run(
647                &self.config,
648                &self.identity,
649                &self.assets,
650                cancel,
651                &options,
652                commands,
653                &mut events,
654            );
655            if result
656                .as_ref()
657                .is_err_and(anyhow::Error::is::<EventDeliveryError>)
658            {
659                return result;
660            }
661            if result.is_ok() || cancel.is_cancelled() {
662                return events.status(ConnectionState::Stopped, 0, None);
663            }
664            events.status(ConnectionState::Disconnected, 0, None)?;
665            if !options.reconnect || result.as_ref().is_err_and(anyhow::Error::is::<LoginError>) {
666                return result;
667            }
668            events.send(ClientEvent::Reconnecting {
669                error: format!("{:#}", result.unwrap_err()),
670                delay_seconds: self.config.reconnect_delay.as_secs(),
671            })?;
672            let retry = Instant::now()
673                .checked_add(self.config.reconnect_delay)
674                .context("reconnect delay exceeds clock range")?;
675            while Instant::now() < retry && !cancel.is_cancelled() {
676                std::thread::sleep(
677                    retry
678                        .saturating_duration_since(Instant::now())
679                        .min(Duration::from_millis(200)),
680                );
681            }
682        }
683    }
684}
685
686#[derive(Debug)]
687struct EventDeliveryError(anyhow::Error);
688
689impl fmt::Display for EventDeliveryError {
690    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691        write!(f, "deliver client event: {}", self.0)
692    }
693}
694
695impl std::error::Error for EventDeliveryError {
696    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
697        Some(self.0.as_ref())
698    }
699}
700
701struct Events<'a> {
702    config: &'a ClientConfig,
703    handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
704    session_id: String,
705    zone: String,
706    messages: u64,
707}
708
709impl<'a> Events<'a> {
710    fn new(
711        config: &'a ClientConfig,
712        handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
713    ) -> Self {
714        Self {
715            config,
716            handler,
717            session_id: String::new(),
718            zone: String::new(),
719            messages: 0,
720        }
721    }
722
723    fn reset(&mut self) {
724        self.session_id = format!("{:016x}", rand::random::<u64>());
725        self.zone.clear();
726        self.messages = 0;
727    }
728
729    fn send(&mut self, event: ClientEvent) -> Result<()> {
730        (self.handler)(event).map_err(|error| EventDeliveryError(error).into())
731    }
732
733    fn diagnostic(&mut self, message: String) -> Result<()> {
734        self.send(ClientEvent::Diagnostic(message))
735    }
736
737    fn status(
738        &mut self,
739        state: ConnectionState,
740        packets: u64,
741        last_received_seconds: Option<u64>,
742    ) -> Result<()> {
743        self.send(ClientEvent::Status(SessionStatus {
744            state,
745            timestamp: chrono::Utc::now().timestamp(),
746            session_id: self.session_id.clone(),
747            zone: self.zone.clone(),
748            messages: self.messages,
749            packets,
750            last_received_seconds,
751        }))
752    }
753
754    fn record(&mut self, zone: &str, event: RecordEvent) -> Result<()> {
755        if let RecordEvent::Chat(chat) = &event {
756            if !self.config.logs(chat) {
757                return Ok(());
758            }
759        }
760        self.messages += 1;
761        self.send(ClientEvent::Record(Box::new(Record {
762            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
763            server: self.config.server.clone(),
764            character: self.config.character.clone(),
765            zone: zone.to_owned(),
766            session_id: self.session_id.clone(),
767            message_id: self.messages,
768            event,
769        })))
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776    use crate::chat;
777
778    #[test]
779    fn protocol_names_are_stable_and_p99_aliases_remain_readable() {
780        assert_eq!(
781            serde_json::to_string(&ServerProtocol::Project1999).unwrap(),
782            r#""project1999""#
783        );
784        for name in [r#""project1999""#, r#""p99""#, r#""project_1999""#] {
785            assert_eq!(
786                serde_json::from_str::<ServerProtocol>(name).unwrap(),
787                ServerProtocol::Project1999
788            );
789        }
790        assert_eq!(
791            "QUARM".parse::<ServerProtocol>().unwrap(),
792            ServerProtocol::Quarm
793        );
794    }
795
796    fn chat(channel: u32) -> ChatEvent {
797        let mut packet = vec![0; 148];
798        packet[64..70].copy_from_slice(b"Sender");
799        packet[132..136].copy_from_slice(&channel.to_le_bytes());
800        packet.extend(b"Example message\0");
801        chat::parse(0x1004, &packet, false).unwrap().unwrap()
802    }
803
804    #[test]
805    fn records_preserve_flat_json_filtering_and_per_session_ids() {
806        let mut config = ClientConfig::new(
807            "EXAMPLE_ACCOUNT",
808            "EXAMPLE_PASSWORD",
809            "Test Server",
810            "ExampleCharacter",
811        );
812        config.channels = Some(HashSet::from([ChannelName::Auction]));
813        let mut received = Vec::new();
814        let mut handler = |event| {
815            received.push(event);
816            Ok(())
817        };
818        let mut events = Events::new(&config, &mut handler);
819        events.reset();
820        events
821            .record("testzone", RecordEvent::Chat(chat(8)))
822            .unwrap();
823        events
824            .record("testzone", RecordEvent::Chat(chat(4)))
825            .unwrap();
826        events
827            .record(
828                "testzone",
829                RecordEvent::DecodeError(DecodeError {
830                    kind: "decode_error",
831                    opcode: 0x1004,
832                    payload_hex: "00".into(),
833                    error: "synthetic truncation".into(),
834                }),
835            )
836            .unwrap();
837        assert_eq!(events.messages, 2);
838        events.reset();
839        events
840            .record("testzone", RecordEvent::Chat(chat(4)))
841            .unwrap();
842
843        let records: Vec<_> = received
844            .into_iter()
845            .map(|event| match event {
846                ClientEvent::Record(record) => serde_json::to_value(record).unwrap(),
847                _ => panic!("unexpected event"),
848            })
849            .collect();
850        assert_eq!(records.len(), 3);
851        let record = &records[0];
852        assert_eq!(record["type"], "chat");
853        assert_eq!(record["channel_name"], "auction");
854        assert_eq!(record["channel"], 4);
855        assert_eq!(record["text"], "Example message");
856        assert_eq!(record["sender"], "Sender");
857        assert_eq!(record["server"], "Test Server");
858        assert_eq!(record["character"], "ExampleCharacter");
859        assert_eq!(record["zone"], "testzone");
860        assert_eq!(record["message_id"], 1);
861        assert!(record.get("event").is_none() && record.get("payload_hex").is_none());
862        assert!(
863            chrono::DateTime::parse_from_rfc3339(record["timestamp"].as_str().unwrap()).is_ok()
864        );
865        assert_eq!(records[1]["type"], "decode_error");
866        assert_eq!(records[1]["message_id"], 2);
867        assert_eq!(records[1]["payload_hex"], "00");
868        assert_eq!(records[1]["session_id"], record["session_id"]);
869        assert_eq!(records[2]["message_id"], 1);
870        assert_ne!(records[2]["session_id"], record["session_id"]);
871        let serialized = serde_json::to_string(&records).unwrap();
872        assert!(
873            !serialized.contains("EXAMPLE_ACCOUNT") && !serialized.contains("EXAMPLE_PASSWORD")
874        );
875    }
876
877    #[test]
878    fn default_channels_include_unknown_and_empty_filter_suppresses_chat() {
879        let mut config = ClientConfig::new(
880            "EXAMPLE_ACCOUNT",
881            "EXAMPLE_PASSWORD",
882            "Test Server",
883            "ExampleCharacter",
884        );
885        assert!(config.logs(&chat(999)));
886        config.channels = Some(HashSet::new());
887        assert!(!config.logs(&chat(999)) && !config.logs(&chat(4)));
888    }
889}