Skip to main content

arcane_sdk/
p2p.rs

1//! P2P lobbies: the meeting point, not the transport.
2//!
3//! Arcane hosts the **lobby** — a host, its members, a capacity, a join code —
4//! and carries an opaque `payload` for each member. Your game keeps its own
5//! netcode, or uses the coop network ([`crate::Net`]); there is no host migration.
6//! What Arcane gives you is the part that is annoying to build yourself: a
7//! place for players to find each other — by friends, by code, or by
8//! [`P2p::search`] over the [`Visibility::Public`] lobbies of your game —
9//! invitations between friends, and "Join" from the launcher.
10//!
11//! ```no_run
12//! # use arcane_sdk::Visibility;
13//! # let client = arcane_sdk::ArcaneClient::init()?;
14//! # let my_endpoint = b"udp://203.0.113.7:7777";
15//! let lobby = client.p2p().create_lobby(4, Visibility::FriendsAndCode, my_endpoint)?;
16//! println!("join code: {:?}", lobby.join_code);
17//! # Ok::<(), arcane_sdk::SdkError>(())
18//! ```
19//!
20//! The `payload` is yours: a public address, a ticket from your own netcode,
21//! anything up to 4 KiB. Arcane transports it base64-encoded and never reads it.
22//!
23//! [`P2p::poll_events`] drains a queue the `arcane-session` thread fills. That
24//! polling is **armed by the first call to [`crate::ArcaneClient::p2p`]** and
25//! costs a game that never touches lobbies exactly nothing. While the client is
26//! in an open lobby the thread polls every 5 seconds instead of every 60;
27//! heartbeats keep their own schedule either way.
28
29use std::collections::{BTreeMap, VecDeque};
30use std::sync::atomic::{AtomicBool, Ordering};
31use std::sync::{Mutex, MutexGuard, Weak};
32use std::time::Duration;
33
34use base64::engine::general_purpose::STANDARD as BASE64;
35use base64::Engine;
36use serde::{Deserialize, Serialize};
37use serde_json::json;
38
39use crate::desktop::{
40    delete_json, get_json, offline_only, patch_json, post_json, DesktopCall, GAMES_PATH_PREFIX,
41    OFFLINE_ONLY_ENV,
42};
43use crate::error::{ErrorCode, SdkError};
44use crate::session::SessionInner;
45
46const CALL_TIMEOUT: Duration = Duration::from_secs(5);
47
48/// How fast the session thread polls lobby events while the client is in an
49/// open lobby, instead of the usual 60-second tick.
50pub(crate) const IN_LOBBY_POLL: Duration = Duration::from_secs(5);
51
52/// Longest `payload` the SDK will carry for one member, in bytes.
53pub const MAX_LOBBY_PAYLOAD_LEN: usize = 4096;
54
55/// Number of characters in a join code.
56pub const JOIN_CODE_LEN: usize = 6;
57
58/// Most key / value pairs a lobby carries in its metadata.
59pub const MAX_LOBBY_METADATA_PAIRS: usize = 16;
60
61/// Longest metadata key, in bytes: lowercase ASCII letters, digits and `_`.
62pub const MAX_LOBBY_METADATA_KEY_LEN: usize = 32;
63
64/// Longest metadata value, in characters.
65pub const MAX_LOBBY_METADATA_VALUE_LEN: usize = 128;
66
67/// Largest lobby metadata set, in bytes of its JSON object.
68pub const MAX_LOBBY_METADATA_BYTES: usize = 2048;
69
70/// Most lobbies one [`P2p::search`] returns.
71pub const MAX_LOBBY_SEARCH_RESULTS: u8 = 50;
72
73const MAX_ID_LEN: usize = 64;
74const MAX_QUEUED_EVENTS: usize = 256;
75const MAX_SEEN_EVENT_IDS: usize = 256;
76
77/// What [`MAX_LOBBY_PAYLOAD_LEN`] bytes take once base64-encoded, so an
78/// oversized answer is refused before it is decoded.
79const BASE64_LEN_LIMIT: usize = MAX_LOBBY_PAYLOAD_LEN.div_ceil(3) * 4;
80
81/// Who can join a lobby.
82///
83/// Only a [`Visibility::Public`] lobby is ever listed, and only to players who
84/// own the game; the others are reachable through the host's friends, through
85/// their join code, or both.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Visibility {
88    /// The host's friends can see it in the launcher and join. No join code is
89    /// issued.
90    Friends,
91    /// Only players who have the join code can join.
92    Code,
93    /// Both: friends see it, and the code works for anyone who has it.
94    FriendsAndCode,
95    /// Anyone who owns the game finds it with [`P2p::search`] and joins it by
96    /// id; friends see it in the launcher too. The join code still goes to the
97    /// host and the members only.
98    Public,
99}
100
101impl Visibility {
102    /// Stable wire string: `"friends"`, `"code"`, `"friends_and_code"`,
103    /// `"public"`.
104    pub fn as_str(&self) -> &'static str {
105        match self {
106            Self::Friends => "friends",
107            Self::Code => "code",
108            Self::FriendsAndCode => "friends_and_code",
109            Self::Public => "public",
110        }
111    }
112}
113
114impl std::fmt::Display for Visibility {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.write_str(self.as_str())
117    }
118}
119
120/// A lobby as Arcane knows it, right after a create or a join.
121///
122/// It is a snapshot, not a live view: members who arrive later come through
123/// [`P2p::poll_events`] as [`LobbyEvent::MemberJoined`].
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct Lobby {
126    /// Arcane's id for the lobby — what [`P2p::invite`], [`P2p::leave`] and
127    /// [`P2p::close`] take.
128    pub lobby_id: String,
129    /// The six-character code to show the player, when the lobby's
130    /// [`Visibility`] issues one. `None` for a friends-only lobby, and for a
131    /// member who is not the host.
132    pub join_code: Option<String>,
133    /// The Arcane account hosting the lobby.
134    pub host_user_id: String,
135    /// The host's connection blob, decoded. This is what a joining player
136    /// connects to.
137    pub host_payload: Vec<u8>,
138    /// Everyone in the lobby right now, host included.
139    pub members: Vec<LobbyMember>,
140    /// Capacity the host asked for.
141    pub max_players: u8,
142    /// What the host says about the lobby — mode, map, region — and what
143    /// [`P2p::search`] filters on. Only the host changes it, with
144    /// [`P2p::set_metadata`].
145    pub metadata: BTreeMap<String, String>,
146}
147
148/// What [`P2p::create`] opens.
149#[derive(Debug, Clone, Copy)]
150pub struct LobbyOptions<'a> {
151    /// Capacity, host included: 2 to 64.
152    pub max_players: u8,
153    /// Who can find and join it.
154    pub visibility: Visibility,
155    /// The host's connection blob, at most [`MAX_LOBBY_PAYLOAD_LEN`] bytes.
156    pub payload: &'a [u8],
157    /// At most [`MAX_LOBBY_METADATA_PAIRS`] pairs, searchable on a
158    /// [`Visibility::Public`] lobby.
159    pub metadata: &'a [(&'a str, &'a str)],
160}
161
162/// What [`P2p::search`] looks for among the open [`Visibility::Public`]
163/// lobbies of this game.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct LobbyQuery {
166    /// Metadata a lobby must carry, every pair matched exactly.
167    pub filters: Vec<(String, String)>,
168    /// Leave full lobbies out. On by default.
169    pub has_free_slot: bool,
170    /// How many lobbies to return, 1 to [`MAX_LOBBY_SEARCH_RESULTS`]. 20 by
171    /// default.
172    pub limit: u8,
173}
174
175impl Default for LobbyQuery {
176    fn default() -> Self {
177        Self {
178            filters: Vec::new(),
179            has_free_slot: true,
180            limit: 20,
181        }
182    }
183}
184
185/// One lobby [`P2p::search`] found. Join it with [`P2p::join`] and its
186/// [`lobby_id`](LobbySummary::lobby_id).
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct LobbySummary {
189    pub lobby_id: String,
190    pub host_user_id: String,
191    pub host_pseudo: String,
192    /// Players in it right now, host included.
193    pub members: u8,
194    pub max_players: u8,
195    pub metadata: BTreeMap<String, String>,
196    /// Whether the host is a friend of this player. Friends' lobbies come
197    /// first.
198    pub host_is_friend: bool,
199}
200
201/// One player in a lobby, with the blob they published.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct LobbyMember {
204    /// Their Arcane account id.
205    pub user_id: String,
206    /// Their display name on Arcane.
207    pub pseudo: String,
208    /// Their connection blob, decoded — whatever their copy of the game passed
209    /// to [`P2p::create_lobby`] or [`P2p::join`].
210    pub payload: Vec<u8>,
211}
212
213/// Something that happened in a lobby this player is in, or an invitation.
214///
215/// Delivered by [`P2p::poll_events`], oldest first, exactly once.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub enum LobbyEvent {
218    /// A friend invited this player to their lobby. Join it with
219    /// [`P2p::join`], or with [`P2p::join_by_code`] when a code came with it.
220    Invite {
221        lobby_id: String,
222        join_code: Option<String>,
223        from_user_id: String,
224        pseudo: String,
225    },
226    /// Somebody joined a lobby this player is in. `payload` is their
227    /// connection blob — connect to it.
228    MemberJoined {
229        lobby_id: String,
230        user_id: String,
231        pseudo: String,
232        payload: Vec<u8>,
233    },
234    /// Somebody left.
235    MemberLeft { lobby_id: String, user_id: String },
236    /// The lobby is over: the host closed it or their play session expired.
237    /// There is no host migration — open a new lobby.
238    LobbyClosed { lobby_id: String },
239    /// The host changed the lobby's metadata. `metadata` is the whole new
240    /// set, not a difference.
241    LobbyUpdated {
242        lobby_id: String,
243        metadata: BTreeMap<String, String>,
244    },
245    /// Arcane dropped events before this client fetched them, so the queue has
246    /// a hole in it. Re-read the lobbies you are in with [`P2p::get_lobby`]
247    /// instead of trusting what the earlier events built up.
248    Resync,
249}
250
251impl LobbyEvent {
252    /// The lobby this event is about, or `None` for a
253    /// [`Resync`](LobbyEvent::Resync), which is about all of them.
254    pub fn lobby_id(&self) -> Option<&str> {
255        match self {
256            Self::Invite { lobby_id, .. }
257            | Self::MemberJoined { lobby_id, .. }
258            | Self::MemberLeft { lobby_id, .. }
259            | Self::LobbyClosed { lobby_id }
260            | Self::LobbyUpdated { lobby_id, .. } => Some(lobby_id),
261            Self::Resync => None,
262        }
263    }
264}
265
266/// Whether the session thread is polling Arcane for lobby events.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum LobbyPollingState {
269    /// Nothing is polled: the game has never called `p2p()`, or the play
270    /// session itself is off (`ARCANE_OFFLINE_ONLY`, or nobody to attribute it
271    /// to), so no thread is running to poll with.
272    Off,
273    /// Armed: the session thread asks for events on every tick.
274    Active,
275    /// The Arcane desktop app predates the lobby routes. Polling stopped and
276    /// will not restart for this client.
277    Unavailable,
278}
279
280impl LobbyPollingState {
281    /// Stable wire string: `"off"`, `"active"`, `"unavailable"`.
282    pub fn as_str(&self) -> &'static str {
283        match self {
284            Self::Off => "off",
285            Self::Active => "active",
286            Self::Unavailable => "unavailable",
287        }
288    }
289}
290
291impl std::fmt::Display for LobbyPollingState {
292    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293        f.write_str(self.as_str())
294    }
295}
296
297#[derive(Debug)]
298struct Shared {
299    polling: LobbyPollingState,
300    cursor: Option<String>,
301    events: VecDeque<(u64, LobbyEvent)>,
302    next_seq: u64,
303    seen: VecDeque<String>,
304    lobbies: Vec<String>,
305}
306
307/// Everything the game and the `arcane-session` thread share about lobbies:
308/// the arming flag, the event queue, the cursor, and which lobbies are open.
309#[derive(Debug)]
310pub(crate) struct P2pState {
311    armed: AtomicBool,
312    shared: Mutex<Shared>,
313    launch_code: Mutex<Option<Option<String>>>,
314    waker: Mutex<Option<Weak<SessionInner>>>,
315}
316
317impl P2pState {
318    pub(crate) fn new() -> Self {
319        Self {
320            armed: AtomicBool::new(false),
321            shared: Mutex::new(Shared {
322                polling: LobbyPollingState::Off,
323                cursor: None,
324                events: VecDeque::new(),
325                next_seq: 0,
326                seen: VecDeque::new(),
327                lobbies: Vec::new(),
328            }),
329            launch_code: Mutex::new(None),
330            waker: Mutex::new(None),
331        }
332    }
333
334    /// Let the session thread be woken when arming or a lobby changes what it
335    /// should do next, instead of waiting out a sleep of up to a minute.
336    pub(crate) fn set_waker(&self, waker: Weak<SessionInner>) {
337        *self.waker.lock().unwrap_or_else(|e| e.into_inner()) = Some(waker);
338    }
339
340    fn notify(&self) {
341        let waker = self
342            .waker
343            .lock()
344            .unwrap_or_else(|e| e.into_inner())
345            .as_ref()
346            .and_then(Weak::upgrade);
347        if let Some(session) = waker {
348            session.wake_now();
349        }
350    }
351
352    fn lock(&self) -> MutexGuard<'_, Shared> {
353        self.shared.lock().unwrap_or_else(|e| e.into_inner())
354    }
355
356    /// Start polling, unless a `feature_unavailable` already retired it for
357    /// this client.
358    fn arm(&self) {
359        if self.armed.load(Ordering::Relaxed) {
360            return;
361        }
362        let mut shared = self.lock();
363        if shared.polling == LobbyPollingState::Unavailable {
364            return;
365        }
366        shared.polling = LobbyPollingState::Active;
367        self.armed.store(true, Ordering::Relaxed);
368        drop(shared);
369        self.notify();
370    }
371
372    pub(crate) fn armed(&self) -> bool {
373        self.armed.load(Ordering::Relaxed)
374    }
375
376    pub(crate) fn polling(&self) -> LobbyPollingState {
377        self.lock().polling
378    }
379
380    /// The poll period for this tick: 5 seconds while a lobby is open, the
381    /// session tick otherwise, and never slower than the session tick.
382    pub(crate) fn poll_period(&self, tick: Duration) -> Duration {
383        if self.lock().lobbies.is_empty() {
384            tick
385        } else {
386            IN_LOBBY_POLL.min(tick)
387        }
388    }
389
390    fn enter(&self, lobby_id: &str) {
391        let mut shared = self.lock();
392        if !shared.lobbies.iter().any(|open| open == lobby_id) {
393            shared.lobbies.push(lobby_id.to_string());
394        }
395        drop(shared);
396        self.notify();
397    }
398
399    fn exit(&self, lobby_id: &str) {
400        self.lock().lobbies.retain(|open| open != lobby_id);
401        self.notify();
402    }
403
404    fn take_events(&self) -> Vec<LobbyEvent> {
405        let mut shared = self.lock();
406        shared.events.drain(..).map(|(_, event)| event).collect()
407    }
408
409    /// The queued events as C ABI JSON, and the sequence number of the last one
410    /// rendered — so the caller can drop exactly those, and only those, once
411    /// they are safely in the buffer. Every event carries a number that only
412    /// grows, so an event queued in between is never dropped unread.
413    pub(crate) fn events_json(&self) -> (String, Option<u64>) {
414        let shared = self.lock();
415        let rendered = render_events(shared.events.iter().map(|(_, event)| event));
416        (rendered, shared.events.back().map(|(seq, _)| *seq))
417    }
418
419    pub(crate) fn discard(&self, through: u64) {
420        let mut shared = self.lock();
421        while shared
422            .events
423            .front()
424            .is_some_and(|(seq, _)| *seq <= through)
425        {
426            shared.events.pop_front();
427        }
428    }
429
430    /// Queue what a poll returned. An event Arcane already sent — the cursor did
431    /// not advance, or the desktop app replayed it — is dropped rather than
432    /// delivered twice.
433    fn ingest(&self, events: Vec<Incoming>, cursor: Option<String>) {
434        let mut shared = self.lock();
435        if let Some(cursor) = cursor.filter(|value| !value.is_empty()) {
436            shared.cursor = Some(cursor);
437        }
438        for Incoming { id, event } in events {
439            if let Some(id) = &id {
440                if shared.seen.contains(id) {
441                    continue;
442                }
443                if shared.seen.len() >= MAX_SEEN_EVENT_IDS {
444                    shared.seen.pop_front();
445                }
446                shared.seen.push_back(id.clone());
447            }
448            if let LobbyEvent::LobbyClosed { lobby_id } = &event {
449                shared.lobbies.retain(|open| open != lobby_id);
450            }
451            if shared.events.len() >= MAX_QUEUED_EVENTS {
452                shared.events.pop_front();
453            }
454            let seq = shared.next_seq;
455            shared.next_seq += 1;
456            shared.events.push_back((seq, event));
457        }
458    }
459
460    /// Retire polling for good: the desktop app does not know the route.
461    fn retire(&self) {
462        let mut shared = self.lock();
463        self.armed.store(false, Ordering::Relaxed);
464        shared.polling = LobbyPollingState::Unavailable;
465    }
466}
467
468/// One round of event polling, called by the `arcane-session` thread.
469///
470/// Returns the failure to record on the session, if any. A
471/// `feature_unavailable` is not one: it retires polling silently and shows up
472/// as [`LobbyPollingState::Unavailable`] in the session snapshot instead.
473pub(crate) fn poll_once(game_id: &str, state: &P2pState) -> Option<SdkError> {
474    let cursor = state.lock().cursor.clone();
475    let response: WireEvents =
476        match get_json(&events_path(game_id, cursor.as_deref()), CALL_TIMEOUT) {
477            Ok(response) => response,
478            Err(call) => {
479                let err = call.into_sdk_error();
480                if err.error_code() == ErrorCode::FeatureUnavailable {
481                    state.retire();
482                    return None;
483                }
484                return Some(err);
485            }
486        };
487
488    let mut events: Vec<Incoming> = Vec::new();
489    if response.dropped {
490        events.push(Incoming {
491            id: None,
492            event: LobbyEvent::Resync,
493        });
494    }
495    events.extend(response.events.into_iter().filter_map(map_event));
496    state.ingest(events, response.cursor);
497    None
498}
499
500/// One event as it arrived, with the id Arcane deduplicates on.
501#[derive(Debug)]
502struct Incoming {
503    id: Option<String>,
504    event: LobbyEvent,
505}
506
507/// The lobby accessor, borrowed from the client.
508///
509/// Build it with [`crate::ArcaneClient::p2p`]. Doing so is what arms lobby
510/// event polling on the session thread, so a game that never calls it pays
511/// nothing.
512#[derive(Debug)]
513pub struct P2p<'a> {
514    game_id: &'a str,
515    state: &'a P2pState,
516}
517
518impl<'a> P2p<'a> {
519    pub(crate) fn new(game_id: &'a str, state: &'a P2pState) -> Self {
520        state.arm();
521        Self { game_id, state }
522    }
523
524    /// Open a lobby with this player as its host.
525    ///
526    /// `payload` is your connection blob — up to [`MAX_LOBBY_PAYLOAD_LEN`]
527    /// opaque bytes that Arcane carries to whoever joins. `max_players`
528    /// includes the host.
529    ///
530    /// One synchronous loopback round trip. The returned [`Lobby`] carries the
531    /// [`join_code`](Lobby::join_code) to show the player when the visibility
532    /// issues one.
533    ///
534    /// # Errors
535    ///
536    /// `invalid_argument` when `payload` is longer than
537    /// [`MAX_LOBBY_PAYLOAD_LEN`] (raised before any call), `not_owned`,
538    /// `not_authenticated`, `network_required` (including under
539    /// `ARCANE_OFFLINE_ONLY`), `arcane_unavailable`, `feature_unavailable`.
540    pub fn create_lobby(
541        &self,
542        max_players: u8,
543        visibility: Visibility,
544        payload: &[u8],
545    ) -> Result<Lobby, SdkError> {
546        self.create(LobbyOptions {
547            max_players,
548            visibility,
549            payload,
550            metadata: &[],
551        })
552    }
553
554    /// Open a lobby with this player as its host, with metadata.
555    ///
556    /// The same call as [`P2p::create_lobby`], plus up to
557    /// [`MAX_LOBBY_METADATA_PAIRS`] key / value pairs that other players see in
558    /// [`P2p::search`] when the lobby is [`Visibility::Public`].
559    ///
560    /// ```no_run
561    /// # use arcane_sdk::{LobbyOptions, Visibility};
562    /// # let client = arcane_sdk::ArcaneClient::init()?;
563    /// let lobby = client.p2p().create(LobbyOptions {
564    ///     max_players: 4,
565    ///     visibility: Visibility::Public,
566    ///     payload: b"udp://203.0.113.7:7777",
567    ///     metadata: &[("mode", "coop"), ("map", "crypt")],
568    /// })?;
569    /// # Ok::<(), arcane_sdk::SdkError>(())
570    /// ```
571    ///
572    /// # Errors
573    ///
574    /// `invalid_argument` for an oversized payload or malformed metadata
575    /// (raised before any call), plus the codes of [`P2p::create_lobby`].
576    pub fn create(&self, options: LobbyOptions<'_>) -> Result<Lobby, SdkError> {
577        let encoded = encode_payload(options.payload)?;
578        let metadata = metadata_arg(options.metadata.iter().copied())?;
579        self.guard_offline("Creating a lobby")?;
580
581        let body = json!({
582            "max_players": options.max_players,
583            "visibility": options.visibility.as_str(),
584            "payload": encoded,
585            "metadata": metadata,
586        });
587        let wire: WireLobby = post_json(&self.lobbies_path(), Some(body), CALL_TIMEOUT)
588            .map_err(DesktopCall::into_sdk_error)?;
589
590        self.entered(map_lobby(wire)?)
591    }
592
593    /// Join the lobby a six-character code points at.
594    ///
595    /// The code is uppercased before it is checked, so a player typing
596    /// `k7p3qx` is fine. `payload` is your own connection blob, published to
597    /// the members already there.
598    ///
599    /// # Errors
600    ///
601    /// `invalid_argument` when the code is not six characters of
602    /// `A–H J–N P–Z 2–9` or `payload` is too long (both raised before any
603    /// call), `lobby_not_found`, `lobby_full`, `lobby_closed`, plus the codes
604    /// of [`P2p::create_lobby`].
605    pub fn join_by_code(&self, join_code: &str, payload: &[u8]) -> Result<Lobby, SdkError> {
606        let code = normalize_join_code(join_code)?;
607        let encoded = encode_payload(payload)?;
608        self.guard_offline("Joining a lobby")?;
609
610        let body = json!({ "join_code": code, "payload": encoded });
611        let wire: WireLobby = post_json(
612            &format!("{}/join", self.lobbies_path()),
613            Some(body),
614            CALL_TIMEOUT,
615        )
616        .map_err(|call| call.into_sdk_error().with_context("join_code", &code))?;
617
618        self.entered(map_lobby(wire)?)
619    }
620
621    /// Join a lobby by id — what an [`LobbyEvent::Invite`] carries, and what
622    /// the launcher passes when a friend hits "Join".
623    ///
624    /// # Errors
625    ///
626    /// `invalid_argument` for a malformed id or an oversized payload,
627    /// `not_friends` when the lobby is open to the host's friends only,
628    /// `lobby_not_found`, `lobby_full`, `lobby_closed`, plus the codes of
629    /// [`P2p::create_lobby`].
630    pub fn join(&self, lobby_id: &str, payload: &[u8]) -> Result<Lobby, SdkError> {
631        validate_id("lobby_id", lobby_id)?;
632        let encoded = encode_payload(payload)?;
633        self.guard_offline("Joining a lobby")?;
634
635        let body = json!({ "payload": encoded });
636        let wire: WireLobby = post_json(
637            &format!("{}/{lobby_id}/join", self.lobbies_path()),
638            Some(body),
639            CALL_TIMEOUT,
640        )
641        .map_err(|call| call.into_sdk_error().with_context("lobby_id", lobby_id))?;
642
643        self.entered(map_lobby(wire)?)
644    }
645
646    /// Read a lobby as Arcane knows it right now.
647    ///
648    /// Use it after a [`LobbyEvent::Resync`], or whenever you would rather ask
649    /// than replay events. One synchronous loopback round trip; it does not
650    /// join or leave anything, so it never changes what this client is in.
651    ///
652    /// # Errors
653    ///
654    /// `invalid_argument` for a malformed id (raised before any call),
655    /// `lobby_not_found`, `lobby_closed`, `not_friends`, plus the codes of
656    /// [`P2p::create_lobby`].
657    pub fn get_lobby(&self, lobby_id: &str) -> Result<Lobby, SdkError> {
658        validate_id("lobby_id", lobby_id)?;
659        self.guard_offline("Reading a lobby")?;
660
661        let wire: WireLobby =
662            get_json(&format!("{}/{lobby_id}", self.lobbies_path()), CALL_TIMEOUT)
663                .map_err(|call| call.into_sdk_error().with_context("lobby_id", lobby_id))?;
664
665        map_lobby(wire)
666    }
667
668    /// Replace the metadata of a lobby this player hosts.
669    ///
670    /// The members get a [`LobbyEvent::LobbyUpdated`] with the new set. Pass
671    /// the whole set every time: a key left out is removed.
672    ///
673    /// # Errors
674    ///
675    /// `invalid_argument` for a malformed id or metadata (raised before any
676    /// call), `not_host`, `lobby_not_found`, `lobby_closed`, plus the codes of
677    /// [`P2p::create_lobby`].
678    pub fn set_metadata(
679        &self,
680        lobby_id: &str,
681        metadata: &[(&str, &str)],
682    ) -> Result<Lobby, SdkError> {
683        validate_id("lobby_id", lobby_id)?;
684        let metadata = metadata_arg(metadata.iter().copied())?;
685        self.guard_offline("Changing a lobby")?;
686
687        let body = json!({ "metadata": metadata });
688        let wire: WireLobby = patch_json(
689            &format!("{}/{lobby_id}/metadata", self.lobbies_path()),
690            Some(body),
691            CALL_TIMEOUT,
692        )
693        .map_err(|call| call.into_sdk_error().with_context("lobby_id", lobby_id))?;
694
695        map_lobby(wire)
696    }
697
698    /// Find open [`Visibility::Public`] lobbies of this game.
699    ///
700    /// Friends' lobbies come first, then the newest. Lobbies whose host has
701    /// stopped playing are never listed. One synchronous loopback round trip;
702    /// the desktop app answers the same query from a 5-second cache, so call
703    /// it when a menu opens or every few seconds, never per frame.
704    ///
705    /// ```no_run
706    /// # use arcane_sdk::LobbyQuery;
707    /// # let client = arcane_sdk::ArcaneClient::init()?;
708    /// let found = client.p2p().search(&LobbyQuery {
709    ///     filters: vec![("mode".into(), "coop".into())],
710    ///     ..LobbyQuery::default()
711    /// })?;
712    /// if let Some(first) = found.first() {
713    ///     client.p2p().join(&first.lobby_id, b"udp://198.51.100.4:7777")?;
714    /// }
715    /// # Ok::<(), arcane_sdk::SdkError>(())
716    /// ```
717    ///
718    /// # Errors
719    ///
720    /// `invalid_argument` for malformed filters or a limit out of range
721    /// (raised before any call), `rate_limited`, `not_owned`, plus the codes of
722    /// [`P2p::create_lobby`].
723    pub fn search(&self, query: &LobbyQuery) -> Result<Vec<LobbySummary>, SdkError> {
724        if query.limit == 0 || query.limit > MAX_LOBBY_SEARCH_RESULTS {
725            return Err(
726                SdkError::invalid_argument("The search limit is out of range.")
727                    .with_context("limit", query.limit)
728                    .with_context("max", MAX_LOBBY_SEARCH_RESULTS),
729            );
730        }
731        let filters = metadata_arg(
732            query
733                .filters
734                .iter()
735                .map(|(key, value)| (key.as_str(), value.as_str())),
736        )?;
737        self.guard_offline("Searching for lobbies")?;
738
739        let wire: WireSearch = get_json(&search_path(self.game_id, query, &filters), CALL_TIMEOUT)
740            .map_err(DesktopCall::into_sdk_error)?;
741
742        Ok(wire.lobbies.into_iter().filter_map(map_summary).collect())
743    }
744
745    /// Invite one friend to a lobby.
746    ///
747    /// Arcane delivers it to their launcher: they get an
748    /// [`LobbyEvent::Invite`] if they are already playing this title, and the
749    /// code for their next launch otherwise
750    /// ([`P2p::launch_join_code`]).
751    ///
752    /// # Errors
753    ///
754    /// `invalid_argument` for a malformed id, `lobby_not_found`,
755    /// `lobby_closed`, `not_friends` when that account is not a friend, plus
756    /// the codes of [`P2p::create_lobby`].
757    pub fn invite(&self, lobby_id: &str, to_user_id: &str) -> Result<(), SdkError> {
758        validate_id("lobby_id", lobby_id)?;
759        validate_id("to_user_id", to_user_id)?;
760        self.guard_offline("Inviting a friend")?;
761
762        let body = json!({ "to_user_id": to_user_id });
763        let _: WireOk = post_json(
764            &format!("{}/{lobby_id}/invite", self.lobbies_path()),
765            Some(body),
766            CALL_TIMEOUT,
767        )
768        .map_err(|call| {
769            call.into_sdk_error()
770                .with_context("lobby_id", lobby_id)
771                .with_context("to_user_id", to_user_id)
772        })?;
773
774        Ok(())
775    }
776
777    /// Leave a lobby. For the host this is the same as [`P2p::close`] on
778    /// Arcane's side: there is no host migration.
779    ///
780    /// # Errors
781    ///
782    /// `invalid_argument` for a malformed id, `lobby_not_found`, plus the
783    /// codes of [`P2p::create_lobby`].
784    pub fn leave(&self, lobby_id: &str) -> Result<(), SdkError> {
785        validate_id("lobby_id", lobby_id)?;
786        self.guard_offline("Leaving a lobby")?;
787
788        let sent: Result<WireOk, DesktopCall> = post_json(
789            &format!("{}/{lobby_id}/leave", self.lobbies_path()),
790            None,
791            CALL_TIMEOUT,
792        );
793
794        self.left(lobby_id, sent)
795    }
796
797    /// Close a lobby this player hosts. Its members get a
798    /// [`LobbyEvent::LobbyClosed`].
799    ///
800    /// # Errors
801    ///
802    /// `invalid_argument` for a malformed id, `lobby_not_found`, plus the
803    /// codes of [`P2p::create_lobby`].
804    pub fn close(&self, lobby_id: &str) -> Result<(), SdkError> {
805        validate_id("lobby_id", lobby_id)?;
806        self.guard_offline("Closing a lobby")?;
807
808        let sent: Result<WireOk, DesktopCall> =
809            delete_json(&format!("{}/{lobby_id}", self.lobbies_path()), CALL_TIMEOUT);
810
811        self.left(lobby_id, sent)
812    }
813
814    /// The join code this game was launched with, when the player started it
815    /// from a friend's "Join" in the launcher.
816    ///
817    /// Read from the Arcane desktop app on the **first** call and cached for
818    /// the client's lifetime — the desktop app clears it once it has been
819    /// served, so it belongs to this launch and no other. `None` when the game
820    /// was started normally, when the desktop app predates the route, and in
821    /// offline-only mode. Never fails.
822    ///
823    /// ```no_run
824    /// # let client = arcane_sdk::ArcaneClient::init()?;
825    /// # let my_endpoint = b"udp://203.0.113.7:7777";
826    /// if let Some(code) = client.p2p().launch_join_code() {
827    ///     let lobby = client.p2p().join_by_code(&code, my_endpoint)?;
828    ///     println!("connect to {} bytes", lobby.host_payload.len());
829    /// }
830    /// # Ok::<(), arcane_sdk::SdkError>(())
831    /// ```
832    pub fn launch_join_code(&self) -> Option<String> {
833        let mut cached = self
834            .state
835            .launch_code
836            .lock()
837            .unwrap_or_else(|e| e.into_inner());
838        if let Some(code) = cached.as_ref() {
839            return code.clone();
840        }
841        if offline_only() {
842            return None;
843        }
844
845        let fetched = match get_json::<WireLaunchContext>(
846            &format!("{GAMES_PATH_PREFIX}/{}/launch-context", self.game_id),
847            CALL_TIMEOUT,
848        ) {
849            Ok(context) => context
850                .join_code
851                .and_then(|code| normalize_join_code(&code).ok()),
852            // A desktop app that does not know the route has no code to hold,
853            // so that answer is final. A call that never got through is not an
854            // answer at all: leave the cache empty and let the next call ask.
855            Err(call) => {
856                if call.into_sdk_error().error_code() != ErrorCode::FeatureUnavailable {
857                    return None;
858                }
859                None
860            }
861        };
862
863        *cached = Some(fetched.clone());
864        fetched
865    }
866
867    /// Take everything the session thread has collected since the last call.
868    ///
869    /// Reads memory only — no I/O, no failure, no callback and no extra
870    /// thread. Once a second is plenty. Events come oldest first and are
871    /// delivered exactly once.
872    ///
873    /// ```no_run
874    /// # use arcane_sdk::LobbyEvent;
875    /// # let client = arcane_sdk::ArcaneClient::init()?;
876    /// for event in client.p2p().poll_events() {
877    ///     if let LobbyEvent::MemberJoined { payload, .. } = event {
878    ///         // connect_to(&payload)
879    ///     }
880    /// }
881    /// # Ok::<(), arcane_sdk::SdkError>(())
882    /// ```
883    pub fn poll_events(&self) -> Vec<LobbyEvent> {
884        self.state.take_events()
885    }
886
887    pub(crate) fn events_json(&self) -> (String, Option<u64>) {
888        self.state.events_json()
889    }
890
891    pub(crate) fn discard(&self, through: u64) {
892        self.state.discard(through);
893    }
894
895    /// Stop treating the lobby as open only once it really is: a call that
896    /// failed to reach Arcane leaves the player in it, and the faster poll with
897    /// them.
898    fn left(&self, lobby_id: &str, sent: Result<WireOk, DesktopCall>) -> Result<(), SdkError> {
899        let Err(call) = sent else {
900            self.state.exit(lobby_id);
901            return Ok(());
902        };
903
904        let error = call.into_sdk_error().with_context("lobby_id", lobby_id);
905        if matches!(
906            error.error_code(),
907            ErrorCode::LobbyNotFound | ErrorCode::LobbyClosed
908        ) {
909            self.state.exit(lobby_id);
910        }
911        Err(error)
912    }
913
914    fn entered(&self, lobby: Lobby) -> Result<Lobby, SdkError> {
915        self.state.enter(&lobby.lobby_id);
916        Ok(lobby)
917    }
918
919    fn lobbies_path(&self) -> String {
920        format!("{GAMES_PATH_PREFIX}/{}/lobbies", self.game_id)
921    }
922
923    fn guard_offline(&self, action: &str) -> Result<(), SdkError> {
924        if !offline_only() {
925            return Ok(());
926        }
927        Err(SdkError::network_required(format!(
928            "{action} needs the Arcane desktop app, and the SDK is running in offline-only mode."
929        ))
930        .with_hint(format!(
931            "Unset {OFFLINE_ONLY_ENV} to let the SDK contact the Arcane desktop app."
932        ))
933        .with_context("env", OFFLINE_ONLY_ENV))
934    }
935}
936
937/// Reject an oversized payload before any network call, and encode the rest.
938pub(crate) fn encode_payload(payload: &[u8]) -> Result<String, SdkError> {
939    if payload.len() > MAX_LOBBY_PAYLOAD_LEN {
940        return Err(
941            SdkError::invalid_argument("The lobby payload is larger than Arcane carries.")
942                .with_hint(
943                    "Send a reference your own netcode can resolve — an address or a ticket — \
944             not the data itself.",
945                )
946                .with_context("length", payload.len())
947                .with_context("max_length", MAX_LOBBY_PAYLOAD_LEN),
948        );
949    }
950    Ok(BASE64.encode(payload))
951}
952
953fn is_metadata_key(key: &str) -> bool {
954    !key.is_empty()
955        && key.len() <= MAX_LOBBY_METADATA_KEY_LEN
956        && key
957            .bytes()
958            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
959}
960
961/// Check metadata before any call, so a bad key is the game's own
962/// `invalid_argument` rather than a refusal from Arcane.
963pub(crate) fn metadata_arg<'k>(
964    pairs: impl Iterator<Item = (&'k str, &'k str)>,
965) -> Result<BTreeMap<String, String>, SdkError> {
966    let mut metadata = BTreeMap::new();
967    for (key, value) in pairs {
968        if !is_metadata_key(key) {
969            return Err(
970                SdkError::invalid_argument("A lobby metadata key is malformed.")
971                    .with_hint("Keys are 1 to 32 characters of a-z, 0-9 and _.")
972                    .with_context("key", key),
973            );
974        }
975        if value.chars().count() > MAX_LOBBY_METADATA_VALUE_LEN {
976            return Err(
977                SdkError::invalid_argument("A lobby metadata value is too long.")
978                    .with_context("key", key)
979                    .with_context("max_length", MAX_LOBBY_METADATA_VALUE_LEN),
980            );
981        }
982        metadata.insert(key.to_string(), value.to_string());
983    }
984    if metadata.len() > MAX_LOBBY_METADATA_PAIRS {
985        return Err(
986            SdkError::invalid_argument("A lobby carries too many metadata pairs.")
987                .with_context("pairs", metadata.len())
988                .with_context("max", MAX_LOBBY_METADATA_PAIRS),
989        );
990    }
991    let bytes = serde_json::to_vec(&metadata)
992        .map(|v| v.len())
993        .unwrap_or(usize::MAX);
994    if bytes > MAX_LOBBY_METADATA_BYTES {
995        return Err(SdkError::invalid_argument(
996            "The lobby metadata is over 2048 bytes as JSON.",
997        )
998        .with_context("bytes", bytes)
999        .with_context("max_bytes", MAX_LOBBY_METADATA_BYTES));
1000    }
1001    Ok(metadata)
1002}
1003
1004fn search_path(game_id: &str, query: &LobbyQuery, filters: &BTreeMap<String, String>) -> String {
1005    let mut path = format!(
1006        "{GAMES_PATH_PREFIX}/{game_id}/lobbies/search?has_free_slot={}&limit={}",
1007        query.has_free_slot, query.limit
1008    );
1009    for (key, value) in filters {
1010        path.push_str(&format!("&meta.{key}={}", encode_query(value)));
1011    }
1012    path
1013}
1014
1015/// Decode a base64 payload argument from the C ABI. `None` when it is not
1016/// base64 at all — the caller reports a bad argument rather than sending bytes
1017/// the game did not mean.
1018pub(crate) fn decode_payload_arg(raw: &str) -> Option<Vec<u8>> {
1019    let raw = raw.trim();
1020    if raw.len() > BASE64_LEN_LIMIT {
1021        return None;
1022    }
1023    let decoded = BASE64.decode(raw).ok()?;
1024    (decoded.len() <= MAX_LOBBY_PAYLOAD_LEN).then_some(decoded)
1025}
1026
1027/// Uppercase a join code and check it against the unambiguous alphabet the
1028/// backend generates from — no `I`, `O`, `0` or `1` to mistype.
1029pub(crate) fn normalize_join_code(join_code: &str) -> Result<String, SdkError> {
1030    let code = join_code.trim().to_ascii_uppercase();
1031    let malformed = SdkError::invalid_argument("That is not an Arcane join code.")
1032        .with_hint(
1033            "Join codes are 6 characters long, from `A`–`Z` without `I` or `O` and \
1034             `2`–`9`. Check what the player typed.",
1035        )
1036        .with_context("join_code", join_code)
1037        .with_context("expected_length", JOIN_CODE_LEN);
1038
1039    if code.chars().count() != JOIN_CODE_LEN {
1040        return Err(malformed);
1041    }
1042    if !code
1043        .chars()
1044        .all(|c| matches!(c, 'A'..='H' | 'J'..='N' | 'P'..='Z' | '2'..='9'))
1045    {
1046        return Err(malformed);
1047    }
1048    Ok(code)
1049}
1050
1051/// Reject an id that would not survive being interpolated into a loopback path.
1052pub(crate) fn validate_id(field: &str, value: &str) -> Result<(), SdkError> {
1053    let malformed = |reason: &str| {
1054        SdkError::invalid_argument(format!("The {field} is {reason}."))
1055            .with_hint(
1056                "Pass the value Arcane gave you — ids are ASCII letters, digits and `-`, \
1057                 up to 64 characters.",
1058            )
1059            .with_context("field", field)
1060            .with_context(field, value)
1061    };
1062
1063    if value.is_empty() {
1064        return Err(malformed("empty"));
1065    }
1066    if value.len() > MAX_ID_LEN {
1067        return Err(malformed("too long"));
1068    }
1069    if !value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
1070        return Err(malformed("not an Arcane id"));
1071    }
1072    Ok(())
1073}
1074
1075#[derive(Debug, Deserialize)]
1076struct WireOk {
1077    #[serde(default)]
1078    #[allow(dead_code)]
1079    ok: bool,
1080}
1081
1082#[derive(Debug, Deserialize)]
1083struct WireLaunchContext {
1084    #[serde(default)]
1085    join_code: Option<String>,
1086}
1087
1088#[derive(Debug, Deserialize)]
1089struct WireLobby {
1090    #[serde(default)]
1091    lobby_id: String,
1092    #[serde(default)]
1093    join_code: Option<String>,
1094    #[serde(default)]
1095    host_user_id: String,
1096    #[serde(default)]
1097    host_payload: Option<String>,
1098    #[serde(default)]
1099    max_players: u8,
1100    #[serde(default)]
1101    metadata: BTreeMap<String, String>,
1102    #[serde(default)]
1103    members: Vec<WireMember>,
1104}
1105
1106#[derive(Debug, Deserialize)]
1107struct WireSearch {
1108    #[serde(default)]
1109    lobbies: Vec<WireSummary>,
1110}
1111
1112#[derive(Debug, Deserialize)]
1113struct WireSummary {
1114    #[serde(default)]
1115    lobby_id: String,
1116    #[serde(default)]
1117    host_user_id: String,
1118    #[serde(default)]
1119    host_pseudo: String,
1120    #[serde(default)]
1121    members: u8,
1122    #[serde(default)]
1123    max_players: u8,
1124    #[serde(default)]
1125    metadata: BTreeMap<String, String>,
1126    #[serde(default)]
1127    host_is_friend: bool,
1128}
1129
1130#[derive(Debug, Deserialize)]
1131struct WireMember {
1132    #[serde(default)]
1133    user_id: String,
1134    #[serde(default)]
1135    pseudo: String,
1136    #[serde(default)]
1137    payload: Option<String>,
1138}
1139
1140#[derive(Debug, Deserialize)]
1141struct WireEvents {
1142    #[serde(default)]
1143    events: Vec<WireEvent>,
1144    #[serde(default)]
1145    cursor: Option<String>,
1146    /// Set when the desktop app's ring buffer evicted events this client never
1147    /// fetched.
1148    #[serde(default)]
1149    dropped: bool,
1150}
1151
1152#[derive(Debug, Deserialize)]
1153struct WireEvent {
1154    #[serde(default)]
1155    id: Option<String>,
1156    #[serde(rename = "type", default)]
1157    kind: String,
1158    #[serde(default)]
1159    lobby_id: String,
1160    #[serde(default)]
1161    join_code: Option<String>,
1162    #[serde(default)]
1163    from_user_id: Option<String>,
1164    #[serde(default)]
1165    user_id: Option<String>,
1166    #[serde(default)]
1167    pseudo: Option<String>,
1168    #[serde(default)]
1169    payload: Option<String>,
1170    #[serde(default)]
1171    metadata: Option<BTreeMap<String, String>>,
1172}
1173
1174fn map_summary(wire: WireSummary) -> Option<LobbySummary> {
1175    if wire.lobby_id.trim().is_empty() {
1176        return None;
1177    }
1178    Some(LobbySummary {
1179        lobby_id: wire.lobby_id,
1180        host_user_id: wire.host_user_id,
1181        host_pseudo: wire.host_pseudo,
1182        members: wire.members,
1183        max_players: wire.max_players,
1184        metadata: wire.metadata,
1185        host_is_friend: wire.host_is_friend,
1186    })
1187}
1188
1189fn map_lobby(wire: WireLobby) -> Result<Lobby, SdkError> {
1190    if wire.lobby_id.trim().is_empty() {
1191        return Err(
1192            SdkError::arcane_unavailable("Arcane desktop returned a lobby without an id.")
1193                .with_hint("The Arcane desktop app may be older than this SDK — update it.")
1194                .with_context("field", "lobby_id"),
1195        );
1196    }
1197
1198    Ok(Lobby {
1199        lobby_id: wire.lobby_id,
1200        join_code: wire.join_code.filter(|code| !code.trim().is_empty()),
1201        host_user_id: wire.host_user_id,
1202        host_payload: decode_payload(wire.host_payload.as_deref(), "host_payload")?,
1203        members: wire
1204            .members
1205            .into_iter()
1206            .map(|member| {
1207                Ok(LobbyMember {
1208                    user_id: member.user_id,
1209                    pseudo: member.pseudo,
1210                    payload: decode_payload(member.payload.as_deref(), "payload")?,
1211                })
1212            })
1213            .collect::<Result<Vec<_>, SdkError>>()?,
1214        max_players: wire.max_players,
1215        metadata: wire.metadata,
1216    })
1217}
1218
1219/// An event whose payload the desktop app mangled is still delivered — there is
1220/// no caller to hand an error to on the session thread — with an empty payload.
1221fn map_event(wire: WireEvent) -> Option<Incoming> {
1222    let lobby_id = wire.lobby_id;
1223    if lobby_id.is_empty() {
1224        return None;
1225    }
1226    let payload = || decode_payload(wire.payload.as_deref(), "payload").unwrap_or_default();
1227
1228    let event = match wire.kind.as_str() {
1229        "invite" => LobbyEvent::Invite {
1230            lobby_id,
1231            join_code: wire.join_code.filter(|code| !code.trim().is_empty()),
1232            from_user_id: wire.from_user_id.unwrap_or_default(),
1233            pseudo: wire.pseudo.unwrap_or_default(),
1234        },
1235        "member_joined" => LobbyEvent::MemberJoined {
1236            lobby_id,
1237            user_id: wire.user_id.unwrap_or_default(),
1238            pseudo: wire.pseudo.unwrap_or_default(),
1239            payload: payload(),
1240        },
1241        "member_left" => LobbyEvent::MemberLeft {
1242            lobby_id,
1243            user_id: wire.user_id.unwrap_or_default(),
1244        },
1245        "lobby_closed" => LobbyEvent::LobbyClosed { lobby_id },
1246        "lobby_updated" => LobbyEvent::LobbyUpdated {
1247            lobby_id,
1248            metadata: wire.metadata.unwrap_or_default(),
1249        },
1250        _ => return None,
1251    };
1252
1253    Some(Incoming { id: wire.id, event })
1254}
1255
1256/// The inbound half of the 4 KiB limit: Arcane carries at most that much, so an
1257/// answer holding more is not a payload this SDK sent and is refused rather
1258/// than kept in memory.
1259fn decode_payload(encoded: Option<&str>, field: &str) -> Result<Vec<u8>, SdkError> {
1260    let Some(encoded) = encoded.map(str::trim).filter(|value| !value.is_empty()) else {
1261        return Ok(Vec::new());
1262    };
1263    let malformed = |detail: String| {
1264        SdkError::arcane_unavailable(format!("Unexpected Arcane desktop payload: {detail}"))
1265            .with_hint("The Arcane desktop app must relay a payload untouched — update it.")
1266            .with_context("field", field)
1267    };
1268
1269    if encoded.len() > BASE64_LEN_LIMIT {
1270        return Err(malformed(format!(
1271            "it is longer than the {MAX_LOBBY_PAYLOAD_LEN} bytes Arcane carries"
1272        )));
1273    }
1274    let decoded = BASE64
1275        .decode(encoded)
1276        .map_err(|e| malformed(e.to_string()))?;
1277    if decoded.len() > MAX_LOBBY_PAYLOAD_LEN {
1278        return Err(malformed(format!(
1279            "it is longer than the {MAX_LOBBY_PAYLOAD_LEN} bytes Arcane carries"
1280        )));
1281    }
1282    Ok(decoded)
1283}
1284
1285fn events_path(game_id: &str, cursor: Option<&str>) -> String {
1286    let base = format!("{GAMES_PATH_PREFIX}/{game_id}/lobbies/events");
1287    match cursor {
1288        Some(cursor) => format!("{base}?after={}", encode_query(cursor)),
1289        None => base,
1290    }
1291}
1292
1293/// Percent-encode an opaque cursor so it survives the query string whatever the
1294/// desktop app puts in it.
1295fn encode_query(value: &str) -> String {
1296    let mut encoded = String::with_capacity(value.len());
1297    for byte in value.as_bytes() {
1298        match byte {
1299            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
1300                encoded.push(*byte as char)
1301            }
1302            _ => encoded.push_str(&format!("%{byte:02X}")),
1303        }
1304    }
1305    encoded
1306}
1307
1308/// The C ABI rendering, in the field order the header and the docs promise —
1309/// which `serde_json::json!` would not keep, as it sorts its keys.
1310#[derive(Serialize)]
1311struct JsonLobby<'a> {
1312    lobby_id: &'a str,
1313    join_code: Option<&'a str>,
1314    host_user_id: &'a str,
1315    host_payload: String,
1316    members: Vec<JsonMember<'a>>,
1317    max_players: u8,
1318    metadata: &'a BTreeMap<String, String>,
1319}
1320
1321#[derive(Serialize)]
1322struct JsonSearch<'a> {
1323    lobbies: Vec<JsonSummary<'a>>,
1324}
1325
1326#[derive(Serialize)]
1327struct JsonSummary<'a> {
1328    lobby_id: &'a str,
1329    host_user_id: &'a str,
1330    host_pseudo: &'a str,
1331    members: u8,
1332    max_players: u8,
1333    metadata: &'a BTreeMap<String, String>,
1334    host_is_friend: bool,
1335}
1336
1337#[derive(Serialize)]
1338struct JsonMember<'a> {
1339    user_id: &'a str,
1340    pseudo: &'a str,
1341    payload: String,
1342}
1343
1344#[derive(Serialize)]
1345struct JsonEvents<'a> {
1346    events: Vec<JsonEvent<'a>>,
1347}
1348
1349#[derive(Serialize)]
1350#[serde(tag = "type", rename_all = "snake_case")]
1351enum JsonEvent<'a> {
1352    Invite {
1353        lobby_id: &'a str,
1354        join_code: Option<&'a str>,
1355        from_user_id: &'a str,
1356        pseudo: &'a str,
1357    },
1358    MemberJoined {
1359        lobby_id: &'a str,
1360        user_id: &'a str,
1361        pseudo: &'a str,
1362        payload: String,
1363    },
1364    MemberLeft {
1365        lobby_id: &'a str,
1366        user_id: &'a str,
1367    },
1368    LobbyClosed {
1369        lobby_id: &'a str,
1370    },
1371    LobbyUpdated {
1372        lobby_id: &'a str,
1373        metadata: &'a BTreeMap<String, String>,
1374    },
1375    Resync,
1376}
1377
1378pub(crate) fn to_json(lobby: &Lobby) -> String {
1379    let rendered = JsonLobby {
1380        lobby_id: &lobby.lobby_id,
1381        join_code: lobby.join_code.as_deref(),
1382        host_user_id: &lobby.host_user_id,
1383        host_payload: BASE64.encode(&lobby.host_payload),
1384        members: lobby
1385            .members
1386            .iter()
1387            .map(|member| JsonMember {
1388                user_id: &member.user_id,
1389                pseudo: &member.pseudo,
1390                payload: BASE64.encode(&member.payload),
1391            })
1392            .collect(),
1393        max_players: lobby.max_players,
1394        metadata: &lobby.metadata,
1395    };
1396    serde_json::to_string(&rendered).unwrap_or_else(|_| r#"{"lobby_id":""}"#.to_string())
1397}
1398
1399pub(crate) fn summaries_to_json(lobbies: &[LobbySummary]) -> String {
1400    let rendered = JsonSearch {
1401        lobbies: lobbies
1402            .iter()
1403            .map(|lobby| JsonSummary {
1404                lobby_id: &lobby.lobby_id,
1405                host_user_id: &lobby.host_user_id,
1406                host_pseudo: &lobby.host_pseudo,
1407                members: lobby.members,
1408                max_players: lobby.max_players,
1409                metadata: &lobby.metadata,
1410                host_is_friend: lobby.host_is_friend,
1411            })
1412            .collect(),
1413    };
1414    serde_json::to_string(&rendered).unwrap_or_else(|_| r#"{"lobbies":[]}"#.to_string())
1415}
1416
1417fn render_events<'a>(events: impl Iterator<Item = &'a LobbyEvent>) -> String {
1418    let rendered = JsonEvents {
1419        events: events
1420            .map(|event| match event {
1421                LobbyEvent::Invite {
1422                    lobby_id,
1423                    join_code,
1424                    from_user_id,
1425                    pseudo,
1426                } => JsonEvent::Invite {
1427                    lobby_id,
1428                    join_code: join_code.as_deref(),
1429                    from_user_id,
1430                    pseudo,
1431                },
1432                LobbyEvent::MemberJoined {
1433                    lobby_id,
1434                    user_id,
1435                    pseudo,
1436                    payload,
1437                } => JsonEvent::MemberJoined {
1438                    lobby_id,
1439                    user_id,
1440                    pseudo,
1441                    payload: BASE64.encode(payload),
1442                },
1443                LobbyEvent::MemberLeft { lobby_id, user_id } => {
1444                    JsonEvent::MemberLeft { lobby_id, user_id }
1445                }
1446                LobbyEvent::LobbyClosed { lobby_id } => JsonEvent::LobbyClosed { lobby_id },
1447                LobbyEvent::LobbyUpdated { lobby_id, metadata } => {
1448                    JsonEvent::LobbyUpdated { lobby_id, metadata }
1449                }
1450                LobbyEvent::Resync => JsonEvent::Resync,
1451            })
1452            .collect(),
1453    };
1454    serde_json::to_string(&rendered).unwrap_or_else(|_| r#"{"events":[]}"#.to_string())
1455}
1456
1457#[cfg(test)]
1458mod tests {
1459    use super::*;
1460
1461    fn parse_lobby(raw: &str) -> Lobby {
1462        map_lobby(serde_json::from_str(raw).expect("wire lobby")).expect("mapped lobby")
1463    }
1464
1465    const LOBBY: &str = r#"{
1466        "lobby_id": "lobby-1",
1467        "join_code": "K7P3QX",
1468        "host_user_id": "user-host",
1469        "host_payload": "dWRwOi8vMTAuMC4wLjE6Nzc3Nw==",
1470        "visibility": "friends_and_code",
1471        "max_players": 4,
1472        "members": [
1473            {"user_id":"user-host","pseudo":"Ada","payload":"dWRwOi8vMTAuMC4wLjE6Nzc3Nw=="},
1474            {"user_id":"user-b","pseudo":"Bo","payload":null}
1475        ],
1476        "expires_at": "2026-05-01T12:34:56Z"
1477    }"#;
1478
1479    #[test]
1480    fn a_payload_survives_the_base64_round_trip() {
1481        let payload: Vec<u8> = (0u8..=255).collect();
1482        let encoded = encode_payload(&payload).expect("encoded");
1483
1484        assert_eq!(
1485            decode_payload(Some(&encoded), "payload").expect("decoded"),
1486            payload
1487        );
1488        assert_eq!(encode_payload(b"").expect("empty"), "");
1489        assert_eq!(
1490            decode_payload(Some(""), "payload").expect("empty"),
1491            Vec::<u8>::new()
1492        );
1493        assert_eq!(
1494            decode_payload(None, "payload").expect("absent"),
1495            Vec::<u8>::new()
1496        );
1497    }
1498
1499    #[test]
1500    fn a_payload_at_the_limit_is_accepted_and_one_byte_over_is_not() {
1501        assert!(encode_payload(&vec![7u8; MAX_LOBBY_PAYLOAD_LEN]).is_ok());
1502
1503        let err = encode_payload(&vec![7u8; MAX_LOBBY_PAYLOAD_LEN + 1]).expect_err("too long");
1504        assert_eq!(err.code(), "invalid_argument");
1505        assert!(err
1506            .context()
1507            .iter()
1508            .any(|(k, v)| k == "length" && v == &(MAX_LOBBY_PAYLOAD_LEN + 1).to_string()));
1509    }
1510
1511    #[test]
1512    fn a_c_abi_payload_argument_decodes_or_is_refused() {
1513        assert_eq!(decode_payload_arg("aGk=").expect("base64"), b"hi");
1514        assert_eq!(decode_payload_arg("").expect("empty"), Vec::<u8>::new());
1515        assert!(decode_payload_arg("not base64!!").is_none());
1516    }
1517
1518    #[test]
1519    fn a_join_code_is_uppercased_before_it_is_checked() {
1520        assert_eq!(normalize_join_code("k7p3qx").expect("lowercase"), "K7P3QX");
1521        assert_eq!(normalize_join_code(" K7P3QX ").expect("padded"), "K7P3QX");
1522    }
1523
1524    #[test]
1525    fn the_ambiguous_characters_are_not_join_codes() {
1526        for code in [
1527            "", "K7P3Q", "K7P3QXY", "K7P3Q0", "K7P3Q1", "K7P3QI", "K7P3QO", "K7-3QX", "K7P3Q ",
1528            "K7P3Q✨",
1529        ] {
1530            let err = normalize_join_code(code).expect_err("accepted {code}");
1531            assert_eq!(err.code(), "invalid_argument", "accepted {code:?}");
1532        }
1533    }
1534
1535    #[test]
1536    fn ids_are_checked_before_they_reach_a_url() {
1537        assert!(validate_id("lobby_id", "lobby-1").is_ok());
1538        assert!(validate_id("lobby_id", &"a".repeat(MAX_ID_LEN)).is_ok());
1539
1540        for bad in [
1541            "",
1542            "lobby/../evil",
1543            "lobby 1",
1544            "lobby?x=1",
1545            "lobby#f",
1546            "lobbÿ",
1547        ] {
1548            let err = validate_id("lobby_id", bad).expect_err("accepted");
1549            assert_eq!(err.code(), "invalid_argument", "accepted {bad:?}");
1550        }
1551        assert_eq!(
1552            validate_id("lobby_id", &"a".repeat(MAX_ID_LEN + 1))
1553                .expect_err("too long")
1554                .code(),
1555            "invalid_argument"
1556        );
1557    }
1558
1559    #[test]
1560    fn the_wire_lobby_maps_onto_the_public_struct() {
1561        let lobby = parse_lobby(LOBBY);
1562
1563        assert_eq!(lobby.lobby_id, "lobby-1");
1564        assert_eq!(lobby.join_code.as_deref(), Some("K7P3QX"));
1565        assert_eq!(lobby.host_user_id, "user-host");
1566        assert_eq!(lobby.host_payload, b"udp://10.0.0.1:7777");
1567        assert_eq!(lobby.max_players, 4);
1568        assert_eq!(lobby.members.len(), 2);
1569        assert_eq!(lobby.members[0].pseudo, "Ada");
1570        assert_eq!(lobby.members[0].payload, b"udp://10.0.0.1:7777");
1571        assert!(lobby.members[1].payload.is_empty());
1572    }
1573
1574    #[test]
1575    fn a_null_join_code_reads_as_no_code() {
1576        let lobby = parse_lobby(
1577            r#"{"lobby_id":"lobby-1","join_code":null,"host_user_id":"user-host",
1578                "max_players":2,"members":[]}"#,
1579        );
1580
1581        assert_eq!(lobby.join_code, None);
1582        assert!(lobby.host_payload.is_empty());
1583    }
1584
1585    #[test]
1586    fn a_payload_that_is_not_base64_fails_the_lobby_rather_than_reading_as_empty() {
1587        let wire: WireLobby = serde_json::from_str(
1588            r#"{"lobby_id":"lobby-1","host_user_id":"u","host_payload":"not base64!!","members":[]}"#,
1589        )
1590        .expect("wire lobby");
1591
1592        let err = map_lobby(wire).expect_err("bad base64");
1593        assert_eq!(err.code(), "arcane_unavailable");
1594        assert!(err
1595            .context()
1596            .iter()
1597            .any(|(k, v)| k == "field" && v == "host_payload"));
1598    }
1599
1600    fn parse_events(raw: &str) -> Vec<LobbyEvent> {
1601        parse_incoming(raw)
1602            .into_iter()
1603            .map(|incoming| incoming.event)
1604            .collect()
1605    }
1606
1607    fn parse_incoming(raw: &str) -> Vec<Incoming> {
1608        let wire: WireEvents = serde_json::from_str(raw).expect("wire events");
1609        wire.events.into_iter().filter_map(map_event).collect()
1610    }
1611
1612    fn queued(events: Vec<LobbyEvent>) -> Vec<Incoming> {
1613        events
1614            .into_iter()
1615            .map(|event| Incoming { id: None, event })
1616            .collect()
1617    }
1618
1619    #[test]
1620    fn every_event_type_maps_and_unknown_ones_are_skipped() {
1621        let events = parse_events(
1622            r#"{"events":[
1623                {"id":"1","type":"invite","lobby_id":"lobby-1","join_code":"K7P3QX",
1624                 "from_user_id":"user-a","pseudo":"Ada"},
1625                {"id":"2","type":"member_joined","lobby_id":"lobby-1","user_id":"user-b",
1626                 "pseudo":"Bo","payload":"dWRwOi8vMTAuMC4wLjI6Nzc3Nw=="},
1627                {"id":"3","type":"member_left","lobby_id":"lobby-1","user_id":"user-b"},
1628                {"id":"4","type":"lobby_closed","lobby_id":"lobby-1"},
1629                {"id":"5","type":"lobby_renamed","lobby_id":"lobby-1"},
1630                {"id":"6","type":"invite","lobby_id":""}
1631            ],"cursor":"c-2"}"#,
1632        );
1633
1634        assert_eq!(events.len(), 4, "{events:?}");
1635        assert_eq!(
1636            events[0],
1637            LobbyEvent::Invite {
1638                lobby_id: "lobby-1".into(),
1639                join_code: Some("K7P3QX".into()),
1640                from_user_id: "user-a".into(),
1641                pseudo: "Ada".into(),
1642            }
1643        );
1644        assert_eq!(
1645            events[1],
1646            LobbyEvent::MemberJoined {
1647                lobby_id: "lobby-1".into(),
1648                user_id: "user-b".into(),
1649                pseudo: "Bo".into(),
1650                payload: b"udp://10.0.0.2:7777".to_vec(),
1651            }
1652        );
1653        assert_eq!(events[2].lobby_id(), Some("lobby-1"));
1654        assert_eq!(
1655            events[3],
1656            LobbyEvent::LobbyClosed {
1657                lobby_id: "lobby-1".into()
1658            }
1659        );
1660    }
1661
1662    #[test]
1663    fn an_event_payload_that_is_not_base64_arrives_empty() {
1664        let events = parse_events(
1665            r#"{"events":[{"type":"member_joined","lobby_id":"lobby-1","user_id":"user-b",
1666                 "pseudo":"Bo","payload":"not base64!!"}]}"#,
1667        );
1668
1669        assert_eq!(
1670            events[0],
1671            LobbyEvent::MemberJoined {
1672                lobby_id: "lobby-1".into(),
1673                user_id: "user-b".into(),
1674                pseudo: "Bo".into(),
1675                payload: Vec::new(),
1676            }
1677        );
1678    }
1679
1680    #[test]
1681    fn the_events_path_carries_the_cursor_only_once_there_is_one() {
1682        assert_eq!(
1683            events_path("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", None),
1684            "/v1/games/7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34/lobbies/events"
1685        );
1686        assert_eq!(
1687            events_path("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", Some("c-2")),
1688            "/v1/games/7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34/lobbies/events?after=c-2"
1689        );
1690        assert_eq!(
1691            events_path("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", Some("a b&c=1/2")),
1692            "/v1/games/7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34/lobbies/events?after=a%20b%26c%3D1%2F2"
1693        );
1694    }
1695
1696    fn state() -> P2pState {
1697        P2pState::new()
1698    }
1699
1700    #[test]
1701    fn polling_is_off_until_the_accessor_is_built() {
1702        let state = state();
1703        assert_eq!(state.polling(), LobbyPollingState::Off);
1704        assert!(!state.armed());
1705
1706        P2p::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", &state);
1707
1708        assert_eq!(state.polling(), LobbyPollingState::Active);
1709        assert!(state.armed());
1710    }
1711
1712    #[test]
1713    fn an_unavailable_desktop_retires_polling_for_good() {
1714        let state = state();
1715        P2p::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", &state);
1716        state.retire();
1717
1718        assert!(!state.armed());
1719        assert_eq!(state.polling(), LobbyPollingState::Unavailable);
1720
1721        P2p::new("7c9e6f21-4b58-4a3d-8e10-5d2f9b0c1a34", &state);
1722
1723        assert!(!state.armed(), "a later p2p() call must not re-arm polling");
1724        assert_eq!(state.polling(), LobbyPollingState::Unavailable);
1725    }
1726
1727    #[test]
1728    fn the_poll_period_drops_to_five_seconds_inside_a_lobby() {
1729        let state = state();
1730        let tick = Duration::from_secs(60);
1731        assert_eq!(state.poll_period(tick), tick);
1732
1733        state.enter("lobby-1");
1734        assert_eq!(state.poll_period(tick), IN_LOBBY_POLL);
1735        assert_eq!(
1736            state.poll_period(Duration::from_millis(50)),
1737            Duration::from_millis(50),
1738            "the poll never runs slower than the session tick"
1739        );
1740
1741        state.exit("lobby-1");
1742        assert_eq!(state.poll_period(tick), tick);
1743    }
1744
1745    #[test]
1746    fn a_closed_lobby_event_clears_the_in_lobby_state() {
1747        let state = state();
1748        state.enter("lobby-1");
1749        state.enter("lobby-2");
1750
1751        state.ingest(
1752            queued(vec![LobbyEvent::LobbyClosed {
1753                lobby_id: "lobby-1".into(),
1754            }]),
1755            Some("c-2".into()),
1756        );
1757
1758        assert_eq!(state.poll_period(Duration::from_secs(60)), IN_LOBBY_POLL);
1759        state.exit("lobby-2");
1760        assert_eq!(
1761            state.poll_period(Duration::from_secs(60)),
1762            Duration::from_secs(60)
1763        );
1764        assert_eq!(state.lock().cursor.as_deref(), Some("c-2"));
1765    }
1766
1767    #[test]
1768    fn an_empty_cursor_does_not_replace_the_one_we_have() {
1769        let state = state();
1770        state.ingest(Vec::new(), Some("c-1".into()));
1771        state.ingest(Vec::new(), None);
1772        state.ingest(Vec::new(), Some(String::new()));
1773
1774        assert_eq!(state.lock().cursor.as_deref(), Some("c-1"));
1775    }
1776
1777    #[test]
1778    fn events_are_drained_once_and_in_order() {
1779        let state = state();
1780        state.ingest(
1781            queued(vec![
1782                LobbyEvent::MemberLeft {
1783                    lobby_id: "lobby-1".into(),
1784                    user_id: "user-b".into(),
1785                },
1786                LobbyEvent::LobbyClosed {
1787                    lobby_id: "lobby-1".into(),
1788                },
1789            ]),
1790            None,
1791        );
1792
1793        let first = state.take_events();
1794        assert_eq!(first.len(), 2);
1795        assert_eq!(first[0].lobby_id(), Some("lobby-1"));
1796        assert!(matches!(first[1], LobbyEvent::LobbyClosed { .. }));
1797        assert!(state.take_events().is_empty());
1798    }
1799
1800    #[test]
1801    fn the_queue_is_bounded_and_drops_the_oldest_events() {
1802        let state = state();
1803        for index in 0..MAX_QUEUED_EVENTS + 10 {
1804            state.ingest(
1805                queued(vec![LobbyEvent::MemberLeft {
1806                    lobby_id: format!("lobby-{index}"),
1807                    user_id: "user-b".into(),
1808                }]),
1809                None,
1810            );
1811        }
1812
1813        let drained = state.take_events();
1814        assert_eq!(drained.len(), MAX_QUEUED_EVENTS);
1815        assert_eq!(drained[0].lobby_id(), Some("lobby-10"));
1816    }
1817
1818    #[test]
1819    fn rendering_the_queue_does_not_drain_it_and_discard_takes_exactly_what_was_rendered() {
1820        let state = state();
1821        state.ingest(
1822            queued(vec![LobbyEvent::MemberLeft {
1823                lobby_id: "lobby-1".into(),
1824                user_id: "user-b".into(),
1825            }]),
1826            None,
1827        );
1828
1829        let (rendered, through) = state.events_json();
1830        assert_eq!(through, Some(0));
1831        assert_eq!(
1832            rendered,
1833            r#"{"events":[{"type":"member_left","lobby_id":"lobby-1","user_id":"user-b"}]}"#
1834        );
1835
1836        state.ingest(
1837            queued(vec![LobbyEvent::LobbyClosed {
1838                lobby_id: "lobby-1".into(),
1839            }]),
1840            None,
1841        );
1842        state.discard(through.expect("a rendered event"));
1843
1844        let left = state.take_events();
1845        assert_eq!(left.len(), 1, "an event queued after the render survives");
1846        assert!(matches!(left[0], LobbyEvent::LobbyClosed { .. }));
1847    }
1848
1849    #[test]
1850    fn discarding_drops_what_was_rendered_even_when_the_queue_evicted_in_between() {
1851        let state = state();
1852        state.ingest(
1853            queued(vec![LobbyEvent::MemberLeft {
1854                lobby_id: "rendered".into(),
1855                user_id: "user-b".into(),
1856            }]),
1857            None,
1858        );
1859        let (_, through) = state.events_json();
1860
1861        for index in 0..MAX_QUEUED_EVENTS {
1862            state.ingest(
1863                queued(vec![LobbyEvent::MemberLeft {
1864                    lobby_id: format!("later-{index}"),
1865                    user_id: "user-b".into(),
1866                }]),
1867                None,
1868            );
1869        }
1870        state.discard(through.expect("a rendered event"));
1871
1872        let left = state.take_events();
1873        assert_eq!(
1874            left.len(),
1875            MAX_QUEUED_EVENTS,
1876            "discard drops the events it rendered, never the ones that replaced them"
1877        );
1878        assert!(left
1879            .iter()
1880            .all(|event| event.lobby_id() != Some("rendered")));
1881    }
1882
1883    #[test]
1884    fn an_event_arcane_sends_twice_is_delivered_once() {
1885        let state = state();
1886        let repeat = || {
1887            vec![Incoming {
1888                id: Some("event-1".into()),
1889                event: LobbyEvent::MemberLeft {
1890                    lobby_id: "lobby-1".into(),
1891                    user_id: "user-b".into(),
1892                },
1893            }]
1894        };
1895
1896        state.ingest(repeat(), Some("c-1".into()));
1897        state.ingest(repeat(), Some("c-1".into()));
1898        state.ingest(repeat(), None);
1899
1900        assert_eq!(
1901            state.take_events().len(),
1902            1,
1903            "a replayed id is dropped, whatever the cursor did"
1904        );
1905    }
1906
1907    #[test]
1908    fn an_event_without_an_id_is_still_delivered() {
1909        let state = state();
1910        state.ingest(
1911            queued(vec![LobbyEvent::LobbyClosed {
1912                lobby_id: "lobby-1".into(),
1913            }]),
1914            None,
1915        );
1916        state.ingest(
1917            queued(vec![LobbyEvent::LobbyClosed {
1918                lobby_id: "lobby-1".into(),
1919            }]),
1920            None,
1921        );
1922
1923        assert_eq!(state.take_events().len(), 2);
1924    }
1925
1926    #[test]
1927    fn the_lobby_json_keeps_the_documented_field_order() {
1928        let rendered = to_json(&parse_lobby(LOBBY));
1929
1930        assert_eq!(
1931            rendered,
1932            r#"{"lobby_id":"lobby-1","join_code":"K7P3QX","host_user_id":"user-host","host_payload":"dWRwOi8vMTAuMC4wLjE6Nzc3Nw==","members":[{"user_id":"user-host","pseudo":"Ada","payload":"dWRwOi8vMTAuMC4wLjE6Nzc3Nw=="},{"user_id":"user-b","pseudo":"Bo","payload":""}],"max_players":4,"metadata":{}}"#
1933        );
1934    }
1935
1936    #[test]
1937    fn every_event_renders_with_its_type_first() {
1938        let rendered = render_events(
1939            [
1940                LobbyEvent::Invite {
1941                    lobby_id: "lobby-1".into(),
1942                    join_code: None,
1943                    from_user_id: "user-a".into(),
1944                    pseudo: "Ada".into(),
1945                },
1946                LobbyEvent::MemberJoined {
1947                    lobby_id: "lobby-1".into(),
1948                    user_id: "user-b".into(),
1949                    pseudo: "Bo".into(),
1950                    payload: b"hi".to_vec(),
1951                },
1952            ]
1953            .iter(),
1954        );
1955
1956        let parsed: serde_json::Value = serde_json::from_str(&rendered).expect("json");
1957        assert_eq!(parsed["events"][0]["type"], "invite");
1958        assert_eq!(parsed["events"][0]["join_code"], serde_json::Value::Null);
1959        assert_eq!(parsed["events"][1]["type"], "member_joined");
1960        assert_eq!(parsed["events"][1]["payload"], "aGk=");
1961        assert!(rendered.starts_with(r#"{"events":[{"type":"invite","lobby_id":"lobby-1""#));
1962    }
1963
1964    #[test]
1965    fn an_empty_queue_still_renders_a_valid_document() {
1966        let (rendered, through) = state().events_json();
1967        assert_eq!(rendered, r#"{"events":[]}"#);
1968        assert_eq!(through, None);
1969    }
1970
1971    #[test]
1972    fn a_dropped_answer_becomes_a_resync_event() {
1973        let wire: WireEvents = serde_json::from_str(
1974            r#"{"events":[{"id":"1","type":"lobby_closed","lobby_id":"lobby-1"}],
1975                "cursor":"c-2","dropped":true}"#,
1976        )
1977        .expect("wire events");
1978
1979        assert!(wire.dropped);
1980        assert_eq!(
1981            render_events([LobbyEvent::Resync].iter()),
1982            r#"{"events":[{"type":"resync"}]}"#
1983        );
1984        assert_eq!(LobbyEvent::Resync.lobby_id(), None);
1985    }
1986
1987    #[test]
1988    fn an_inbound_payload_larger_than_the_limit_is_refused() {
1989        let oversized = BASE64.encode(vec![7u8; MAX_LOBBY_PAYLOAD_LEN + 1]);
1990
1991        let err = decode_payload(Some(&oversized), "host_payload").expect_err("too long");
1992        assert_eq!(err.code(), "arcane_unavailable");
1993        assert!(err
1994            .context()
1995            .iter()
1996            .any(|(k, v)| k == "field" && v == "host_payload"));
1997
1998        assert!(
1999            decode_payload(Some(&BASE64.encode(vec![7u8; MAX_LOBBY_PAYLOAD_LEN])), "p").is_ok()
2000        );
2001        assert!(decode_payload_arg(&oversized).is_none());
2002    }
2003
2004    #[test]
2005    fn an_oversized_payload_fails_a_lobby_and_empties_an_event() {
2006        let oversized = BASE64.encode(vec![7u8; MAX_LOBBY_PAYLOAD_LEN + 1]);
2007
2008        let wire: WireLobby = serde_json::from_str(&format!(
2009            r#"{{"lobby_id":"lobby-1","host_user_id":"u","host_payload":"{oversized}",
2010                 "members":[]}}"#
2011        ))
2012        .expect("wire lobby");
2013        assert_eq!(
2014            map_lobby(wire).expect_err("oversized").code(),
2015            "arcane_unavailable"
2016        );
2017
2018        let events = parse_events(&format!(
2019            r#"{{"events":[{{"type":"member_joined","lobby_id":"lobby-1","user_id":"user-b",
2020                 "pseudo":"Bo","payload":"{oversized}"}}]}}"#
2021        ));
2022        assert_eq!(
2023            events[0],
2024            LobbyEvent::MemberJoined {
2025                lobby_id: "lobby-1".into(),
2026                user_id: "user-b".into(),
2027                pseudo: "Bo".into(),
2028                payload: Vec::new(),
2029            }
2030        );
2031    }
2032
2033    #[test]
2034    fn a_lobby_without_an_id_is_not_a_lobby() {
2035        let wire: WireLobby = serde_json::from_str(r#"{}"#).expect("wire lobby");
2036
2037        let err = map_lobby(wire).expect_err("no lobby_id");
2038        assert_eq!(err.code(), "arcane_unavailable");
2039        assert!(err
2040            .context()
2041            .iter()
2042            .any(|(k, v)| k == "field" && v == "lobby_id"));
2043    }
2044
2045    #[test]
2046    fn metadata_is_checked_before_any_call() {
2047        let ok = metadata_arg([("mode", "coop"), ("map_2", "harbor")].into_iter()).expect("valid");
2048        assert_eq!(ok.get("mode").map(String::as_str), Some("coop"));
2049
2050        for key in [
2051            "",
2052            "Mode",
2053            "game-mode",
2054            "a b",
2055            &"k".repeat(MAX_LOBBY_METADATA_KEY_LEN + 1),
2056        ] {
2057            let err = metadata_arg([(key, "v")].into_iter()).expect_err(key);
2058            assert_eq!(err.code(), "invalid_argument");
2059        }
2060
2061        let long = "é".repeat(MAX_LOBBY_METADATA_VALUE_LEN + 1);
2062        assert_eq!(
2063            metadata_arg([("mode", long.as_str())].into_iter())
2064                .expect_err("too long")
2065                .code(),
2066            "invalid_argument"
2067        );
2068        let fits = "é".repeat(MAX_LOBBY_METADATA_VALUE_LEN);
2069        assert!(metadata_arg([("mode", fits.as_str())].into_iter()).is_ok());
2070
2071        let keys: Vec<String> = (0..=MAX_LOBBY_METADATA_PAIRS)
2072            .map(|i| format!("k{i}"))
2073            .collect();
2074        let pairs = keys.iter().map(|k| (k.as_str(), "v"));
2075        assert_eq!(
2076            metadata_arg(pairs).expect_err("too many").code(),
2077            "invalid_argument"
2078        );
2079    }
2080
2081    #[test]
2082    fn a_search_path_carries_every_filter_encoded() {
2083        let query = LobbyQuery {
2084            filters: vec![
2085                ("mode".into(), "co op".into()),
2086                ("map".into(), "a&b".into()),
2087            ],
2088            has_free_slot: false,
2089            limit: 5,
2090        };
2091        let filters = metadata_arg(query.filters.iter().map(|(k, v)| (k.as_str(), v.as_str())))
2092            .expect("filters");
2093
2094        assert_eq!(
2095            search_path("game-1", &query, &filters),
2096            format!(
2097                "{GAMES_PATH_PREFIX}/game-1/lobbies/search?has_free_slot=false&limit=5&meta.map=a%26b&meta.mode=co%20op"
2098            )
2099        );
2100    }
2101
2102    #[test]
2103    fn a_lobby_carries_its_metadata_and_defaults_to_none() {
2104        let lobby = parse_lobby(LOBBY);
2105        assert!(lobby.metadata.is_empty());
2106
2107        let lobby = parse_lobby(
2108            r#"{"lobby_id":"lobby-1","host_user_id":"u","visibility":"public",
2109                "max_players":4,"members":[],"metadata":{"mode":"coop"}}"#,
2110        );
2111        assert_eq!(lobby.metadata.get("mode").map(String::as_str), Some("coop"));
2112    }
2113
2114    #[test]
2115    fn search_results_map_and_render_back_to_json() {
2116        let wire: WireSearch = serde_json::from_str(
2117            r#"{"lobbies":[
2118                {"lobby_id":"lobby-1","host_user_id":"u1","host_pseudo":"Ada","members":1,
2119                 "max_players":4,"metadata":{"mode":"coop"},"host_is_friend":true},
2120                {"host_user_id":"u2"}
2121            ]}"#,
2122        )
2123        .expect("wire search");
2124        let lobbies: Vec<LobbySummary> = wire.lobbies.into_iter().filter_map(map_summary).collect();
2125
2126        assert_eq!(lobbies.len(), 1);
2127        assert_eq!(lobbies[0].host_pseudo, "Ada");
2128        assert!(lobbies[0].host_is_friend);
2129
2130        let rendered: serde_json::Value =
2131            serde_json::from_str(&summaries_to_json(&lobbies)).expect("json");
2132        assert_eq!(rendered["lobbies"][0]["lobby_id"], "lobby-1");
2133        assert_eq!(rendered["lobbies"][0]["metadata"]["mode"], "coop");
2134        assert_eq!(rendered["lobbies"][0]["members"], 1);
2135    }
2136
2137    #[test]
2138    fn a_lobby_updated_event_carries_the_new_metadata() {
2139        let events = parse_events(
2140            r#"{"events":[{"type":"lobby_updated","lobby_id":"lobby-1","metadata":{"map":"docks"}}]}"#,
2141        );
2142
2143        let mut metadata = BTreeMap::new();
2144        metadata.insert("map".to_string(), "docks".to_string());
2145        assert_eq!(
2146            events,
2147            vec![LobbyEvent::LobbyUpdated {
2148                lobby_id: "lobby-1".into(),
2149                metadata
2150            }]
2151        );
2152
2153        let rendered: serde_json::Value =
2154            serde_json::from_str(&render_events(events.iter())).expect("json");
2155        assert_eq!(rendered["events"][0]["type"], "lobby_updated");
2156        assert_eq!(rendered["events"][0]["metadata"]["map"], "docks");
2157    }
2158}