Add: windows mvp - transparent bugs not fixed
This commit is contained in:
405
crates/sprimo-api/src/lib.rs
Normal file
405
crates/sprimo-api/src/lib.rs
Normal file
@@ -0,0 +1,405 @@
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{Json, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
use sprimo_protocol::v1::{
|
||||
CommandEnvelope, ErrorResponse, FrontendStateSnapshot, HealthResponse,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use thiserror::Error;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApiConfig {
|
||||
pub bind_addr: SocketAddr,
|
||||
pub auth_token: String,
|
||||
pub app_version: String,
|
||||
pub app_build: String,
|
||||
pub dedupe_capacity: usize,
|
||||
pub dedupe_ttl: Duration,
|
||||
}
|
||||
|
||||
impl ApiConfig {
|
||||
#[must_use]
|
||||
pub fn default_with_token(auth_token: String) -> Self {
|
||||
Self {
|
||||
bind_addr: SocketAddr::from(([127, 0, 0, 1], 32_145)),
|
||||
auth_token,
|
||||
app_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
app_build: "dev".to_string(),
|
||||
dedupe_capacity: 5_000,
|
||||
dedupe_ttl: Duration::from_secs(600),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ApiState {
|
||||
start_at: Instant,
|
||||
auth_token: String,
|
||||
app_version: String,
|
||||
app_build: String,
|
||||
dedupe_capacity: usize,
|
||||
dedupe_ttl: Duration,
|
||||
recent_ids: Mutex<HashMap<Uuid, Instant>>,
|
||||
snapshot: Arc<RwLock<FrontendStateSnapshot>>,
|
||||
command_tx: mpsc::Sender<CommandEnvelope>,
|
||||
}
|
||||
|
||||
impl ApiState {
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
config: ApiConfig,
|
||||
snapshot: Arc<RwLock<FrontendStateSnapshot>>,
|
||||
command_tx: mpsc::Sender<CommandEnvelope>,
|
||||
) -> Self {
|
||||
Self {
|
||||
start_at: Instant::now(),
|
||||
auth_token: config.auth_token,
|
||||
app_version: config.app_version,
|
||||
app_build: config.app_build,
|
||||
dedupe_capacity: config.dedupe_capacity,
|
||||
dedupe_ttl: config.dedupe_ttl,
|
||||
recent_ids: Mutex::new(HashMap::new()),
|
||||
snapshot,
|
||||
command_tx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ApiServerError {
|
||||
#[error("bind failed: {0}")]
|
||||
Bind(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
pub fn app_router(state: Arc<ApiState>) -> Router {
|
||||
Router::new()
|
||||
.route("/v1/health", get(handle_health))
|
||||
.route("/v1/state", get(handle_state))
|
||||
.route("/v1/command", post(handle_command))
|
||||
.route("/v1/commands", post(handle_commands))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
pub async fn run_server(config: ApiConfig, state: Arc<ApiState>) -> Result<(), ApiServerError> {
|
||||
let listener = TcpListener::bind(config.bind_addr).await?;
|
||||
axum::serve(listener, app_router(state))
|
||||
.await
|
||||
.map_err(ApiServerError::Bind)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_health(State(state): State<Arc<ApiState>>) -> Json<HealthResponse> {
|
||||
let snapshot = state
|
||||
.snapshot
|
||||
.read()
|
||||
.expect("frontend snapshot lock poisoned");
|
||||
Json(HealthResponse {
|
||||
version: state.app_version.clone(),
|
||||
build: state.app_build.clone(),
|
||||
uptime_seconds: state.start_at.elapsed().as_secs(),
|
||||
active_sprite_pack: snapshot.active_sprite_pack.clone(),
|
||||
capabilities: snapshot.capabilities.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_state(
|
||||
State(state): State<Arc<ApiState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<FrontendStateSnapshot>, ApiError> {
|
||||
require_auth(&headers, &state)?;
|
||||
let snapshot = state
|
||||
.snapshot
|
||||
.read()
|
||||
.map_err(|_| ApiError::Internal("snapshot lock poisoned".to_string()))?
|
||||
.clone();
|
||||
Ok(Json(snapshot))
|
||||
}
|
||||
|
||||
async fn handle_command(
|
||||
State(state): State<Arc<ApiState>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
require_auth(&headers, &state)?;
|
||||
let command: CommandEnvelope =
|
||||
serde_json::from_slice(&body).map_err(|e| ApiError::BadJson(e.to_string()))?;
|
||||
enqueue_if_new(&state, command).await?;
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
|
||||
async fn handle_commands(
|
||||
State(state): State<Arc<ApiState>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, ApiError> {
|
||||
require_auth(&headers, &state)?;
|
||||
let commands: Vec<CommandEnvelope> =
|
||||
serde_json::from_slice(&body).map_err(|e| ApiError::BadJson(e.to_string()))?;
|
||||
for command in commands {
|
||||
enqueue_if_new(&state, command).await?;
|
||||
}
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
|
||||
async fn enqueue_if_new(state: &ApiState, command: CommandEnvelope) -> Result<(), ApiError> {
|
||||
let now = Instant::now();
|
||||
{
|
||||
let mut ids = state
|
||||
.recent_ids
|
||||
.lock()
|
||||
.map_err(|_| ApiError::Internal("dedupe lock poisoned".to_string()))?;
|
||||
|
||||
ids.retain(|_, seen_at| now.duration_since(*seen_at) < state.dedupe_ttl);
|
||||
if ids.contains_key(&command.id) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if ids.len() >= state.dedupe_capacity {
|
||||
let oldest = ids
|
||||
.iter()
|
||||
.min_by_key(|(_, seen_at)| *seen_at)
|
||||
.map(|(id, _)| *id);
|
||||
if let Some(oldest) = oldest {
|
||||
ids.remove(&oldest);
|
||||
}
|
||||
}
|
||||
|
||||
ids.insert(command.id, now);
|
||||
}
|
||||
|
||||
state
|
||||
.command_tx
|
||||
.send(command)
|
||||
.await
|
||||
.map_err(|_| ApiError::Internal("command receiver dropped".to_string()))
|
||||
}
|
||||
|
||||
fn require_auth(headers: &HeaderMap, state: &ApiState) -> Result<(), ApiError> {
|
||||
let raw = headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or(ApiError::Unauthorized)?;
|
||||
let expected = format!("Bearer {}", state.auth_token);
|
||||
if raw == expected {
|
||||
return Ok(());
|
||||
}
|
||||
Err(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
enum ApiError {
|
||||
Unauthorized,
|
||||
BadJson(String),
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
match self {
|
||||
Self::Unauthorized => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(ErrorResponse {
|
||||
code: "unauthorized".to_string(),
|
||||
message: "missing or invalid bearer token".to_string(),
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Self::BadJson(message) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorResponse {
|
||||
code: "bad_json".to_string(),
|
||||
message,
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
Self::Internal(message) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
code: "internal".to_string(),
|
||||
message,
|
||||
}),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{app_router, ApiConfig, ApiState};
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use sprimo_protocol::v1::{
|
||||
CapabilityFlags, CommandEnvelope, FrontendCommand, FrontendStateSnapshot,
|
||||
};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use tokio::sync::mpsc;
|
||||
use tower::ServiceExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
fn build_state() -> (Arc<ApiState>, mpsc::Receiver<CommandEnvelope>) {
|
||||
let snapshot =
|
||||
FrontendStateSnapshot::idle(CapabilityFlags::default());
|
||||
let snapshot = Arc::new(RwLock::new(snapshot));
|
||||
let (tx, rx) = mpsc::channel(8);
|
||||
(
|
||||
Arc::new(ApiState::new(
|
||||
ApiConfig::default_with_token("token".to_string()),
|
||||
snapshot,
|
||||
tx,
|
||||
)),
|
||||
rx,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_does_not_require_auth() {
|
||||
let (state, _) = build_state();
|
||||
let app = app_router(state);
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/health")
|
||||
.body(Body::empty())
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn command_requires_auth() {
|
||||
let (state, _) = build_state();
|
||||
let app = app_router(state);
|
||||
let command = CommandEnvelope {
|
||||
id: Uuid::new_v4(),
|
||||
ts_ms: 1,
|
||||
command: FrontendCommand::Toast {
|
||||
text: "hi".to_string(),
|
||||
ttl_ms: None,
|
||||
},
|
||||
};
|
||||
let body = serde_json::to_vec(&command).expect("json");
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/command")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn command_accepts_with_auth() {
|
||||
let (state, mut rx) = build_state();
|
||||
let app = app_router(state);
|
||||
let command = CommandEnvelope {
|
||||
id: Uuid::new_v4(),
|
||||
ts_ms: 1,
|
||||
command: FrontendCommand::Toast {
|
||||
text: "hi".to_string(),
|
||||
ttl_ms: None,
|
||||
},
|
||||
};
|
||||
let body = serde_json::to_vec(&command).expect("json");
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/command")
|
||||
.header("content-type", "application/json")
|
||||
.header("authorization", "Bearer token")
|
||||
.body(Body::from(body))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::ACCEPTED);
|
||||
let received = rx.recv().await.expect("forwarded command");
|
||||
assert_eq!(received.id, command.id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_json_returns_bad_request() {
|
||||
let (state, _) = build_state();
|
||||
let app = app_router(state);
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/command")
|
||||
.header("content-type", "application/json")
|
||||
.header("authorization", "Bearer token")
|
||||
.body(Body::from("{ not-json }"))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_command_is_deduped() {
|
||||
let (state, mut rx) = build_state();
|
||||
let app = app_router(state);
|
||||
let command = CommandEnvelope {
|
||||
id: Uuid::new_v4(),
|
||||
ts_ms: 1,
|
||||
command: FrontendCommand::Toast {
|
||||
text: "hi".to_string(),
|
||||
ttl_ms: None,
|
||||
},
|
||||
};
|
||||
let body = serde_json::to_vec(&command).expect("json");
|
||||
|
||||
let first = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/command")
|
||||
.header("content-type", "application/json")
|
||||
.header("authorization", "Bearer token")
|
||||
.body(Body::from(body.clone()))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(first.status(), StatusCode::ACCEPTED);
|
||||
|
||||
let second = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/command")
|
||||
.header("content-type", "application/json")
|
||||
.header("authorization", "Bearer token")
|
||||
.body(Body::from(body))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(second.status(), StatusCode::ACCEPTED);
|
||||
|
||||
let one = rx.recv().await.expect("first command");
|
||||
assert_eq!(one.id, command.id);
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user