steam-user 0.2.7

Steam User web client for Rust - HTTP-based Steam Community interactions
Documentation
//! Single source of truth for the `SteamUserApi` method surface.
//!
//! Historically the API surface was duplicated across five hand-maintained
//! lists: the `SteamUserApi` trait, the `SteamUser` delegation, the
//! `RemoteSteamUser`/`GasSteamUser` passthrough impls, the `ApiAction` enum
//! (+ its `is_read_only` classification), and the `FallbackSteamUser` impl.
//! Adding a method meant editing all of them in lock-step; forgetting one
//! (e.g. `fetch_matchmaking_stats`) shipped a method that existed but was
//! invisible to the trait.
//!
//! [`for_each_api_method!`] now holds the list **once** and forwards it to
//! callback macros that generate the `ApiAction` enum, the fallback impl, and
//! the passthrough impls. The `SteamUserApi` trait and the `SteamUser`
//! delegation stay hand-written (they carry docs, deprecations and per-method
//! special-casing) but are compile-checked against the generated impls: any
//! drift between this table and the trait is a "method is not a member of
//! trait" / "not all trait items implemented" error, never silent.
//!
//! Each row is: `{ Variant => method(args) -> Ret ; ro|rw }` where `ro` marks
//! a side-effect-free (safely retryable) read and `rw` a mutating call.

/// The canonical method table. Invoked with the name of a callback macro
/// (and, optionally, leading tokens in parentheses that are forwarded ahead
/// of the `@methods` marker — used to pass the target struct/error type to
/// the passthrough generator).
macro_rules! for_each_api_method {
    ($cb:ident $( ( $($pre:tt)* ) )?) => {
        $cb! {
            $( $($pre)* )?
            @methods
        { GetAccountDetails => get_account_details() -> crate::types::AccountDetails ; ro }
        { GetSteamWalletBalance => get_steam_wallet_balance() -> crate::types::WalletBalance ; ro }
        { GetAmountSpentOnSteam => get_amount_spent_on_steam() -> String ; ro }
        { GetPurchaseHistory => get_purchase_history() -> Vec<crate::types::PurchaseHistoryItem> ; ro }
        { RedeemWalletCode => redeem_wallet_code(code: &str) -> crate::types::RedeemWalletCodeResponse ; rw }
        { ParentalUnlock => parental_unlock(pin: &str) -> () ; rw }
        { GetFriendActivity => get_friend_activity(start: Option<u64>) -> crate::types::FriendActivityResponse ; ro }
        { GetFriendActivityFull => get_friend_activity_full() -> Vec<crate::types::FriendActivity> ; ro }
        { CommentUserReceivedNewGame => comment_user_received_new_game(steam_id: steamid::SteamID, thread_id: u64, comment: &str) -> crate::types::ActivityCommentResponse ; rw }
        { RateUpUserReceivedNewGame => rate_up_user_received_new_game(steam_id: steamid::SteamID, thread_id: u64) -> crate::types::ActivityCommentResponse ; rw }
        { DeleteCommentUserReceivedNewGame => delete_comment_user_received_new_game(steam_id: steamid::SteamID, thread_id: u64, comment_id: &str) -> crate::types::ActivityCommentResponse ; rw }
        { GetOwnedApps => get_owned_apps() -> Vec<crate::types::OwnedApp> ; ro }
        { GetOwnedAppsId => get_owned_apps_id() -> Vec<u32> ; ro }
        { GetOwnedAppsDetail => get_owned_apps_detail() -> Vec<crate::types::OwnedAppDetail> ; ro }
        { GetAppDetail => get_app_detail(app_ids: &[u32]) -> std::collections::HashMap<u32, crate::types::AppDetail> ; ro }
        { FetchCsgoAccountStats => fetch_csgo_account_stats() -> crate::types::CsgoAccountStats ; ro }
        { FetchMatchmakingStats => fetch_matchmaking_stats() -> crate::types::MatchmakingStats ; ro }
        { GetAppList => get_app_list() -> crate::types::SimpleSteamAppList ; ro }
        { SuggestAppList => suggest_app_list(term: &str) -> Vec<crate::types::AppListItem> ; ro }
        { QueryAppList => query_app_list(term: &str) -> Vec<crate::types::AppListItem> ; ro }
        { GetSteamAppVersionInfo => get_steam_app_version_info(app_id: u32) -> crate::types::SteamAppVersionInfo ; ro }
        { GetDynamicStoreUserData => get_dynamic_store_user_data() -> crate::types::DynamicStoreUserData ; ro }
        { FetchBatchedLoyaltyRewardItems => fetch_batched_loyalty_reward_items(app_ids: &[u32]) -> Vec<steam_protos::messages::CLoyaltyRewardsBatchedQueryRewardItemsResponseResponse> ; ro }
        { GetMyComments => get_my_comments() -> Vec<crate::types::UserComment> ; ro }
        { GetUserComments => get_user_comments(steam_id: steamid::SteamID) -> Vec<crate::types::UserComment> ; ro }
        { PostComment => post_comment(steam_id: steamid::SteamID, message: &str) -> Option<crate::types::UserComment> ; rw }
        { DeleteComment => delete_comment(steam_id: steamid::SteamID, gidcomment: &str) -> () ; rw }
        { GetConfirmations => get_confirmations(identity_secret: &str, tag: Option<&str>) -> Vec<crate::types::Confirmation> ; ro }
        { AcceptConfirmationForObject => accept_confirmation_for_object(identity_secret: &str, object_id: u64) -> () ; rw }
        { DenyConfirmationForObject => deny_confirmation_for_object(identity_secret: &str, object_id: u64) -> () ; rw }
        { GetAccountEmail => get_account_email() -> String ; ro }
        { GetCurrentSteamLogin => get_current_steam_login() -> String ; ro }
        { AddFriend => add_friend(steam_id: steamid::SteamID) -> () ; rw }
        { RemoveFriend => remove_friend(steam_id: steamid::SteamID) -> () ; rw }
        { AcceptFriendRequest => accept_friend_request(steam_id: steamid::SteamID) -> () ; rw }
        { IgnoreFriendRequest => ignore_friend_request(steam_id: steamid::SteamID) -> () ; rw }
        { BlockUser => block_user(steam_id: steamid::SteamID) -> () ; rw }
        { UnblockUser => unblock_user(steam_id: steamid::SteamID) -> () ; rw }
        { GetFriendsList => get_friends_list() -> std::collections::HashMap<steamid::SteamID, i32> ; ro }
        { GetFriendsDetails => get_friends_details() -> crate::types::FriendListPage ; ro }
        { GetFriendsDetailsOfUser => get_friends_details_of_user(steam_id: steamid::SteamID) -> crate::types::FriendListPage ; ro }
        { SearchUsers => search_users(query: &str, page: u32) -> crate::types::CommunitySearchResult ; ro }
        { CreateInstantInvite => create_instant_invite() -> String ; rw }
        { FollowUser => follow_user(steam_id: steamid::SteamID) -> () ; rw }
        { UnfollowUser => unfollow_user(steam_id: steamid::SteamID) -> () ; rw }
        { GetFollowingList => get_following_list() -> crate::types::FriendListPage ; ro }
        { GetFollowingListOfUser => get_following_list_of_user(steam_id: steamid::SteamID) -> crate::types::FriendListPage ; ro }
        { GetMyFriendsIdList => get_my_friends_id_list() -> Vec<steamid::SteamID> ; ro }
        { GetPendingFriendList => get_pending_friend_list() -> crate::types::PendingFriendList ; ro }
        { RemoveFriends => remove_friends(steam_ids: &[steamid::SteamID]) -> () ; rw }
        { UnfollowUsers => unfollow_users(steam_ids: &[steamid::SteamID]) -> () ; rw }
        { CancelFriendRequest => cancel_friend_request(steam_id: steamid::SteamID) -> () ; rw }
        { GetFriendsInCommon => get_friends_in_common(steam_id: steamid::SteamID) -> Vec<crate::types::FriendDetails> ; ro }
        { GetFriendsGameplayInfo => get_friends_gameplay_info(app_id: u32) -> crate::types::gameplay::GameplayInfoResponse ; ro }
        { GetFriendSince => get_friend_since(steam_id: steamid::SteamID) -> Option<String> ; ro }
        { GetQuickInviteData => get_quick_invite_data() -> crate::types::QuickInviteData ; ro }
        { GetCurrentQuickInviteTokens => get_current_quick_invite_tokens() -> crate::types::QuickInviteTokensResponse ; ro }
        { JoinGroup => join_group(group_id: steamid::SteamID) -> () ; rw }
        { LeaveGroup => leave_group(group_id: steamid::SteamID) -> () ; rw }
        { GetGroupMembers => get_group_members(group_id: steamid::SteamID) -> Vec<steamid::SteamID> ; ro }
        { PostGroupAnnouncement => post_group_announcement(group_id: steamid::SteamID, headline: &str, content: &str) -> () ; rw }
        { KickGroupMember => kick_group_member(group_id: steamid::SteamID, member_id: steamid::SteamID) -> () ; rw }
        { InviteUserToGroup => invite_user_to_group(user_id: steamid::SteamID, group_id: steamid::SteamID) -> () ; rw }
        { InviteUsersToGroup => invite_users_to_group(user_ids: &[steamid::SteamID], group_id: steamid::SteamID) -> () ; rw }
        { AcceptGroupInvite => accept_group_invite(group_id: steamid::SteamID) -> () ; rw }
        { IgnoreGroupInvite => ignore_group_invite(group_id: steamid::SteamID) -> () ; rw }
        { GetGroupOverview => get_group_overview(gid: Option<steamid::SteamID>, group_url: Option<&str>, page: Option<i32>, search_key: Option<&str>) -> crate::types::GroupOverview ; ro }
        { GetGroupSteamIdFromVanityUrl => get_group_steam_id_from_vanity_url(vanity_url: &str) -> String ; ro }
        { GetGroupInfoXml => get_group_info_xml(gid: Option<steamid::SteamID>, group_url: Option<&str>, page: Option<u32>) -> crate::types::GroupInfoXml ; ro }
        { GetGroupInfoXmlFull => get_group_info_xml_full(gid: Option<steamid::SteamID>, group_url: Option<&str>) -> crate::types::GroupInfoXml ; ro }
        { GetInvitableGroups => get_invitable_groups(user_steam_id: steamid::SteamID) -> Vec<crate::types::InvitableGroup> ; ro }
        { InviteAllFriendsToGroup => invite_all_friends_to_group(group_id: steamid::SteamID) -> () ; rw }
        { GetInventory => get_inventory(appid: crate::types::AppId, context_id: crate::types::ContextId) -> Vec<crate::types::EconItem> ; ro }
        { GetUserInventoryContents => get_user_inventory_contents(steam_id: steamid::SteamID, appid: crate::types::AppId, context_id: crate::types::ContextId) -> Vec<crate::types::EconItem> ; ro }
        { GetInventoryHistory => get_inventory_history() -> crate::types::InventoryHistoryResult ; ro }
        { GetPriceOverview => get_price_overview(appid: crate::types::AppId, market_hash_name: &str) -> crate::types::PriceOverview ; ro }
        { GetActiveInventories => get_active_inventories() -> Vec<crate::types::ActiveInventory> ; ro }
        { GetInventoryTrading => get_inventory_trading(appid: crate::types::AppId, context_id: crate::types::ContextId) -> serde_json::Value ; ro }
        { GetInventoryTradingPartner => get_inventory_trading_partner(appid: crate::types::AppId, partner: steamid::SteamID, context_id: crate::types::ContextId) -> serde_json::Value ; ro }
        { GetFullInventoryHistory => get_full_inventory_history() -> Vec<crate::types::InventoryHistoryItem> ; ro }
        { GetMyListings => get_my_listings(start: u32, count: u32) -> crate::types::MyListingsResult ; ro }
        { GetMarketHistory => get_market_history(start: u32, count: u32) -> crate::types::MarketHistoryResponse ; ro }
        { SellItem => sell_item(appid: crate::types::AppId, contextid: crate::types::ContextId, assetid: crate::types::AssetId, amount: crate::types::Amount, price: crate::types::PriceCents) -> crate::types::SellItemResult ; rw }
        { RemoveListing => remove_listing(listing_id: &str) -> bool ; rw }
        { GetGemValue => get_gem_value(appid: crate::types::AppId, assetid: crate::types::AssetId) -> crate::types::GemValue ; ro }
        { TurnItemIntoGems => turn_item_into_gems(appid: crate::types::AppId, assetid: crate::types::AssetId, expected_value: u32) -> crate::types::GemResult ; rw }
        { GetBoosterPackCatalog => get_booster_pack_catalog() -> Vec<crate::types::BoosterPackEntry> ; ro }
        { CreateBoosterPack => create_booster_pack(appid: crate::types::AppId, use_untradable_gems: bool) -> crate::types::BoosterResult ; rw }
        { OpenBoosterPack => open_booster_pack(appid: crate::types::AppId, assetid: crate::types::AssetId) -> Vec<crate::types::EconItem> ; rw }
        { GetMarketRestrictions => get_market_restrictions() -> (crate::types::MarketRestrictions, Option<crate::types::WalletBalance>) ; ro }
        { GetMarketApps => get_market_apps() -> std::collections::HashMap<u32, String> ; ro }
        { GetItemNameid => get_item_nameid(app_id: crate::types::AppId, market_hash_name: &str) -> crate::types::ItemNameId ; ro }
        { GetItemOrdersHistogram => get_item_orders_histogram(item_nameid: crate::types::ItemNameId, country: &str, currency: u32) -> crate::types::ItemOrdersHistogramResponse ; ro }
        { GetPhoneNumberStatus => get_phone_number_status() -> Option<String> ; ro }
        { AddPhoneNumber => add_phone_number(phone: &str) -> crate::types::AddPhoneNumberResponse ; rw }
        { ConfirmPhoneCodeForAdd => confirm_phone_code_for_add(code: &str) -> crate::types::ConfirmPhoneCodeResponse ; rw }
        { ResendPhoneVerificationCode => resend_phone_verification_code() -> serde_json::Value ; rw }
        { GetRemovePhoneNumberType => get_remove_phone_number_type() -> Option<crate::types::RemovePhoneResult> ; ro }
        { SendAccountRecoveryCode => send_account_recovery_code(wizard_param: serde_json::Value, method: i32) -> serde_json::Value ; rw }
        { ConfirmRemovePhoneNumberCode => confirm_remove_phone_number_code(wizard_param: serde_json::Value, code: &str) -> serde_json::Value ; rw }
        { SendConfirmation2SteamMobileApp => send_confirmation_2_steam_mobile_app(wizard_param: serde_json::Value) -> serde_json::Value ; rw }
        { SendConfirmation2SteamMobileAppFinal => send_confirmation_2_steam_mobile_app_final(wizard_param: serde_json::Value) -> serde_json::Value ; rw }
        { GetPrivacySettings => get_privacy_settings() -> crate::types::PrivacySettings ; ro }
        { SetPrivacySettings => set_privacy_settings(settings: crate::types::PrivacySettings) -> crate::types::PrivacySettings ; rw }
        { SetAllPrivacy => set_all_privacy(level: &str) -> crate::types::PrivacySettings ; rw }
        { GetProfile => get_profile(steam_id: Option<steamid::SteamID>) -> crate::types::SteamProfile ; ro }
        { EditProfile => edit_profile(settings: serde_json::Value) -> () ; rw }
        { SetPersonaName => set_persona_name(name: &str) -> () ; rw }
        { GetAliasHistory => get_alias_history(steam_id: steamid::SteamID) -> Vec<crate::types::AliasEntry> ; ro }
        { ClearPreviousAliases => clear_previous_aliases() -> () ; rw }
        { SetNickname => set_nickname(steam_id: steamid::SteamID, nickname: &str) -> () ; rw }
        { RemoveNickname => remove_nickname(steam_id: steamid::SteamID) -> () ; rw }
        { PostProfileStatus => post_profile_status(text: &str, app_id: Option<u32>) -> u64 ; rw }
        { SelectPreviousAvatar => select_previous_avatar(avatar_hash: &str) -> () ; rw }
        { SetupProfile => setup_profile() -> bool ; rw }
        { GetUserSummaryFromXml => get_user_summary_from_xml(steam_id: steamid::SteamID) -> crate::types::UserSummaryXml ; ro }
        { GetUserSummaryFromProfile => get_user_summary_from_profile(steam_id: Option<steamid::SteamID>) -> crate::types::UserSummaryProfile ; ro }
        { FetchFullProfile => fetch_full_profile(steam_id: steamid::SteamID) -> crate::types::SteamProfile ; ro }
        { ResolveUser => resolve_user(steam_id: steamid::SteamID) -> Option<crate::types::SteamUserProfile> ; ro }
        { GetAvatarHistory => get_avatar_history() -> Vec<crate::types::AvatarHistoryEntry> ; ro }
        { UploadAvatarFromUrl => upload_avatar_from_url(url: &str) -> crate::types::AvatarUploadResponse ; rw }
        { EnumerateTokens => enumerate_tokens() -> steam_protos::CAuthenticationRefreshTokenEnumerateResponse ; ro }
        { CheckTokenExists => check_token_exists(token_id: &str) -> bool ; ro }
        { RevokeTokens => revoke_tokens(token_ids: &[&str], shared_secret: Option<&str>) -> crate::services::tokens::RevokeTokensResult ; rw }
        { GetTradeUrl => get_trade_url() -> Option<String> ; ro }
        { GetTradeOffer => get_trade_offer() -> crate::types::TradeOffersResponse ; ro }
        { AcceptTradeOffer => accept_trade_offer(trade_offer_id: u64, partner_steam_id: Option<String>) -> String ; rw }
        { DeclineTradeOffer => decline_trade_offer(trade_offer_id: u64) -> () ; rw }
        { CancelTradeOffer => cancel_trade_offer(trade_offer_id: u64) -> () ; rw }
        { SendTradeOffer => send_trade_offer(trade_url: &str, my_assets: Vec<crate::types::TradeOfferAsset>, their_assets: Vec<crate::types::TradeOfferAsset>, message: &str) -> crate::types::TradeOfferResult ; rw }
        { GetSentTradeOffers => get_sent_trade_offers() -> crate::types::TradeOffersResponse ; ro }
        { GetSteamGuardStatus => get_steam_guard_status() -> crate::types::SteamGuardStatus ; ro }
        { EnableTwoFactor => enable_two_factor() -> crate::types::TwoFactorResponse ; rw }
        { FinalizeTwoFactor => finalize_two_factor(shared_secret: &str, activation_code: &str) -> () ; rw }
        { DisableTwoFactor => disable_two_factor(revocation_code: &str) -> () ; rw }
        { DeauthorizeDevices => deauthorize_devices() -> () ; rw }
        { AddAuthenticator => add_authenticator() -> crate::types::TwoFactorResponse ; rw }
        { FinalizeAuthenticator => finalize_authenticator(activation_code: &str) -> () ; rw }
        { RemoveAuthenticator => remove_authenticator(revocation_code: &str) -> () ; rw }
        { EnableSteamGuardEmail => enable_steam_guard_email() -> bool ; rw }
        { DisableSteamGuardEmail => disable_steam_guard_email() -> bool ; rw }
        { GetPlayerReports => get_player_reports() -> Vec<crate::types::PlayerReport> ; ro }
        { AddFreeLicense => add_free_license(package_id: u32) -> bool ; rw }
        { AddSubFreeLicense => add_sub_free_license(sub_id: u32) -> bool ; rw }
        { RedeemPoints => redeem_points(definition_id: u32) -> steam_protos::messages::loyalty_rewards::CLoyaltyRewardsRedeemPointsResponse ; rw }
        { GetHelpRequests => get_help_requests() -> Vec<crate::types::HelpRequest> ; ro }
        { GetHelpRequestDetail => get_help_request_detail(id: &str) -> String ; ro }
        { GetMatchHistory => get_match_history(match_type: &str, token: Option<&str>) -> crate::types::MatchHistoryResponse ; ro }
        { LoggedIn => logged_in() -> crate::types::LoggedInResult ; ro }
        { GetNotifications => get_notifications() -> crate::types::Notifications ; ro }
        { GetWebApiKey => get_web_api_key(domain: &str) -> String ; ro }
        { ResolveVanityUrl => resolve_vanity_url(api_key: &str, vanity_name: &str) -> steamid::SteamID ; ro }
        { RevokeWebApiKey => revoke_web_api_key() -> () ; rw }
        }
    };
}

/// Generates the `ApiAction` enum and its `is_read_only` classifier.
macro_rules! define_api_action {
    (@ro ro) => { true };
    (@ro rw) => { false };
    (@methods $( { $variant:ident => $method:ident ( $($arg:ident : $argty:ty),* $(,)? ) -> $ret:ty ; $ro:ident } )* ) => {
        /// All available actions exposed by `SteamUserApi`.
        ///
        /// Generated from the canonical table in [`for_each_api_method!`].
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum ApiAction {
            $( $variant, )*
        }

        impl ApiAction {
            /// Returns true if the action fetches data without side effects,
            /// making it safe to blindly retry on transient failures.
            pub fn is_read_only(&self) -> bool {
                match self {
                    $( Self::$variant => define_api_action!(@ro $ro), )*
                }
            }
        }
    };
}

/// Generates a pure-passthrough `impl SteamUserApi for $struct` that delegates
/// every method to the inherent method of the same name. Used for
/// `RemoteSteamUser` and `GasSteamUser`.
#[cfg(any(feature = "remote", feature = "gas"))]
macro_rules! gen_passthrough_impl {
    ( $struct:ty, $error:ty, @methods $( { $variant:ident => $method:ident ( $($arg:ident : $argty:ty),* $(,)? ) -> $ret:ty ; $ro:ident } )* ) => {
        #[async_trait::async_trait]
        impl $crate::SteamUserApi for $struct {
            type Error = $error;

            $(
                async fn $method(&self $(, $arg: $argty)*) -> Result<$ret, Self::Error> {
                    self.$method($($arg),*).await
                }
            )*
        }
    };
}

/// Public entry point used by `remote/trait_impl.rs` and `gas/trait_impl.rs`.
///
/// # Usage
///
/// ```ignore
/// impl_passthrough_steam_user_api!(RemoteSteamUser, RemoteSteamUserError);
/// ```
#[cfg(any(feature = "remote", feature = "gas"))]
macro_rules! impl_passthrough_steam_user_api {
    ($struct:ty, $error:ty) => {
        for_each_api_method!(gen_passthrough_impl($struct, $error,));
    };
}

/// Generates `impl SteamUserApi for FallbackSteamUser`: try local first, then
/// (for retryable failures on read-only actions) remote, then gas, with
/// structured tracing around every attempt.
macro_rules! gen_fallback_impl {
    // Redact sensitive arguments from the traced request line.
    (@record_arg identity_secret, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg shared_secret, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg pin, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg code, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg activation_code, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg revocation_code, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg api_key, $val:expr) => { "[REDACTED]".to_string() };
    (@record_arg $name:ident, $val:expr) => { format!("{:?}", $val) };

    (@methods $( { $variant:ident => $method:ident ( $($arg:ident : $argty:ty),* $(,)? ) -> $ret:ty ; $ro:ident } )* ) => {
        #[allow(deprecated)]
        #[async_trait::async_trait]
        impl SteamUserApi for FallbackSteamUser {
            type Error = SteamUserError;

            $(
                #[allow(unused_assignments)]
                #[tracing::instrument(target = "steam_user", skip_all, fields(http_method, url, raw_response, response_type, content_type))]
                async fn $method(&self $(, $arg: $argty)*) -> Result<$ret, Self::Error> {
                    let _start = std::time::Instant::now();
                    let _steam_id = self.local.steam_id().and_then(|s| i64::try_from(s.steam_id64()).ok()).unwrap_or(0);
                    let _input = if tracing::enabled!(target: "steam_user", tracing::Level::WARN) {
                        #[allow(unused_mut)]
                        let mut parts: Vec<String> = Vec::new();
                        $(
                            parts.push(format!("{}: {}", stringify!($arg), gen_fallback_impl!(@record_arg $arg, &$arg)));
                        )*
                        if parts.is_empty() {
                            String::new()
                        } else {
                            format!("{{ {} }}", parts.join(", "))
                        }
                    } else {
                        String::new()
                    };

                    let mut _source = "local";

                    #[allow(unused_mut)]
                    let mut last_error = match SteamUserApi::$method(&self.local, $($arg.clone()),*).await {
                        Ok(v) => {
                            let duration = i64::try_from(_start.elapsed().as_millis()).unwrap_or(i64::MAX);
                            let output_str = if tracing::enabled!(target: "steam_user", tracing::Level::DEBUG) {
                                let s = format!("{:?}", &v);
                                if s.len() > 256 { format!("{}…[truncated, {} bytes]", &s[..256], s.len()) } else { s }
                            } else {
                                String::new()
                            };
                            tracing::info!(
                                target: "steam_user",
                                steam_id = _steam_id,
                                function = stringify!($method),
                                action = stringify!($variant),
                                status = "ok",
                                source = _source,
                                duration_ms = duration,
                                request = _input.as_str(),
                                response = output_str.as_str(),
                                "API call completed"
                            );
                            return Ok(v);
                        }
                        Err(e) => e,
                    };

                    let is_network_or_rate_limit = last_error.is_retryable();
                    let is_safe_action = ApiAction::$variant.is_read_only();

                    if is_network_or_rate_limit && is_safe_action {
                        #[cfg(feature = "remote")]
                        if let Some(remote) = &self.remote {
                            _source = "remote";
                            match SteamUserApi::$method(remote, $($arg.clone()),*).await {
                                Ok(v) => {
                                    let duration = i64::try_from(_start.elapsed().as_millis()).unwrap_or(i64::MAX);
                                    let output_str = format!("{:?}", &v);
                                    tracing::info!(
                                        target: "steam_user",
                                        steam_id = _steam_id,
                                        function = stringify!($method),
                                        action = stringify!($variant),
                                        status = "ok",
                                        source = _source,
                                        duration_ms = duration,
                                        request = _input.as_str(),
                                        response = output_str.as_str(),
                                        "API call completed"
                                    );
                                    return Ok(v);
                                }
                                Err(e) => {
                                    last_error = SteamUserError::RemoteFailed(Box::new(e));
                                }
                            }
                        }

                        #[cfg(feature = "gas")]
                        if let Some(gas) = &self.gas {
                            _source = "gas";
                            match SteamUserApi::$method(gas, $($arg),*).await {
                                Ok(v) => {
                                    let duration = i64::try_from(_start.elapsed().as_millis()).unwrap_or(i64::MAX);
                                    let output_str = format!("{:?}", &v);
                                    tracing::info!(
                                        target: "steam_user",
                                        steam_id = _steam_id,
                                        function = stringify!($method),
                                        action = stringify!($variant),
                                        status = "ok",
                                        source = _source,
                                        duration_ms = duration,
                                        request = _input.as_str(),
                                        response = output_str.as_str(),
                                        "API call completed"
                                    );
                                    return Ok(v);
                                }
                                Err(e) => {
                                    last_error = SteamUserError::GasFailed(Box::new(e));
                                }
                            }
                        }
                    }

                    let duration = i64::try_from(_start.elapsed().as_millis()).unwrap_or(i64::MAX);
                    let err_str = format!("{}", last_error);
                    tracing::warn!(
                        target: "steam_user",
                        steam_id = _steam_id,
                        function = stringify!($method),
                        action = stringify!($variant),
                        status = "error",
                        source = _source,
                        duration_ms = duration,
                        request = _input.as_str(),
                        error = err_str.as_str(),
                        "API call failed"
                    );

                    Err(last_error).with_action(ApiAction::$variant)
                }
            )*
        }
    };
}