Skip to main content

arcane_sdk/
error.rs

1//! Structured SDK errors.
2//!
3//! Every failure carries a stable machine-readable [`ErrorCode`], a player-facing
4//! `message`, a developer-facing `hint` (what to actually do about it), and a
5//! `context` key/value list naming the values that were compared or the paths
6//! that were read. The goal is that a single log line is enough to debug.
7
8use std::fmt;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ErrorCode {
13    /// No ticket cache, or the cached ticket is empty while DRM is on.
14    TicketMissing,
15    /// The ticket JWT is past `exp` (beyond clock skew).
16    TicketExpired,
17    /// Bad JWT, missing/invalid JWKS, wrong title, or `own=false`.
18    TicketInvalid,
19    /// The ticket is bound to a different machine.
20    DeviceMismatch,
21    /// The system clock is earlier than the ticket or the last-seen time.
22    ClockRollback,
23    /// Cloud confirmed the signed-in account does not own this title.
24    NotOwned,
25    /// No usable offline ticket, and a refresh needs the network.
26    NetworkRequired,
27    /// Arcane desktop is reachable but nobody is signed in.
28    NotAuthenticated,
29    /// Could not reach or launch the Arcane desktop loopback server.
30    ArcaneUnavailable,
31    /// The Arcane desktop app does not know this route yet — it predates the
32    /// feature the SDK asked for.
33    FeatureUnavailable,
34    /// The Arcane desktop app knows the route but not the achievement the game
35    /// asked to unlock.
36    UnknownAchievement,
37    /// No open lobby with that id or join code.
38    LobbyNotFound,
39    /// The lobby already holds `max_players`.
40    LobbyFull,
41    /// The lobby was closed by its host, or its host's session expired.
42    LobbyClosed,
43    /// The lobby is visible to the host's friends only, and this player is not
44    /// one of them.
45    NotFriends,
46    /// Only the lobby's host may do this — change its metadata or close it.
47    NotHost,
48    /// No Arcane account has that id.
49    UserNotFound,
50    /// You are already friends with that player, or a friend request between
51    /// you is already pending either way.
52    AlreadyFriends,
53    /// The coop network was asked for a lobby this player is not a member of.
54    NotInLobby,
55    /// The Arcane desktop app has no play session open for this game, so it
56    /// will not open the coop network.
57    NoOpenSession,
58    /// Arcane refused the call because this player made too many of them;
59    /// wait and try again.
60    RateLimited,
61    /// `ARCANE_GAME_ID` is unset or empty — the game was not started by Arcane
62    /// Powered, and no developer override is in place.
63    MissingGameId,
64    /// The game id in `ARCANE_GAME_ID` is oversized or has forbidden characters.
65    InvalidGameId,
66    /// An argument other than the game id is empty, oversized, or has
67    /// forbidden characters.
68    InvalidArgument,
69    /// Several accounts hold a ticket for this title and Arcane has not recorded
70    /// which one is signed in.
71    AmbiguousSession,
72    /// A client accessor was used before a successful init (C ABI only).
73    NotInitialized,
74    /// Filesystem / path failure.
75    Internal,
76}
77
78impl ErrorCode {
79    /// Stable wire string. This is the public contract — never change these.
80    pub fn as_str(&self) -> &'static str {
81        match self {
82            Self::TicketMissing => "ticket_missing",
83            Self::TicketExpired => "ticket_expired",
84            Self::TicketInvalid => "ticket_invalid",
85            Self::DeviceMismatch => "device_mismatch",
86            Self::ClockRollback => "clock_rollback",
87            Self::NotOwned => "not_owned",
88            Self::NetworkRequired => "network_required",
89            Self::NotAuthenticated => "not_authenticated",
90            Self::ArcaneUnavailable => "arcane_unavailable",
91            Self::FeatureUnavailable => "feature_unavailable",
92            Self::UnknownAchievement => "unknown_achievement",
93            Self::LobbyNotFound => "lobby_not_found",
94            Self::LobbyFull => "lobby_full",
95            Self::LobbyClosed => "lobby_closed",
96            Self::NotFriends => "not_friends",
97            Self::NotHost => "not_host",
98            Self::UserNotFound => "user_not_found",
99            Self::AlreadyFriends => "already_friends",
100            Self::NotInLobby => "not_in_lobby",
101            Self::NoOpenSession => "no_open_session",
102            Self::RateLimited => "rate_limited",
103            Self::MissingGameId => "missing_game_id",
104            Self::InvalidGameId => "invalid_game_id",
105            Self::InvalidArgument => "invalid_argument",
106            Self::AmbiguousSession => "ambiguous_session",
107            Self::NotInitialized => "not_initialized",
108            Self::Internal => "internal",
109        }
110    }
111}
112
113impl fmt::Display for ErrorCode {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(self.as_str())
116    }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum OwnershipStatus {
121    Owned,
122    DrmDisabled,
123}
124
125impl OwnershipStatus {
126    pub fn as_str(&self) -> &'static str {
127        match self {
128            Self::Owned => "owned",
129            Self::DrmDisabled => "drm_disabled",
130        }
131    }
132}
133
134impl fmt::Display for OwnershipStatus {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.write_str(self.as_str())
137    }
138}
139
140/// A single SDK failure.
141///
142/// Match on [`SdkError::code`] — it is the stable contract. `message` is safe to
143/// show a player; `hint` and `context` are for the developer's logs.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct SdkError {
146    code: ErrorCode,
147    message: String,
148    hint: Option<String>,
149    context: Vec<(String, String)>,
150}
151
152impl SdkError {
153    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
154        Self {
155            code,
156            message: message.into(),
157            hint: None,
158            context: Vec::new(),
159        }
160    }
161
162    /// Attach the developer-facing "what to do about it" line.
163    #[must_use]
164    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
165        self.hint = Some(hint.into());
166        self
167    }
168
169    /// Attach a named value that was compared, read, or resolved.
170    #[must_use]
171    pub fn with_context(mut self, key: impl Into<String>, value: impl fmt::Display) -> Self {
172        self.context.push((key.into(), value.to_string()));
173        self
174    }
175
176    /// Stable machine-readable code, e.g. `"not_owned"`.
177    pub fn code(&self) -> &'static str {
178        self.code.as_str()
179    }
180
181    /// Typed form of [`SdkError::code`], for exhaustive matching in Rust.
182    pub fn error_code(&self) -> ErrorCode {
183        self.code
184    }
185
186    /// Player-facing explanation, without developer detail.
187    pub fn message(&self) -> &str {
188        &self.message
189    }
190
191    /// Developer-facing next step, when one exists.
192    pub fn hint(&self) -> Option<&str> {
193        self.hint.as_deref()
194    }
195
196    /// Named values involved in the failure (compared ids, resolved paths, ports).
197    pub fn context(&self) -> &[(String, String)] {
198        &self.context
199    }
200
201    /// Whether retrying the same call could succeed once an external condition
202    /// changes (network comes back, Arcane opens, the player signs in) without
203    /// the developer changing any code.
204    pub fn is_retryable(&self) -> bool {
205        matches!(
206            self.code,
207            ErrorCode::TicketMissing
208                | ErrorCode::TicketExpired
209                | ErrorCode::NetworkRequired
210                | ErrorCode::NotAuthenticated
211                | ErrorCode::ArcaneUnavailable
212                | ErrorCode::RateLimited
213                | ErrorCode::NoOpenSession
214        )
215    }
216
217    /// Machine-readable rendering for engines that want to surface full detail.
218    pub fn to_json(&self) -> String {
219        let context: serde_json::Map<String, serde_json::Value> = self
220            .context
221            .iter()
222            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
223            .collect();
224        let value = serde_json::json!({
225            "code": self.code.as_str(),
226            "message": self.message,
227            "hint": self.hint,
228            "retryable": self.is_retryable(),
229            "context": context,
230        });
231        value.to_string()
232    }
233
234    /// Whether init should attempt a desktop ownership refresh for this error.
235    pub(crate) fn should_refresh_via_desktop(&self) -> bool {
236        matches!(
237            self.code,
238            ErrorCode::TicketMissing | ErrorCode::TicketExpired
239        )
240    }
241
242    /// Whether this is the desktop app telling us *it* could not reach the
243    /// cloud — the one refresh failure the cached ticket is allowed to answer.
244    ///
245    /// Every other failure is a verdict, not a gap: `not_owned` and
246    /// `not_authenticated` are answers, and `arcane_unavailable` means the
247    /// desktop never spoke at all, which is not a state a game may start in.
248    pub(crate) fn is_cloud_unreachable(&self) -> bool {
249        matches!(self.code, ErrorCode::NetworkRequired)
250    }
251
252    pub(crate) fn ticket_missing(message: impl Into<String>) -> Self {
253        Self::new(ErrorCode::TicketMissing, message)
254    }
255
256    pub(crate) fn ticket_expired(message: impl Into<String>) -> Self {
257        Self::new(ErrorCode::TicketExpired, message)
258    }
259
260    pub(crate) fn ticket_invalid(message: impl Into<String>) -> Self {
261        Self::new(ErrorCode::TicketInvalid, message)
262    }
263
264    pub(crate) fn device_mismatch(message: impl Into<String>) -> Self {
265        Self::new(ErrorCode::DeviceMismatch, message)
266    }
267
268    pub(crate) fn clock_rollback(message: impl Into<String>) -> Self {
269        Self::new(ErrorCode::ClockRollback, message)
270    }
271
272    pub(crate) fn not_owned(message: impl Into<String>) -> Self {
273        Self::new(ErrorCode::NotOwned, message)
274    }
275
276    pub(crate) fn network_required(message: impl Into<String>) -> Self {
277        Self::new(ErrorCode::NetworkRequired, message)
278    }
279
280    pub(crate) fn not_authenticated(message: impl Into<String>) -> Self {
281        Self::new(ErrorCode::NotAuthenticated, message)
282    }
283
284    pub(crate) fn arcane_unavailable(message: impl Into<String>) -> Self {
285        Self::new(ErrorCode::ArcaneUnavailable, message)
286    }
287
288    pub(crate) fn feature_unavailable(message: impl Into<String>) -> Self {
289        Self::new(ErrorCode::FeatureUnavailable, message)
290    }
291
292    pub(crate) fn unknown_achievement(message: impl Into<String>) -> Self {
293        Self::new(ErrorCode::UnknownAchievement, message)
294    }
295
296    pub(crate) fn lobby_not_found(message: impl Into<String>) -> Self {
297        Self::new(ErrorCode::LobbyNotFound, message)
298    }
299
300    pub(crate) fn lobby_full(message: impl Into<String>) -> Self {
301        Self::new(ErrorCode::LobbyFull, message)
302    }
303
304    pub(crate) fn lobby_closed(message: impl Into<String>) -> Self {
305        Self::new(ErrorCode::LobbyClosed, message)
306    }
307
308    pub(crate) fn not_friends(message: impl Into<String>) -> Self {
309        Self::new(ErrorCode::NotFriends, message)
310    }
311
312    pub(crate) fn not_host(message: impl Into<String>) -> Self {
313        Self::new(ErrorCode::NotHost, message)
314    }
315
316    pub(crate) fn user_not_found(message: impl Into<String>) -> Self {
317        Self::new(ErrorCode::UserNotFound, message)
318    }
319
320    pub(crate) fn already_friends(message: impl Into<String>) -> Self {
321        Self::new(ErrorCode::AlreadyFriends, message)
322    }
323
324    pub(crate) fn not_in_lobby(message: impl Into<String>) -> Self {
325        Self::new(ErrorCode::NotInLobby, message)
326    }
327
328    pub(crate) fn no_open_session(message: impl Into<String>) -> Self {
329        Self::new(ErrorCode::NoOpenSession, message)
330    }
331
332    pub(crate) fn rate_limited(message: impl Into<String>) -> Self {
333        Self::new(ErrorCode::RateLimited, message)
334    }
335
336    pub(crate) fn missing_game_id(message: impl Into<String>) -> Self {
337        Self::new(ErrorCode::MissingGameId, message)
338    }
339
340    pub(crate) fn invalid_game_id(message: impl Into<String>) -> Self {
341        Self::new(ErrorCode::InvalidGameId, message)
342    }
343
344    pub(crate) fn invalid_argument(message: impl Into<String>) -> Self {
345        Self::new(ErrorCode::InvalidArgument, message)
346    }
347
348    pub(crate) fn ambiguous_session(message: impl Into<String>) -> Self {
349        Self::new(ErrorCode::AmbiguousSession, message)
350    }
351
352    pub(crate) fn not_initialized(message: impl Into<String>) -> Self {
353        Self::new(ErrorCode::NotInitialized, message)
354    }
355
356    pub(crate) fn internal(message: impl Into<String>) -> Self {
357        Self::new(ErrorCode::Internal, message)
358    }
359}
360
361impl fmt::Display for SdkError {
362    /// `code: message — hint (key=value, key=value)`
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        write!(f, "{}: {}", self.code, self.message)?;
365        if let Some(hint) = &self.hint {
366            write!(f, " — {hint}")?;
367        }
368        if !self.context.is_empty() {
369            f.write_str(" (")?;
370            for (i, (key, value)) in self.context.iter().enumerate() {
371                if i > 0 {
372                    f.write_str(", ")?;
373                }
374                write!(f, "{key}={value}")?;
375            }
376            f.write_str(")")?;
377        }
378        Ok(())
379    }
380}
381
382impl std::error::Error for SdkError {}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn display_includes_code_message_hint_and_context() {
390        let err = SdkError::ticket_invalid("Ticket was issued for a different title.")
391            .with_hint("Check the game id in your build.")
392            .with_context("expected", "game-a")
393            .with_context("ticket_gid", "game-b");
394
395        assert_eq!(
396            err.to_string(),
397            "ticket_invalid: Ticket was issued for a different title. \
398             — Check the game id in your build. (expected=game-a, ticket_gid=game-b)"
399        );
400    }
401
402    #[test]
403    fn display_without_hint_or_context_is_just_code_and_message() {
404        let err = SdkError::not_owned("You do not own this game.");
405        assert_eq!(err.to_string(), "not_owned: You do not own this game.");
406    }
407
408    #[test]
409    fn json_carries_every_field() {
410        let err = SdkError::network_required("Connect to the internet once.")
411            .with_hint("Open Arcane while online.")
412            .with_context("port", 39284);
413
414        let parsed: serde_json::Value = serde_json::from_str(&err.to_json()).unwrap();
415        assert_eq!(parsed["code"], "network_required");
416        assert_eq!(parsed["message"], "Connect to the internet once.");
417        assert_eq!(parsed["hint"], "Open Arcane while online.");
418        assert_eq!(parsed["retryable"], true);
419        assert_eq!(parsed["context"]["port"], "39284");
420    }
421
422    #[test]
423    fn json_hint_is_null_when_absent() {
424        let parsed: serde_json::Value =
425            serde_json::from_str(&SdkError::internal("boom").to_json()).unwrap();
426        assert_eq!(parsed["hint"], serde_json::Value::Null);
427        assert_eq!(parsed["retryable"], false);
428    }
429
430    #[test]
431    fn only_externally_resolvable_failures_are_retryable() {
432        assert!(SdkError::network_required("x").is_retryable());
433        assert!(SdkError::arcane_unavailable("x").is_retryable());
434        assert!(SdkError::not_authenticated("x").is_retryable());
435        assert!(!SdkError::not_owned("x").is_retryable());
436        assert!(!SdkError::device_mismatch("x").is_retryable());
437        assert!(!SdkError::missing_game_id("x").is_retryable());
438        assert!(!SdkError::invalid_game_id("x").is_retryable());
439        assert!(!SdkError::invalid_argument("x").is_retryable());
440        assert!(!SdkError::feature_unavailable("x").is_retryable());
441        assert!(!SdkError::unknown_achievement("x").is_retryable());
442        assert!(!SdkError::lobby_not_found("x").is_retryable());
443        assert!(!SdkError::lobby_full("x").is_retryable());
444        assert!(!SdkError::lobby_closed("x").is_retryable());
445        assert!(!SdkError::not_friends("x").is_retryable());
446    }
447
448    #[test]
449    fn the_lobby_codes_are_stable() {
450        assert_eq!(SdkError::lobby_not_found("x").code(), "lobby_not_found");
451        assert_eq!(SdkError::lobby_full("x").code(), "lobby_full");
452        assert_eq!(SdkError::lobby_closed("x").code(), "lobby_closed");
453        assert_eq!(SdkError::not_friends("x").code(), "not_friends");
454    }
455
456    #[test]
457    fn feature_unavailable_is_a_stable_code() {
458        assert_eq!(
459            SdkError::feature_unavailable("x").code(),
460            "feature_unavailable"
461        );
462    }
463
464    #[test]
465    fn the_achievement_codes_are_stable() {
466        assert_eq!(
467            SdkError::unknown_achievement("x").code(),
468            "unknown_achievement"
469        );
470        assert_eq!(SdkError::invalid_argument("x").code(), "invalid_argument");
471        assert_eq!(SdkError::invalid_game_id("x").code(), "invalid_game_id");
472        assert_eq!(SdkError::missing_game_id("x").code(), "missing_game_id");
473    }
474
475    #[test]
476    fn only_ticket_gaps_trigger_a_desktop_refresh() {
477        assert!(SdkError::ticket_missing("x").should_refresh_via_desktop());
478        assert!(SdkError::ticket_expired("x").should_refresh_via_desktop());
479        assert!(!SdkError::ticket_invalid("x").should_refresh_via_desktop());
480        assert!(!SdkError::not_owned("x").should_refresh_via_desktop());
481    }
482}