Skip to main content

rpfm_server/
main.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! # `rpfm_server`
12//!
13//! Backend process for [Rusted PackFile Manager][rpfm]. Hosts the heavy work
14//! that the Qt6 UI ([`rpfm_ui`][ui]) and AI / MCP clients drive remotely:
15//! Pack I/O, schema decoding, diagnostics, search, dependencies, optimisation
16//! and so on.
17//!
18//! [rpfm]: https://github.com/Frodo45127/rpfm
19//! [ui]: https://crates.io/crates/rpfm_ui
20//!
21//! ## Architecture
22//!
23//! The server is built on [`axum`] (HTTP + WebSocket) and [`tokio`]. It binds
24//! to `127.0.0.1:45127` by default and exposes three endpoints:
25//!
26//! | Endpoint    | Method | Purpose                                                                          |
27//! |-------------|--------|----------------------------------------------------------------------------------|
28//! | `/ws`       | GET    | WebSocket upgrade. Carries the [`rpfm_ipc`] command/response protocol.           |
29//! | `/version`  | GET    | REST: report the server build version + pid.    |
30//! | `/sessions` | GET    | REST: list every active session (used by the UI session picker).                 |
31//! | `/mcp`      | *      | MCP `StreamableHttpService` exposing the same surface to AI / MCP clients.       |
32//!
33//! Every client connection is wrapped in a [`session::Session`] managed by a
34//! [`session::SessionManager`]. Each session owns a dedicated background
35//! thread (see [`background_thread`]) that processes commands serially against
36//! its own in-memory state (open packs, dependency cache, settings cache),
37//! so multiple concurrent clients can't step on each other.
38//!
39//! ## Modules
40//!
41//! - [`background_thread`] — central command dispatcher; one async loop per session.
42//! - [`comms`] — generic mpsc-based request/response abstraction used to talk
43//!   to the background thread.
44//! - [`server_websocket`] — `/ws` upgrade handler and message multiplexer.
45//! - [`server_mcp`] — `/mcp` endpoint: tools, prompts, resources for MCP clients.
46//! - [`session`] — `SessionManager`, `Session`, lifecycle and timeout handling.
47//! - [`settings`] — JSON-backed settings store with batch-write optimisation.
48//! - [`updater`] — self-update checks against GitHub releases.
49//!
50//! ## Telemetry
51//!
52//! Logging, panic capture and action telemetry are wired through
53//! [`rpfm_telemetry`]. The Sentry guard returned by [`Logger::init`] is held
54//! for the process lifetime in [`main`].
55
56// Under windows, hide the server window by default.
57#![windows_subsystem = "windows"]
58
59use axum::{extract::State, routing::get, Json, Router};
60use rmcp::transport::streamable_http_server::{session::local::LocalSessionManager, StreamableHttpService};
61use tokio::net::TcpListener;
62use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer};
63
64use std::net::SocketAddr;
65use std::path::PathBuf;
66use std::sync::Arc;
67
68use rpfm_ipc::helpers::SessionInfo;
69use rpfm_ipc::messages::{Command, Response};
70use rpfm_ipc::settings_keys::{ANONYMOUS_TELEMETRY_ID, ENABLE_CRASH_REPORTS, ENABLE_USAGE_TELEMETRY};
71
72use rpfm_telemetry::{Logger, SentryLayer, SENTRY_DSN, info, release_name, warn};
73
74use crate::server_mcp::McpServer;
75use crate::session::SessionManager;
76use crate::settings::{error_path, init_config_path, Settings};
77use crate::server_websocket::ws_handler;
78
79pub mod background_thread;
80pub mod ceo_builder;
81pub mod comms;
82pub mod server_mcp;
83pub mod server_websocket;
84pub mod session;
85pub mod settings;
86#[cfg(test)] mod settings_test;
87pub mod translation_hub;
88pub mod updater;
89#[cfg(test)] mod updater_test;
90
91use mimalloc::MiMalloc;
92
93#[global_allocator]
94static GLOBAL: MiMalloc = MiMalloc;
95
96//-------------------------------------------------------------------------------//
97//                                  Constants
98//-------------------------------------------------------------------------------//
99
100/// Sentry DSN used for crash reports.
101const SENTRY_DSN_KEY: &str = match option_env!("RPFM_SERVER_SENTRY_DSN") {
102    Some(dsn) => dsn,
103    None => "",
104};
105
106/// PostHog project API key used for telemetry and feedback.
107const POSTHOG_API_KEY_VALUE: &str = match option_env!("RPFM_SERVER_POSTHOG_API_KEY") {
108    Some(key) => key,
109    None => "",
110};
111
112/// Client ID of RPFM's GitHub OAuth App, used to sign in to submit translations.
113pub const GITHUB_OAUTH_CLIENT_ID: &str = match option_env!("RPFM_SERVER_GITHUB_OAUTH_CLIENT_ID") {
114    Some(id) => id,
115    None => "",
116};
117
118/// Default IP address the HTTP server binds to (`127.0.0.1` / loopback).
119const DEFAULT_ADDRESS: [u8; 4] = [127, 0, 0, 1];
120
121/// Default TCP port the HTTP server listens on.
122const DEFAULT_PORT: u16 = 45127;
123
124/// Organisation domain used to derive the OS-specific config directory
125/// (mirrors `QCoreApplication::organizationDomain` on the UI side).
126const ORG_DOMAIN: &str = "com";
127
128/// Organisation name used to derive the OS-specific config directory.
129const ORG_NAME: &str = "FrodoWazEre";
130
131/// Application name used to derive the OS-specific config directory.
132const APP_NAME: &str = "rpfm";
133
134//-------------------------------------------------------------------------------//
135//                                  Functions
136//-------------------------------------------------------------------------------//
137
138/// Process entry point.
139///
140/// Initialises the Sentry/telemetry guard, primes the telemetry toggles from
141/// persisted settings, builds the [`session::SessionManager`], wires the
142/// `axum` router (`/ws`, `/sessions`, `/mcp`) and starts the listener on
143/// [`DEFAULT_ADDRESS`]:[`DEFAULT_PORT`].
144///
145/// Returns when the listener stops accepting (typically after every session
146/// has been cleaned up — the cleanup task in [`session::SessionManager`]
147/// terminates the process when the session set drains).
148#[tokio::main]
149async fn main() {
150
151    // Sentry client guard, so we can reuse it later on and keep it in scope for the entire duration of the program.
152    // Must be initialized before the tracing subscriber so the SentryLayer can capture spans.
153    *SENTRY_DSN.write().unwrap() = SENTRY_DSN_KEY.to_owned();
154    rpfm_telemetry::set_posthog_api_key(POSTHOG_API_KEY_VALUE);
155    let guard = Logger::init(&{
156        init_config_path().expect("Error while trying to initialize config path. We're fucked.");
157        error_path().unwrap_or_else(|_| PathBuf::from("."))
158    }, true, false, release_name!()).expect("Failed to initialize logging system.");
159
160    // Setup tracing subscriber for logging, redirecting to stderr to avoid interfering with MCP.
161    // The SentryLayer captures tracing spans/events as Sentry breadcrumbs and performance spans.
162    tracing_subscriber::registry()
163        .with(tracing_subscriber::fmt::layer()
164            .with_writer(std::io::stderr)
165            .with_filter(tracing_subscriber::filter::LevelFilter::INFO))
166        .with(SentryLayer::default())
167        .init();
168
169    if guard.is_enabled() {
170        info!("Sentry logging support for RPFM SERVER enabled. Starting...");
171    } else {
172        info!("Sentry logging support for RPFM SERVER disabled. Starting...");
173    }
174
175    // Read telemetry settings from disk before any sessions spin up so early commands
176    // are counted and crash reports respect the user's choice. Background threads will
177    // refresh these whenever the settings change.
178    if let Ok(settings) = Settings::init(false) {
179        rpfm_telemetry::set_usage_telemetry_enabled(settings.bool(ENABLE_USAGE_TELEMETRY));
180        rpfm_telemetry::set_crash_reports_enabled(settings.bool(ENABLE_CRASH_REPORTS));
181
182        let id = settings.string(ANONYMOUS_TELEMETRY_ID);
183        if !id.is_empty() {
184            rpfm_telemetry::set_distinct_id(&id);
185        }
186    }
187
188    // Attach breakdown dimensions to every PostHog event in the next flush.
189    rpfm_telemetry::set_event_property("release", serde_json::Value::from(env!("CARGO_PKG_VERSION")));
190    rpfm_telemetry::set_event_property("os", serde_json::Value::from(std::env::consts::OS));
191    rpfm_telemetry::set_event_property("is_beta", serde_json::Value::from(rpfm_telemetry::is_beta()));
192
193    // Create the session manager to handle per-client sessions,
194    // and start the background cleanup task for expired sessions.
195    let session_manager: Arc<SessionManager> = Arc::new(SessionManager::default());
196    SessionManager::start_cleanup_task(session_manager.clone());
197
198    // Create an MCP service with its own session for MCP clients.
199    let sm = session_manager.clone();
200    let http_service = StreamableHttpService::new(
201        move || {
202            let session = sm.create_mcp_session();
203            Ok(McpServer::new(session))
204        },
205        LocalSessionManager::default().into(),
206        Default::default(),
207    );
208
209    // Setup the endpoints for the server.
210    let app = Router::new()
211        .route("/ws", get(ws_handler))
212        .route("/version", get(version_handler))
213        .route("/sessions", get(sessions_handler))
214        .nest_service("/mcp", http_service)
215        .with_state(session_manager);
216
217    let addr = SocketAddr::from((DEFAULT_ADDRESS, DEFAULT_PORT));
218    match TcpListener::bind(addr).await {
219        Ok(listener) => {
220            info!("Listening on {}", addr);
221            axum::serve(listener, app).await.unwrap();
222        }
223        Err(err) => {
224            warn!("Failed to bind to address {}: {}\n\nThis usually means you got another copy of the server running. Either use that one, or stop it and try again.", addr, err);
225        }
226    }
227}
228
229/// REST endpoint reporting the server's build version and process id.
230///
231/// Returns a JSON object: `{ "version": "5.0.0", "pid": 1234 }`.
232async fn version_handler() -> Json<serde_json::Value> {
233    Json(serde_json::json!({
234        "version": env!("CARGO_PKG_VERSION"),
235        "pid": std::process::id(),
236    }))
237}
238
239/// REST endpoint to get information about all active sessions.
240///
241/// Returns a JSON array of [`SessionInfo`] objects containing:
242/// - `session_id`: Unique session identifier
243/// - `connection_count`: Number of active WebSocket connections
244/// - `timeout_remaining_secs`: Seconds until session cleanup (if disconnected)
245/// - `is_shutting_down`: Whether session is marked for shutdown
246///
247/// This endpoint is used by the UI's session management dialog to display
248/// available sessions and allow users to connect to specific ones.
249async fn sessions_handler(State(session_manager): State<Arc<SessionManager>>) -> Json<Vec<SessionInfo>> {
250    let sessions = session_manager.get_sessions_info();
251    info!("Sessions endpoint queried: {} active session(s)", sessions.len());
252    Json(sessions)
253}