use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
TicketMissing,
TicketExpired,
TicketInvalid,
DeviceMismatch,
ClockRollback,
NotOwned,
NetworkRequired,
NotAuthenticated,
ArcaneUnavailable,
FeatureUnavailable,
UnknownAchievement,
LobbyNotFound,
LobbyFull,
LobbyClosed,
NotFriends,
NotHost,
UserNotFound,
AlreadyFriends,
NotInLobby,
NoOpenSession,
RateLimited,
MissingGameId,
InvalidGameId,
InvalidArgument,
AmbiguousSession,
NotInitialized,
Internal,
}
impl ErrorCode {
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())
}
}
#[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(),
}
}
#[must_use]
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
#[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
}
pub fn code(&self) -> &'static str {
self.code.as_str()
}
pub fn error_code(&self) -> ErrorCode {
self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn context(&self) -> &[(String, String)] {
&self.context
}
pub fn is_retryable(&self) -> bool {
matches!(
self.code,
ErrorCode::TicketMissing
| ErrorCode::TicketExpired
| ErrorCode::NetworkRequired
| ErrorCode::NotAuthenticated
| ErrorCode::ArcaneUnavailable
| ErrorCode::RateLimited
| ErrorCode::NoOpenSession
)
}
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()
}
pub(crate) fn should_refresh_via_desktop(&self) -> bool {
matches!(
self.code,
ErrorCode::TicketMissing | ErrorCode::TicketExpired
)
}
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 {
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());
}
}