1use std::fmt;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ErrorCode {
13 TicketMissing,
15 TicketExpired,
17 TicketInvalid,
19 DeviceMismatch,
21 ClockRollback,
23 NotOwned,
25 NetworkRequired,
27 NotAuthenticated,
29 ArcaneUnavailable,
31 FeatureUnavailable,
34 UnknownAchievement,
37 LobbyNotFound,
39 LobbyFull,
41 LobbyClosed,
43 NotFriends,
46 NotHost,
48 UserNotFound,
50 AlreadyFriends,
53 NotInLobby,
55 NoOpenSession,
58 RateLimited,
61 MissingGameId,
64 InvalidGameId,
66 InvalidArgument,
69 AmbiguousSession,
72 NotInitialized,
74 Internal,
76}
77
78impl ErrorCode {
79 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#[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 #[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 #[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 pub fn code(&self) -> &'static str {
178 self.code.as_str()
179 }
180
181 pub fn error_code(&self) -> ErrorCode {
183 self.code
184 }
185
186 pub fn message(&self) -> &str {
188 &self.message
189 }
190
191 pub fn hint(&self) -> Option<&str> {
193 self.hint.as_deref()
194 }
195
196 pub fn context(&self) -> &[(String, String)] {
198 &self.context
199 }
200
201 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 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 pub(crate) fn should_refresh_via_desktop(&self) -> bool {
236 matches!(
237 self.code,
238 ErrorCode::TicketMissing | ErrorCode::TicketExpired
239 )
240 }
241
242 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 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}