ctb_io_webui/controllers/
rpc.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use axum::{
30 Json,
31 extract::{Path, State},
32 response::{IntoResponse, Response},
33};
34use serde::{Deserialize, Serialize};
35use serde_json::Value;
36
37use crate::AppState;
38use crate::session_auth::AuthenticatedUser;
39
40pub mod calculator;
41pub mod center_of_gravity;
42pub mod eite;
43
44#[derive(Deserialize)]
46pub struct RpcRequest {
47 pub function: String,
48 pub args: Vec<Value>,
49}
50
51#[derive(Serialize)]
53pub struct RpcResponse {
54 pub value: Value,
55}
56
57pub async fn post_rpc_call(
60 State(state): State<AppState>,
61 user: AuthenticatedUser,
62 Path(service): Path<String>,
63 Json(payload): Json<RpcRequest>,
64) -> Response {
65 let result = match service.as_str() {
66 "eite" => {
67 let user_id = user.user.lock().await.local_id();
68 let mut eite_states = state.eite_states.lock().await;
69 let eite_state = eite_states
70 .entry(user_id)
71 .or_insert_with(ctb_formats_eite::eite_state::EiteState::new);
72 eite::handle_eite_call(eite_state, &payload.function, &payload.args)
73 .await
74 }
75 "calculator" => {
76 calculator::handle_calculator_call(&payload.function, &payload.args)
77 .await
78 }
79 "center_of_gravity" | "center-of-gravity" => {
80 center_of_gravity::handle_center_of_gravity_call(
81 &payload.function,
82 &payload.args,
83 )
84 .await
85 }
86 _ => Err(anyhow::anyhow!("Unknown RPC service: {service}")),
87 };
88
89 match result {
90 Ok(val) => Json(RpcResponse { value: val }).into_response(),
91 Err(err) => {
92 let err_msg = err.to_string();
93 crate::warn!(
94 "RPC call to service '{}', function '{}' failed: {}",
95 service,
96 payload.function,
97 err_msg.clone()
98 );
99 (axum::http::StatusCode::BAD_REQUEST, err_msg).into_response()
100 }
101 }
102}