|
| 1 | +use crate::errors::{ApiErrorBody, Error}; |
| 2 | +use crate::services::game::GameService; |
| 3 | +use crate::services::social::SocialService; |
| 4 | +use crate::Result; |
| 5 | +use once_cell::sync::Lazy; |
| 6 | +use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, RETRY_AFTER, USER_AGENT}; |
| 7 | +use reqwest::StatusCode; |
| 8 | +use std::time::Duration; |
| 9 | +use tracing::{debug, instrument}; |
| 10 | +use url::Url; |
| 11 | + |
| 12 | +static DEFAULT_BASE: &str = "https://uapis.cn/api/v1"; |
| 13 | +static DEFAULT_UA: &str = "uapi-sdk-rust/0.1.0"; |
| 14 | +static DEFAULT_BASE_URL: Lazy<Url> = Lazy::new(|| Url::parse(DEFAULT_BASE).expect("valid default base")); |
| 15 | + |
| 16 | +#[derive(Clone)] |
| 17 | +pub struct Client { |
| 18 | + pub(crate) http: reqwest::Client, |
| 19 | + pub(crate) base_url: Url, |
| 20 | + pub(crate) api_key: Option<String>, |
| 21 | + pub(crate) user_agent: String, |
| 22 | +} |
| 23 | + |
| 24 | +impl Client { |
| 25 | + pub fn new<T: Into<String>>(api_key: T) -> Self { |
| 26 | + let http = reqwest::Client::builder() |
| 27 | + .timeout(Duration::from_secs(20)) |
| 28 | + .build() |
| 29 | + .expect("reqwest client"); |
| 30 | + Self { |
| 31 | + http, |
| 32 | + base_url: DEFAULT_BASE_URL.clone(), |
| 33 | + api_key: Some(api_key.into()), |
| 34 | + user_agent: DEFAULT_UA.to_string(), |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + pub fn from_env() -> Option<Self> { |
| 39 | + let token = std::env::var("UAPI_TOKEN").ok()?; |
| 40 | + let mut cli = Self::new(token); |
| 41 | + if let Ok(base) = std::env::var("UAPI_BASE_URL") { |
| 42 | + if let Ok(url) = Url::parse(&base) { |
| 43 | + cli.base_url = url; |
| 44 | + } |
| 45 | + } |
| 46 | + Some(cli) |
| 47 | + } |
| 48 | + |
| 49 | + pub fn builder() -> ClientBuilder { |
| 50 | + ClientBuilder::default() |
| 51 | + } |
| 52 | + |
| 53 | + pub fn game(&self) -> GameService<'_> { |
| 54 | + GameService { client: self } |
| 55 | + } |
| 56 | + |
| 57 | + pub fn social(&self) -> SocialService<'_> { |
| 58 | + SocialService { client: self } |
| 59 | + } |
| 60 | + |
| 61 | + #[instrument(skip(self, headers, query), fields(method=%method, path=%path))] |
| 62 | + pub(crate) async fn request_json<T: serde::de::DeserializeOwned>( |
| 63 | + &self, |
| 64 | + method: reqwest::Method, |
| 65 | + path: &str, |
| 66 | + headers: Option<HeaderMap>, |
| 67 | + query: Option<&[(&str, &str)]>, |
| 68 | + json_body: Option<serde_json::Value>, |
| 69 | + ) -> Result<T> { |
| 70 | + let url = self.base_url.join(path)?; |
| 71 | + let mut req = self.http.request(method.clone(), url.clone()); |
| 72 | + |
| 73 | + let mut merged = HeaderMap::new(); |
| 74 | + merged.insert(USER_AGENT, HeaderValue::from_static(DEFAULT_UA)); |
| 75 | + if let Some(t) = &self.api_key { |
| 76 | + let value = format!("Bearer {}", t); |
| 77 | + if let Ok(h) = HeaderValue::from_str(&value) { |
| 78 | + merged.insert(AUTHORIZATION, h); |
| 79 | + } |
| 80 | + } |
| 81 | + if let Some(h) = headers { |
| 82 | + merged.extend(h); |
| 83 | + } |
| 84 | + req = req.headers(merged); |
| 85 | + |
| 86 | + if let Some(q) = query { |
| 87 | + req = req.query(q); |
| 88 | + } |
| 89 | + if let Some(body) = json_body { |
| 90 | + req = req.json(&body); |
| 91 | + } |
| 92 | + |
| 93 | + debug!("request {}", url); |
| 94 | + let resp = req.send().await?; |
| 95 | + self.handle_json_response(resp).await |
| 96 | + } |
| 97 | + |
| 98 | + async fn handle_json_response<T: serde::de::DeserializeOwned>(&self, resp: reqwest::Response) -> Result<T> { |
| 99 | + let status = resp.status(); |
| 100 | + let req_id = find_request_id(resp.headers()); |
| 101 | + let retry_after = parse_retry_after(resp.headers()); |
| 102 | + if status.is_success() { |
| 103 | + return Ok(resp.json::<T>().await?); |
| 104 | + } |
| 105 | + let text = resp.text().await.unwrap_or_default(); |
| 106 | + let parsed = serde_json::from_str::<ApiErrorBody>(&text).ok(); |
| 107 | + let msg = parsed.as_ref().and_then(|b| b.message.clone()).or_else(|| non_empty(text.clone())); |
| 108 | + let code = parsed.as_ref().and_then(|b| b.code.clone()); |
| 109 | + let details = parsed.as_ref().and_then(|b| b.details.clone()); |
| 110 | + Err(map_status_to_error(status, code, msg, details, req_id, retry_after)) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +#[derive(Default)] |
| 115 | +pub struct ClientBuilder { |
| 116 | + api_key: Option<String>, |
| 117 | + base_url: Option<Url>, |
| 118 | + timeout: Option<Duration>, |
| 119 | + client: Option<reqwest::Client>, |
| 120 | + user_agent: Option<String>, |
| 121 | +} |
| 122 | + |
| 123 | +impl ClientBuilder { |
| 124 | + pub fn api_key<T: Into<String>>(mut self, api_key: T) -> Self { self.api_key = Some(api_key.into()); self } |
| 125 | + pub fn base_url(mut self, base: Url) -> Self { self.base_url = Some(base); self } |
| 126 | + pub fn timeout(mut self, secs: u64) -> Self { self.timeout = Some(Duration::from_secs(secs)); self } |
| 127 | + pub fn user_agent<T: Into<String>>(mut self, ua: T) -> Self { self.user_agent = Some(ua.into()); self } |
| 128 | + pub fn http_client(mut self, cli: reqwest::Client) -> Self { self.client = Some(cli); self } |
| 129 | + |
| 130 | + pub fn build(self) -> Result<Client> { |
| 131 | + let http = if let Some(cli) = self.client { |
| 132 | + cli |
| 133 | + } else { |
| 134 | + reqwest::Client::builder() |
| 135 | + .timeout(self.timeout.unwrap_or(Duration::from_secs(20))) |
| 136 | + .build()? |
| 137 | + }; |
| 138 | + Ok(Client { |
| 139 | + http, |
| 140 | + base_url: self.base_url.unwrap_or_else(|| DEFAULT_BASE_URL.clone()), |
| 141 | + api_key: self.api_key, |
| 142 | + user_agent: self.user_agent.unwrap_or_else(|| DEFAULT_UA.to_string()), |
| 143 | + }) |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +fn find_request_id(headers: &HeaderMap) -> Option<String> { |
| 148 | + const CANDIDATES: &[&str] = &["x-request-id", "x-amzn-requestid", "traceparent"]; |
| 149 | + for key in CANDIDATES { |
| 150 | + if let Some(v) = headers.get(*key) { |
| 151 | + if let Ok(text) = v.to_str() { |
| 152 | + return Some(text.to_string()); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + None |
| 157 | +} |
| 158 | + |
| 159 | +fn parse_retry_after(headers: &HeaderMap) -> Option<u64> { |
| 160 | + headers |
| 161 | + .get(RETRY_AFTER) |
| 162 | + .and_then(|v| v.to_str().ok()) |
| 163 | + .and_then(|s| s.trim().parse::<u64>().ok()) |
| 164 | +} |
| 165 | + |
| 166 | +fn non_empty(s: String) -> Option<String> { |
| 167 | + let trimmed = s.trim(); |
| 168 | + if trimmed.is_empty() { None } else { Some(trimmed.to_owned()) } |
| 169 | +} |
| 170 | + |
| 171 | +fn map_status_to_error( |
| 172 | + status: StatusCode, |
| 173 | + code: Option<String>, |
| 174 | + message: Option<String>, |
| 175 | + details: Option<serde_json::Value>, |
| 176 | + request_id: Option<String>, |
| 177 | + retry_after: Option<u64>, |
| 178 | +) -> Error { |
| 179 | + use StatusCode::*; |
| 180 | + let s = status.as_u16(); |
| 181 | + match status { |
| 182 | + UNAUTHORIZED | FORBIDDEN => Error::AuthenticationError { status: s, message, request_id }, |
| 183 | + TOO_MANY_REQUESTS => Error::RateLimitError { status: s, message, retry_after_seconds: retry_after, request_id }, |
| 184 | + NOT_FOUND => Error::NotFound { status: s, message, request_id }, |
| 185 | + BAD_REQUEST => Error::ValidationError { status: s, message, details, request_id }, |
| 186 | + _ if status.is_server_error() => Error::ServerError { status: s, message, request_id }, |
| 187 | + _ if status.is_client_error() => Error::ApiError { status: s, code, message, details, request_id }, |
| 188 | + _ => Error::ApiError { status: s, code, message, details, request_id }, |
| 189 | + } |
| 190 | +} |
0 commit comments