interplane.Get Omega
Read in your language

mobhub

Decentralized model and agent weights distribution network

Brought by drakestapleton

branch main Branches Tags History

mobhub / src / torn.rs

267 lines · 9604 bytes Raw Blame History
1//! Torn API v2 client in native Rust.
2//! Includes sliding-window rate limiting, exponential backoff, concurrency caps,
3//! in-memory caching, and dynamic Hardware TPM Vault integration.
4
5use crate::vault;
6use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
7use std::collections::HashMap;
8use std::fmt;
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11use tokio::sync::{Mutex, Semaphore};
12
13const BASE_URL: &str = "https://api.torn.com/v2";
14const CLIENT_USER_AGENT: &str = "MobHub-Rust/0.1 (sovereign native faction ops)";
15const CACHE_TTL: Duration = Duration::from_secs(30);
16const MAX_REQUESTS_PER_MINUTE: usize = 80;
17const RATE_WINDOW: Duration = Duration::from_secs(60);
18const MAX_CONCURRENT_REQUESTS: usize = 6;
19
20#[derive(Debug)]
21pub enum TornError {
22 MissingKey,
23 Network(String),
24 Http { status: u16, detail: String },
25 Api { code: i64, message: String },
26 Serialization(String),
27}
28
29impl fmt::Display for TornError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 TornError::MissingKey => write!(f, "Missing Torn API key in TPM vault or environment"),
33 TornError::Network(s) => write!(f, "Network error: {}", s),
34 TornError::Http { status, detail } => write!(f, "Torn API HTTP {}: {}", status, detail),
35 TornError::Api { code, message } => write!(f, "Torn API error {}: {}", code, message),
36 TornError::Serialization(s) => write!(f, "Serialization error: {}", s),
37 }
38 }
39}
40
41impl std::error::Error for TornError {}
42
43struct CacheEntry {
44 stored_at: Instant,
45 data: serde_json::Value,
46}
47
48#[derive(Clone)]
49pub struct TornClient {
50 http: reqwest::Client,
51 semaphore: Arc<Semaphore>,
52 request_timestamps: Arc<Mutex<Vec<Instant>>>,
53 cache: Arc<Mutex<HashMap<String, CacheEntry>>>,
54 mock_mode: bool,
55 mock_responses: Arc<Mutex<HashMap<String, serde_json::Value>>>,
56}
57
58impl TornClient {
59 pub fn new() -> Self {
60 let mut headers = HeaderMap::new();
61 headers.insert(USER_AGENT, HeaderValue::from_static(CLIENT_USER_AGENT));
62 headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
63
64 let http = reqwest::Client::builder()
65 .default_headers(headers)
66 .timeout(Duration::from_secs(15))
67 .build()
68 .expect("Failed to initialize HTTP client");
69
70 Self {
71 http,
72 semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REQUESTS)),
73 request_timestamps: Arc::new(Mutex::new(Vec::new())),
74 cache: Arc::new(Mutex::new(HashMap::new())),
75 mock_mode: false,
76 mock_responses: Arc::new(Mutex::new(HashMap::new())),
77 }
78 }
79
80 pub fn new_mock() -> Self {
81 let mut client = Self::new();
82 client.mock_mode = true;
83 client
84 }
85
86 pub async fn set_mock_response(&self, path: &str, data: serde_json::Value) {
87 let mut map = self.mock_responses.lock().await;
88 map.insert(path.to_string(), data);
89 }
90
91 async fn wait_for_rate_limit_slot(&self) {
92 loop {
93 let mut timestamps = self.request_timestamps.lock().await;
94 let now = Instant::now();
95 timestamps.retain(|&t| now.duration_since(t) < RATE_WINDOW);
96
97 if timestamps.len() < MAX_REQUESTS_PER_MINUTE {
98 timestamps.push(now);
99 break;
100 }
101
102 let oldest = timestamps[0];
103 let wait_time = RATE_WINDOW.saturating_sub(now.duration_since(oldest)) + Duration::from_millis(10);
104 drop(timestamps);
105 tokio::time::sleep(wait_time).await;
106 }
107 }
108
109 pub async fn get(&self, path: &str, use_cache: bool) -> Result<serde_json::Value, TornError> {
110 if self.mock_mode {
111 let map = self.mock_responses.lock().await;
112 if let Some(val) = map.get(path) {
113 return Ok(val.clone());
114 }
115 return Ok(serde_json::json!({ "status": "mock_default", "path": path }));
116 }
117
118 let cache_key = path.to_string();
119 if use_cache {
120 let cache = self.cache.lock().await;
121 if let Some(entry) = cache.get(&cache_key) {
122 if entry.stored_at.elapsed() < CACHE_TTL {
123 return Ok(entry.data.clone());
124 }
125 }
126 }
127
128 let api_key = vault::get_torn_api_key().ok_or(TornError::MissingKey)?;
129 let sep = if path.contains('?') { "&" } else { "?" };
130 let full_url = format!("{}{}{}key={}", BASE_URL, path, sep, api_key);
131
132 let mut attempt = 0;
133 let max_attempts = 4;
134 let mut last_error = None;
135
136 while attempt < max_attempts {
137 attempt += 1;
138 let _permit = self.semaphore.acquire().await.map_err(|e| TornError::Network(e.to_string()))?;
139 self.wait_for_rate_limit_slot().await;
140
141 let response = match self.http.get(&full_url).send().await {
142 Ok(res) => res,
143 Err(err) => {
144 let redacted = vault::redact_secrets(&err.to_string());
145 last_error = Some(TornError::Network(redacted));
146 tokio::time::sleep(Duration::from_millis(500 * (1 << attempt))).await;
147 continue;
148 }
149 };
150
151 let status = response.status();
152 if status == 429 || status.is_server_error() {
153 let wait_ms = 1000 * (1 << attempt);
154 tokio::time::sleep(Duration::from_millis(wait_ms)).await;
155 continue;
156 }
157
158 let text = response.text().await.map_err(|e| TornError::Network(vault::redact_secrets(&e.to_string())))?;
159 let json: serde_json::Value = serde_json::from_str(&text).map_err(|e| TornError::Serialization(e.to_string()))?;
160
161 if let Some(err_obj) = json.get("error").and_then(|e| e.as_object()) {
162 let code = err_obj.get("code").and_then(|c| c.as_i64()).unwrap_or(0);
163 let msg = err_obj.get("error").and_then(|m| m.as_str()).unwrap_or("Unknown Torn API error");
164 if (code == 5 || code == 17) && attempt < max_attempts {
165 tokio::time::sleep(Duration::from_millis(1500 * attempt as u64)).await;
166 continue;
167 }
168 return Err(TornError::Api {
169 code,
170 message: msg.to_string(),
171 });
172 }
173
174 if let Some(err_name) = json.get("error_name").and_then(|e| e.as_str()) {
175 let code = json.get("error_code").and_then(|c| c.as_i64()).unwrap_or(status.as_u16() as i64);
176 return Err(TornError::Api {
177 code,
178 message: err_name.to_string(),
179 });
180 }
181
182 if !status.is_success() {
183 return Err(TornError::Http {
184 status: status.as_u16(),
185 detail: format!("Torn API HTTP status {}", status.as_u16()),
186 });
187 }
188
189 if use_cache {
190 let mut cache = self.cache.lock().await;
191 cache.insert(cache_key.clone(), CacheEntry {
192 stored_at: Instant::now(),
193 data: json.clone(),
194 });
195 }
196
197 return Ok(json);
198 }
199
200 Err(last_error.unwrap_or(TornError::Network("Max retry attempts exceeded".to_string())))
201 }
202
203 pub async fn get_ranked_wars(&self) -> Result<serde_json::Value, TornError> {
204 self.get("/faction/rankedwars", true).await
205 }
206
207 pub async fn get_ranked_war_report(&self, war_id: i64) -> Result<serde_json::Value, TornError> {
208 self.get(&format!("/faction/{}/rankedwarreport", war_id), true).await
209 }
210
211 pub async fn get_faction_members(&self) -> Result<serde_json::Value, TornError> {
212 self.get("/faction/members", true).await
213 }
214
215 pub async fn get_faction_balance(&self) -> Result<serde_json::Value, TornError> {
216 self.get("/faction/balance", true).await
217 }
218
219 pub async fn get_bounties(&self) -> Result<serde_json::Value, TornError> {
220 self.get("/torn/bounties", true).await
221 }
222
223 pub async fn get_faction_news(
224 &self,
225 category: &str,
226 from_unix: Option<i64>,
227 to_unix: Option<i64>,
228 limit: Option<usize>,
229 ) -> Result<serde_json::Value, TornError> {
230 let lim = limit.unwrap_or(100);
231 let mut path = format!("/faction/news?cat={}&limit={}", category, lim);
232 if let Some(from) = from_unix {
233 path.push_str(&format!("&from={}", from));
234 }
235 if let Some(to) = to_unix {
236 path.push_str(&format!("&to={}", to));
237 }
238 self.get(&path, false).await
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245 use serde_json::json;
246
247 #[tokio::test]
248 async fn test_mock_client_operations() {
249 let client = TornClient::new_mock();
250 client
251 .set_mock_response("/faction/rankedwars", json!({ "wars": [40711] }))
252 .await;
253
254 let res = client.get_ranked_wars().await.unwrap();
255 assert_eq!(res["wars"][0], 40711);
256
257 client
258 .set_mock_response(
259 "/faction/news?cat=depositFunds&limit=100",
260 json!({ "news": [{ "id": "1", "text": "deposited" }] }),
261 )
262 .await;
263
264 let news = client.get_faction_news("depositFunds", None, None, None).await.unwrap();
265 assert_eq!(news["news"][0]["id"], "1");
266 }
267}