Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/mobhub/blob/main/src/server.rs # mobhub Decentralized model and agent weights distribution network Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `mobhub / src / server.rs` 565 lines ยท 19405 bytes Raw Blame History 1 //! Ultra-low-latency Axum HTTP service and embedded dashboard UI. 2 3 use crate::gym::{self, SessionParams}; 4 use crate::payout::{self, PayoutOptions, PayoutPolicy, PayoutResult, MemberInput}; 5 use crate::reconcile::{self, GiveForMatch, ParsedDisbursement, ReconcileSummary, RegisterRowForMatch}; 6 use crate::storage::{Database, StoredDisbursement, StoredWar}; 7 use crate::torn::TornClient; 8 use crate::valuation::{self, ValuationBreakdown}; 9 use crate::vault; 10 11 use axum::extract::{Path, Query, State}; 12 use axum::http::{header, StatusCode}; 13 use axum::response::{Html, IntoResponse, Json}; 14 use axum::routing::{get, post}; 15 use axum::Router; 16 use serde::Deserialize; 17 use serde_json::json; 18 use std::net::SocketAddr; 19 use std::sync::Arc; 20 use tower_http::cors::CorsLayer; 21 use tower_http::trace::TraceLayer; 22 23 #[derive(Clone)] 24 pub struct AppState { 25 pub storage: Database, 26 pub torn: TornClient, 27 pub faction_id: i64, 28 } 29 30 #[derive(Debug, Deserialize)] 31 pub struct PayoutComputeRequest { 32 pub cache_value: i64, 33 pub policy: PayoutPolicy, 34 pub members: Vec, 35 #[serde(default)] 36 pub options: PayoutOptions, 37 } 38 39 #[derive(Debug, Deserialize)] 40 pub struct ValuationRequest { 41 pub respect: f64, 42 pub respect_rate: f64, 43 pub armory_value: f64, 44 pub faction_cash: f64, 45 } 46 47 #[derive(Debug, Deserialize)] 48 pub struct CsvExportRequest { 49 pub result: PayoutResult, 50 pub faction_id: Option, 51 } 52 53 #[derive(Debug, Deserialize)] 54 pub struct ReconcileMatchRequest { 55 pub gives: Vec, 56 pub register: Vec, 57 #[serde(default)] 58 pub tolerance_pct: Option, 59 } 60 61 #[derive(Debug, Deserialize)] 62 pub struct DisbursementsQuery { 63 pub war_id: Option, 64 } 65 66 pub fn create_router(state: AppState) -> Router { 67 Router::new() 68 .route("/", get(dashboard_handler)) 69 .route("/health", get(health_handler)) 70 .route("/status", get(status_handler)) 71 .route("/api/payout/compute", post(payout_compute_handler)) 72 .route("/api/payout/export-csv", post(payout_csv_handler)) 73 .route("/api/valuation/compute", post(valuation_compute_handler)) 74 .route("/api/gym/simulate", post(gym_simulate_handler)) 75 .route("/api/reconcile/parse", post(reconcile_parse_handler)) 76 .route("/api/reconcile/match", post(reconcile_match_handler)) 77 .route("/api/disbursements", get(list_disbursements_handler).post(save_disbursements_handler)) 78 .route("/api/wars", get(list_wars_handler).post(create_war_handler)) 79 .route("/api/wars/:id", get(get_war_handler)) 80 .route("/api/balances", get(list_balances_handler)) 81 .layer(CorsLayer::permissive()) 82 .layer(TraceLayer::new_for_http()) 83 .with_state(Arc::new(state)) 84 } 85 86 pub async fn run_server(port: u16, state: AppState) -> Result<(), Box> { 87 let app = create_router(state); 88 let addr = SocketAddr::from(([0, 0, 0, 0], port)); 89 tracing::info!("MobHub native server listening on http://{}", addr); 90 91 let listener = tokio::net::TcpListener::bind(addr).await?; 92 axum::serve(listener, app).await?; 93 Ok(()) 94 } 95 96 async fn health_handler() -> impl IntoResponse { 97 Json(json!({ 98 "status": "ok", 99 "service": "mobhub", 100 "engine": "native-rust-axum", 101 "version": env!("CARGO_PKG_VERSION") 102 })) 103 } 104 105 async fn status_handler() -> impl IntoResponse { 106 let tpm_active = vault::is_torn_key_present(); 107 Json(json!({ 108 "status": "ok", 109 "service": "mobhub", 110 "tpm_vault_active": tpm_active, 111 "runtime": "native-arm64-rust", 112 "version": env!("CARGO_PKG_VERSION") 113 })) 114 } 115 116 async fn payout_compute_handler( 117 Json(req): Json, 118 ) -> Result, (StatusCode, Json)> { 119 let res = payout::compute_payout(req.cache_value, &req.policy, &req.members, &req.options); 120 Ok(Json(res)) 121 } 122 123 async fn payout_csv_handler( 124 State(state): State>, 125 Json(req): Json, 126 ) -> impl IntoResponse { 127 let fid = req.faction_id.unwrap_or(state.faction_id); 128 let csv_content = payout::export_payout_csv(&req.result, fid); 129 130 ( 131 [ 132 (header::CONTENT_TYPE, "text/csv; charset=utf-8"), 133 ( 134 header::CONTENT_DISPOSITION, 135 "attachment; filename=\"payout.csv\"", 136 ), 137 ], 138 csv_content, 139 ) 140 } 141 142 async fn valuation_compute_handler( 143 Json(req): Json, 144 ) -> Json { 145 let res = valuation::compute_valuation( 146 req.respect, 147 req.respect_rate, 148 req.armory_value, 149 req.faction_cash, 150 ); 151 Json(res) 152 } 153 154 async fn gym_simulate_handler( 155 Json(req): Json, 156 ) -> Json { 157 let res = gym::run_mojo_optimizer(&req); 158 Json(res) 159 } 160 161 async fn reconcile_parse_handler( 162 Json(news_payload): Json, 163 ) -> Json> { 164 let disbursements = reconcile::parse_disbursements(&news_payload); 165 Json(disbursements) 166 } 167 168 async fn reconcile_match_handler( 169 Json(req): Json, 170 ) -> Json { 171 let tol = req.tolerance_pct.unwrap_or(0.005); 172 let summary = reconcile::match_disbursements(&req.gives, &req.register, tol); 173 Json(summary) 174 } 175 176 async fn list_disbursements_handler( 177 State(state): State>, 178 Query(query): Query, 179 ) -> Result>, (StatusCode, String)> { 180 state 181 .storage 182 .list_disbursements(query.war_id) 183 .map(Json) 184 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())) 185 } 186 187 #[derive(Debug, Deserialize)] 188 pub struct SaveDisbursementPayload { 189 pub news_id: String, 190 pub war_id: Option, 191 pub recipient_torn_id: i64, 192 pub recipient_name: Option, 193 pub amount: i64, 194 pub occurred_at: Option, 195 pub matched_register_id: Option, 196 pub raw_text: String, 197 } 198 199 async fn save_disbursements_handler( 200 State(state): State>, 201 Json(payload): Json, 202 ) -> Result<(StatusCode, Json), (StatusCode, String)> { 203 state 204 .storage 205 .save_disbursement( 206 &payload.news_id, 207 payload.war_id, 208 payload.recipient_torn_id, 209 payload.recipient_name.as_deref(), 210 payload.amount, 211 payload.occurred_at.as_deref(), 212 payload.matched_register_id, 213 &payload.raw_text, 214 ) 215 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 216 217 Ok((StatusCode::CREATED, Json(json!({ "saved": true, "news_id": payload.news_id })))) 218 } 219 220 async fn list_wars_handler( 221 State(state): State>, 222 ) -> Result>, (StatusCode, String)> { 223 state 224 .storage 225 .list_wars() 226 .map(Json) 227 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())) 228 } 229 230 #[derive(Debug, Deserialize)] 231 struct CreateWarPayload { 232 id: i64, 233 name: String, 234 cache_value: i64, 235 status: String, 236 data: serde_json::Value, 237 } 238 239 async fn create_war_handler( 240 State(state): State>, 241 Json(payload): Json, 242 ) -> Result<(StatusCode, Json), (StatusCode, String)> { 243 let data_str = payload.data.to_string(); 244 state 245 .storage 246 .save_war( 247 payload.id, 248 &payload.name, 249 payload.cache_value, 250 &payload.status, 251 &data_str, 252 ) 253 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; 254 255 Ok(( 256 StatusCode::CREATED, 257 Json(json!({ "recorded": true, "war_id": payload.id })), 258 )) 259 } 260 261 async fn get_war_handler( 262 State(state): State>, 263 Path(id): Path, 264 ) -> Result, (StatusCode, String)> { 265 match state.storage.get_war(id) { 266 Ok(Some(w)) => Ok(Json(w)), 267 Ok(None) => Err((StatusCode::NOT_FOUND, "War not found".to_string())), 268 Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), 269 } 270 } 271 272 async fn list_balances_handler( 273 State(state): State>, 274 ) -> Result>, (StatusCode, String)> { 275 state 276 .storage 277 .list_balances() 278 .map(Json) 279 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())) 280 } 281 282 async fn dashboard_handler(State(state): State>) -> Html { 283 let tpm_active = vault::is_torn_key_present(); 284 let status_badge = if tpm_active { 285 r#"TPM Vault Active"# 286 } else { 287 r#"Vault Unbound"# 288 }; 289 290 let html = format!(r#" 291 292 293 294 295 MobHub: Sovereign Faction Ops 296 406 407 408
409

MobHub Sovereign Faction Suite

410
411 {status_badge} 412 Faction: #{faction_id} 413
414
415
416 417
418

MobPay Payout Engine

419 420 421 422 426 427 428 429 430 431
Ready.
432
433 434 435
436

MobWorth Faction Valuation

437 438 439 440 441 442 443 444 445 446
Ready.
447
448 449 450
451

MobGym Mojo Accelerator

452 453 459 460 461 462 463 464 465 466 467 468
Ready.
469
470
471 472 561 562 "#, status_badge = status_badge, faction_id = state.faction_id); 563 564 Html(html) 565 }