High-performance implementation of plcbundle written in Rust
at main 61 lines 1.6 kB view raw
1use crate::server::ServerState; 2use crate::server::error::{bad_request, internal_error, task_join_error}; 3use axum::{ 4 extract::{Query, State}, 5 http::StatusCode, 6 response::IntoResponse, 7}; 8use serde::Deserialize; 9use serde_json::json; 10use std::sync::Arc; 11use std::time::{SystemTime, UNIX_EPOCH}; 12 13#[derive(Deserialize)] 14pub struct RandomQuery { 15 pub count: Option<usize>, 16 pub seed: Option<u64>, 17} 18 19pub async fn handle_random_dids( 20 State(state): State<ServerState>, 21 Query(params): Query<RandomQuery>, 22) -> impl IntoResponse { 23 let count = params.count.unwrap_or(10); 24 if count > 1000 { 25 return bad_request("count must be <= 1000").into_response(); 26 } 27 let effective_seed = params.seed.unwrap_or_else(|| { 28 SystemTime::now() 29 .duration_since(UNIX_EPOCH) 30 .unwrap() 31 .as_nanos() as u64 32 }); 33 if count == 0 { 34 return ( 35 StatusCode::OK, 36 axum::Json(json!({ "dids": [], "count": 0, "seed": effective_seed })), 37 ) 38 .into_response(); 39 } 40 41 let dids = match tokio::task::spawn_blocking({ 42 let manager = Arc::clone(&state.manager); 43 move || manager.sample_random_dids(count, Some(effective_seed)) 44 }) 45 .await 46 { 47 Ok(Ok(list)) => list, 48 Ok(Err(e)) => return internal_error(&e.to_string()).into_response(), 49 Err(e) => return task_join_error(e).into_response(), 50 }; 51 52 ( 53 StatusCode::OK, 54 axum::Json(json!({ 55 "dids": dids, 56 "count": count, 57 "seed": effective_seed 58 })), 59 ) 60 .into_response() 61}