arcane-sdk 0.15.0

Arcane Powered game SDK core (ownership tickets, DRM checks)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Structured SDK errors.
//!
//! Every failure carries a stable machine-readable [`ErrorCode`], a player-facing
//! `message`, a developer-facing `hint` (what to actually do about it), and a
//! `context` key/value list naming the values that were compared or the paths
//! that were read. The goal is that a single log line is enough to debug.

use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// No ticket cache, or the cached ticket is empty while DRM is on.
    TicketMissing,
    /// The ticket JWT is past `exp` (beyond clock skew).
    TicketExpired,
    /// Bad JWT, missing/invalid JWKS, wrong title, or `own=false`.
    TicketInvalid,
    /// The ticket is bound to a different machine.
    DeviceMismatch,
    /// The system clock is earlier than the ticket or the last-seen time.
    ClockRollback,
    /// Cloud confirmed the signed-in account does not own this title.
    NotOwned,
    /// No usable offline ticket, and a refresh needs the network.
    NetworkRequired,
    /// Arcane desktop is reachable but nobody is signed in.
    NotAuthenticated,
    /// Could not reach or launch the Arcane desktop loopback server.
    ArcaneUnavailable,
    /// The Arcane desktop app does not know this route yet — it predates the
    /// feature the SDK asked for.
    FeatureUnavailable,
    /// The Arcane desktop app knows the route but not the achievement the game
    /// asked to unlock.
    UnknownAchievement,
    /// No open lobby with that id or join code.
    LobbyNotFound,
    /// The lobby already holds `max_players`.
    LobbyFull,
    /// The lobby was closed by its host, or its host's session expired.
    LobbyClosed,
    /// The lobby is visible to the host's friends only, and this player is not
    /// one of them.
    NotFriends,
    /// Only the lobby's host may do this — change its metadata or close it.
    NotHost,
    /// No Arcane account has that id.
    UserNotFound,
    /// You are already friends with that player, or a friend request between
    /// you is already pending either way.
    AlreadyFriends,
    /// The coop network was asked for a lobby this player is not a member of.
    NotInLobby,
    /// The Arcane desktop app has no play session open for this game, so it
    /// will not open the coop network.
    NoOpenSession,
    /// Arcane refused the call because this player made too many of them;
    /// wait and try again.
    RateLimited,
    /// `ARCANE_GAME_ID` is unset or empty — the game was not started by Arcane
    /// Powered, and no developer override is in place.
    MissingGameId,
    /// The game id in `ARCANE_GAME_ID` is oversized or has forbidden characters.
    InvalidGameId,
    /// An argument other than the game id is empty, oversized, or has
    /// forbidden characters.
    InvalidArgument,
    /// Several accounts hold a ticket for this title and Arcane has not recorded
    /// which one is signed in.
    AmbiguousSession,
    /// A client accessor was used before a successful init (C ABI only).
    NotInitialized,
    /// Filesystem / path failure.
    Internal,
}

impl ErrorCode {
    /// Stable wire string. This is the public contract — never change these.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::TicketMissing => "ticket_missing",
            Self::TicketExpired => "ticket_expired",
            Self::TicketInvalid => "ticket_invalid",
            Self::DeviceMismatch => "device_mismatch",
            Self::ClockRollback => "clock_rollback",
            Self::NotOwned => "not_owned",
            Self::NetworkRequired => "network_required",
            Self::NotAuthenticated => "not_authenticated",
            Self::ArcaneUnavailable => "arcane_unavailable",
            Self::FeatureUnavailable => "feature_unavailable",
            Self::UnknownAchievement => "unknown_achievement",
            Self::LobbyNotFound => "lobby_not_found",
            Self::LobbyFull => "lobby_full",
            Self::LobbyClosed => "lobby_closed",
            Self::NotFriends => "not_friends",
            Self::NotHost => "not_host",
            Self::UserNotFound => "user_not_found",
            Self::AlreadyFriends => "already_friends",
            Self::NotInLobby => "not_in_lobby",
            Self::NoOpenSession => "no_open_session",
            Self::RateLimited => "rate_limited",
            Self::MissingGameId => "missing_game_id",
            Self::InvalidGameId => "invalid_game_id",
            Self::InvalidArgument => "invalid_argument",
            Self::AmbiguousSession => "ambiguous_session",
            Self::NotInitialized => "not_initialized",
            Self::Internal => "internal",
        }
    }
}

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

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OwnershipStatus {
    Owned,
    DrmDisabled,
}

impl OwnershipStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Owned => "owned",
            Self::DrmDisabled => "drm_disabled",
        }
    }
}

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

/// A single SDK failure.
///
/// Match on [`SdkError::code`] — it is the stable contract. `message` is safe to
/// show a player; `hint` and `context` are for the developer's logs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SdkError {
    code: ErrorCode,
    message: String,
    hint: Option<String>,
    context: Vec<(String, String)>,
}

impl SdkError {
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            hint: None,
            context: Vec::new(),
        }
    }

    /// Attach the developer-facing "what to do about it" line.
    #[must_use]
    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Attach a named value that was compared, read, or resolved.
    #[must_use]
    pub fn with_context(mut self, key: impl Into<String>, value: impl fmt::Display) -> Self {
        self.context.push((key.into(), value.to_string()));
        self
    }

    /// Stable machine-readable code, e.g. `"not_owned"`.
    pub fn code(&self) -> &'static str {
        self.code.as_str()
    }

    /// Typed form of [`SdkError::code`], for exhaustive matching in Rust.
    pub fn error_code(&self) -> ErrorCode {
        self.code
    }

    /// Player-facing explanation, without developer detail.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Developer-facing next step, when one exists.
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }

    /// Named values involved in the failure (compared ids, resolved paths, ports).
    pub fn context(&self) -> &[(String, String)] {
        &self.context
    }

    /// Whether retrying the same call could succeed once an external condition
    /// changes (network comes back, Arcane opens, the player signs in) without
    /// the developer changing any code.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self.code,
            ErrorCode::TicketMissing
                | ErrorCode::TicketExpired
                | ErrorCode::NetworkRequired
                | ErrorCode::NotAuthenticated
                | ErrorCode::ArcaneUnavailable
                | ErrorCode::RateLimited
                | ErrorCode::NoOpenSession
        )
    }

    /// Machine-readable rendering for engines that want to surface full detail.
    pub fn to_json(&self) -> String {
        let context: serde_json::Map<String, serde_json::Value> = self
            .context
            .iter()
            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
            .collect();
        let value = serde_json::json!({
            "code": self.code.as_str(),
            "message": self.message,
            "hint": self.hint,
            "retryable": self.is_retryable(),
            "context": context,
        });
        value.to_string()
    }

    /// Whether init should attempt a desktop ownership refresh for this error.
    pub(crate) fn should_refresh_via_desktop(&self) -> bool {
        matches!(
            self.code,
            ErrorCode::TicketMissing | ErrorCode::TicketExpired
        )
    }

    /// Whether this is the desktop app telling us *it* could not reach the
    /// cloud — the one refresh failure the cached ticket is allowed to answer.
    ///
    /// Every other failure is a verdict, not a gap: `not_owned` and
    /// `not_authenticated` are answers, and `arcane_unavailable` means the
    /// desktop never spoke at all, which is not a state a game may start in.
    pub(crate) fn is_cloud_unreachable(&self) -> bool {
        matches!(self.code, ErrorCode::NetworkRequired)
    }

    pub(crate) fn ticket_missing(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::TicketMissing, message)
    }

    pub(crate) fn ticket_expired(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::TicketExpired, message)
    }

    pub(crate) fn ticket_invalid(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::TicketInvalid, message)
    }

    pub(crate) fn device_mismatch(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::DeviceMismatch, message)
    }

    pub(crate) fn clock_rollback(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::ClockRollback, message)
    }

    pub(crate) fn not_owned(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotOwned, message)
    }

    pub(crate) fn network_required(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NetworkRequired, message)
    }

    pub(crate) fn not_authenticated(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotAuthenticated, message)
    }

    pub(crate) fn arcane_unavailable(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::ArcaneUnavailable, message)
    }

    pub(crate) fn feature_unavailable(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::FeatureUnavailable, message)
    }

    pub(crate) fn unknown_achievement(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::UnknownAchievement, message)
    }

    pub(crate) fn lobby_not_found(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::LobbyNotFound, message)
    }

    pub(crate) fn lobby_full(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::LobbyFull, message)
    }

    pub(crate) fn lobby_closed(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::LobbyClosed, message)
    }

    pub(crate) fn not_friends(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotFriends, message)
    }

    pub(crate) fn not_host(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotHost, message)
    }

    pub(crate) fn user_not_found(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::UserNotFound, message)
    }

    pub(crate) fn already_friends(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::AlreadyFriends, message)
    }

    pub(crate) fn not_in_lobby(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotInLobby, message)
    }

    pub(crate) fn no_open_session(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NoOpenSession, message)
    }

    pub(crate) fn rate_limited(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::RateLimited, message)
    }

    pub(crate) fn missing_game_id(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::MissingGameId, message)
    }

    pub(crate) fn invalid_game_id(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidGameId, message)
    }

    pub(crate) fn invalid_argument(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::InvalidArgument, message)
    }

    pub(crate) fn ambiguous_session(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::AmbiguousSession, message)
    }

    pub(crate) fn not_initialized(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::NotInitialized, message)
    }

    pub(crate) fn internal(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::Internal, message)
    }
}

impl fmt::Display for SdkError {
    /// `code: message — hint (key=value, key=value)`
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code, self.message)?;
        if let Some(hint) = &self.hint {
            write!(f, " — {hint}")?;
        }
        if !self.context.is_empty() {
            f.write_str(" (")?;
            for (i, (key, value)) in self.context.iter().enumerate() {
                if i > 0 {
                    f.write_str(", ")?;
                }
                write!(f, "{key}={value}")?;
            }
            f.write_str(")")?;
        }
        Ok(())
    }
}

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

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

    #[test]
    fn display_includes_code_message_hint_and_context() {
        let err = SdkError::ticket_invalid("Ticket was issued for a different title.")
            .with_hint("Check the game id in your build.")
            .with_context("expected", "game-a")
            .with_context("ticket_gid", "game-b");

        assert_eq!(
            err.to_string(),
            "ticket_invalid: Ticket was issued for a different title. \
             — Check the game id in your build. (expected=game-a, ticket_gid=game-b)"
        );
    }

    #[test]
    fn display_without_hint_or_context_is_just_code_and_message() {
        let err = SdkError::not_owned("You do not own this game.");
        assert_eq!(err.to_string(), "not_owned: You do not own this game.");
    }

    #[test]
    fn json_carries_every_field() {
        let err = SdkError::network_required("Connect to the internet once.")
            .with_hint("Open Arcane while online.")
            .with_context("port", 39284);

        let parsed: serde_json::Value = serde_json::from_str(&err.to_json()).unwrap();
        assert_eq!(parsed["code"], "network_required");
        assert_eq!(parsed["message"], "Connect to the internet once.");
        assert_eq!(parsed["hint"], "Open Arcane while online.");
        assert_eq!(parsed["retryable"], true);
        assert_eq!(parsed["context"]["port"], "39284");
    }

    #[test]
    fn json_hint_is_null_when_absent() {
        let parsed: serde_json::Value =
            serde_json::from_str(&SdkError::internal("boom").to_json()).unwrap();
        assert_eq!(parsed["hint"], serde_json::Value::Null);
        assert_eq!(parsed["retryable"], false);
    }

    #[test]
    fn only_externally_resolvable_failures_are_retryable() {
        assert!(SdkError::network_required("x").is_retryable());
        assert!(SdkError::arcane_unavailable("x").is_retryable());
        assert!(SdkError::not_authenticated("x").is_retryable());
        assert!(!SdkError::not_owned("x").is_retryable());
        assert!(!SdkError::device_mismatch("x").is_retryable());
        assert!(!SdkError::missing_game_id("x").is_retryable());
        assert!(!SdkError::invalid_game_id("x").is_retryable());
        assert!(!SdkError::invalid_argument("x").is_retryable());
        assert!(!SdkError::feature_unavailable("x").is_retryable());
        assert!(!SdkError::unknown_achievement("x").is_retryable());
        assert!(!SdkError::lobby_not_found("x").is_retryable());
        assert!(!SdkError::lobby_full("x").is_retryable());
        assert!(!SdkError::lobby_closed("x").is_retryable());
        assert!(!SdkError::not_friends("x").is_retryable());
    }

    #[test]
    fn the_lobby_codes_are_stable() {
        assert_eq!(SdkError::lobby_not_found("x").code(), "lobby_not_found");
        assert_eq!(SdkError::lobby_full("x").code(), "lobby_full");
        assert_eq!(SdkError::lobby_closed("x").code(), "lobby_closed");
        assert_eq!(SdkError::not_friends("x").code(), "not_friends");
    }

    #[test]
    fn feature_unavailable_is_a_stable_code() {
        assert_eq!(
            SdkError::feature_unavailable("x").code(),
            "feature_unavailable"
        );
    }

    #[test]
    fn the_achievement_codes_are_stable() {
        assert_eq!(
            SdkError::unknown_achievement("x").code(),
            "unknown_achievement"
        );
        assert_eq!(SdkError::invalid_argument("x").code(), "invalid_argument");
        assert_eq!(SdkError::invalid_game_id("x").code(), "invalid_game_id");
        assert_eq!(SdkError::missing_game_id("x").code(), "missing_game_id");
    }

    #[test]
    fn only_ticket_gaps_trigger_a_desktop_refresh() {
        assert!(SdkError::ticket_missing("x").should_refresh_via_desktop());
        assert!(SdkError::ticket_expired("x").should_refresh_via_desktop());
        assert!(!SdkError::ticket_invalid("x").should_refresh_via_desktop());
        assert!(!SdkError::not_owned("x").should_refresh_via_desktop());
    }
}