LINE1 10 20 30 40 50 60 70 80 90 1001use std::sync::Mutex;23use actix_web::{4 HttpResponse, Responder, get, post,5 web::{self, Bytes},6};7use serde::{Deserialize, Serialize};8use tokio::sync::broadcast;910use crate::world::{JoinError, Look, World};1112pub struct AppState {13 pub world: Mutex<World>,14 pub events: broadcast::Sender<String>,15}1617impl AppState {18 pub fn new() -> Self {19 let (events, _) = broadcast::channel(256);20 Self { world: Mutex::new(World::new()), events }21 }2223 24 pub fn send_logs(&self, logs: Vec<String>) {25 for line in logs {26 let data = serde_json::json!({ "text": line }).to_string();27 let _ = self.events.send(format!("event: log\ndata: {data}\n\n"));28 }29 }30}3132#[derive(Deserialize)]33struct JoinReq {34 name: String,35 look: Look,36}3738#[derive(Serialize)]39struct JoinRes {40 id: String,41}4243#[derive(Deserialize)]44struct InputReq {45 id: String,46 dx: f32,47 dy: f32,48}4950#[derive(Deserialize)]51struct IdReq {52 id: String,53}5455#[get("/api/map")]56async fn map(state: web::Data<AppState>) -> impl Responder {57 web::Json(state.world.lock().unwrap().map.view())58}5960#[post("/api/join")]61async fn join(state: web::Data<AppState>, body: web::Json<JoinReq>) -> impl Responder {62 let result = {63 let mut world = state.world.lock().unwrap();64 let joined = world.join(&body.name, body.look);65 let name = body.name.trim().to_string();66 joined.map(|id| (id, name))67 };68 match result {69 Ok((id, name)) => {70 state.send_logs(vec![format!("{} came in.", if name.is_empty() { "Friend" } else { &name })]);71 HttpResponse::Ok().json(JoinRes { id })72 }73 Err(JoinError::Full) => HttpResponse::Conflict().body("The flat is full. Try again soon."),74 }75}7677#[post("/api/input")]78async fn input(state: web::Data<AppState>, body: web::Json<InputReq>) -> impl Responder {79 let ok = state.world.lock().unwrap().set_input(&body.id, body.dx, body.dy);80 if ok { HttpResponse::NoContent().finish() } else { HttpResponse::NotFound().finish() }81}8283#[post("/api/action")]84async fn action(state: web::Data<AppState>, body: web::Json<IdReq>) -> impl Responder {85 let logs = state.world.lock().unwrap().act(&body.id);86 match logs {87 Some(logs) => {88 state.send_logs(logs);89 HttpResponse::NoContent().finish()90 }91 None => HttpResponse::NotFound().finish(),92 }93}9495#[post("/api/leave")]96async fn leave(state: web::Data<AppState>, body: web::Json<IdReq>) -> impl Responder {97 let logs = state.world.lock().unwrap().leave(&body.id);98 state.send_logs(logs);99 HttpResponse::NoContent().finish()100}101102#[get("/api/events")]103async fn event_stream(state: web::Data<AppState>) -> impl Responder {104 let rx = state.events.subscribe();105 let stream = futures_util::stream::unfold(rx, |mut rx| async move {106 loop {107 match rx.recv().await {108 Ok(frame) => return Some((Ok::<Bytes, actix_web::Error>(Bytes::from(frame)), rx)),109 Err(broadcast::error::RecvError::Lagged(_)) => continue,110 Err(broadcast::error::RecvError::Closed) => return None,111 }112 }113 });114 HttpResponse::Ok()115 .content_type("text/event-stream")116 .insert_header(("Cache-Control", "no-cache"))117 .insert_header(("X-Accel-Buffering", "no"))118 .streaming(stream)119}120121pub fn configure(cfg: &mut web::ServiceConfig) {122 cfg.service(map)123 .service(join)124 .service(input)125 .service(action)126 .service(leave)127 .service(event_stream);128}