ctb_io_webui/controllers/
rpc.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Generic JSON-RPC controller dispatching calls to specialized tool submodules.
21
22#[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/// Generic request payload for JSON-RPC tool endpoints.
45#[derive(Deserialize)]
46pub struct RpcRequest {
47    pub function: String,
48    pub args: Vec<Value>,
49}
50
51/// Generic response payload for JSON-RPC tool endpoints.
52#[derive(Serialize)]
53pub struct RpcResponse {
54    pub value: Value,
55}
56
57/// Main consolidated JSON-RPC endpoint for tools.
58/// Requires an authenticated session and routes by service name.
59pub 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}