Fixed the .NET server shutting down while the runtime still runs (#1237)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-26 12:01:08 +01:00
1 parent 9ebfce3855
commit 902e406e1d
22 files changed
+923 -115

No files matched your search

+50 -5
View File
@@ -455,15 +455,32 @@ fn log_with_level(
}
}
/// Logs an event from the .NET server.
pub async fn log_event(Json(event): Json<LogEvent>) -> Json<LogEventResponse> {
/// Logs a batch of events from the .NET server, in the order the server sent them.
///
/// The server sends its events in batches. With one request per event, a burst of events, such as
/// the changes of a build in a watched folder, flooded the one HTTP/2 connection which all calls of
/// the server share, until the runtime closed it.
pub async fn log_events(Json(request): Json<LogEventsRequest>) -> Json<LogEventResponse> {
log_dotnet_events(log::logger(), &request.events);
Json(LogEventResponse { success: true, issue: String::new() })
}
/// Logs the given events from the .NET server, one after another.
fn log_dotnet_events(logger: &dyn log::Log, events: &[LogEvent]) {
for event in events {
log_dotnet_event(logger, event);
}
}
/// Logs one event from the .NET server.
fn log_dotnet_event(logger: &dyn log::Log, event: &LogEvent) {
let level = parse_dotnet_log_level(&event.level);
let message = event.message.as_str();
let category = event.category.as_str();
let created_at = parse_dotnet_timestamp(&event.timestamp);
log_with_level(
log::logger(),
logger,
level,
category,
created_at,
@@ -481,8 +498,6 @@ pub async fn log_event(Json(event): Json<LogEvent>) -> Json<LogEventResponse> {
if created_at.is_none() && !WARNED_ABOUT_UNREADABLE_DOTNET_TIMESTAMP.swap(true, Ordering::Relaxed) {
log::warn!(Source = ".NET Server", Comp = category; "Could not read the timestamp '{}' of a log event. Such events show the time they arrived instead. This warning appears only once.", event.timestamp);
}
Json(LogEventResponse { success: true, issue: String::new() })
}
/// The response the get log paths request.
@@ -505,6 +520,13 @@ pub struct LogEvent {
stack_trace: Option<String>,
}
/// A batch of log events from the .NET server.
#[derive(Deserialize)]
pub struct LogEventsRequest {
/// The events, in the order they happened.
events: Vec<LogEvent>,
}
/// The response to a log event request.
#[derive(Serialize)]
pub struct LogEventResponse {
@@ -685,6 +707,29 @@ mod tests {
]);
}
#[test]
fn a_batch_of_dotnet_events_is_logged_in_order() {
log::set_max_level(LevelFilter::Info);
// The shape in which the .NET server sends its batches:
let request: LogEventsRequest = serde_json::from_str(r#"{"events":[
{"timestamp":"2026-11-25T18:02:02.2220000+00:00","level":"Information","category":"Tests","message":"First","exception":null,"stack_trace":null},
{"timestamp":"2026-11-25T18:02:03.2930000+00:00","level":"Error","category":"Tests","message":"Second","exception":"Boom","stack_trace":"at Third()"}
]}"#).unwrap();
let logger = CapturingLogger::default();
log_dotnet_events(&logger, &request.events);
let first = parse_dotnet_timestamp("2026-11-25T18:02:02.2220000+00:00");
let second = parse_dotnet_timestamp("2026-11-25T18:02:03.2930000+00:00");
assert_eq!(logger.0.into_inner().unwrap(), vec![
(String::from("First"), first),
(String::from("Second"), second),
(String::from(" Exception: Boom"), second),
(String::from(" at Third()"), second),
]);
}
#[test]
fn flatpak_standard_path_matches_tauri_local_data_path() {
let base_directory = PathBuf::from("/var/data");
+28 -1
View File
@@ -1,6 +1,7 @@
use log::info;
use once_cell::sync::Lazy;
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::middleware;
use axum::routing::{delete, get, post};
use axum::Router;
@@ -19,6 +20,10 @@ static RUSTLS_CRYPTO_PROVIDER_INIT: Once = Once::new();
/// what a tool returns to a model well below this. The limit is headroom, not a working constraint.
const PROMPT_INJECTION_BODY_LIMIT_BYTES: usize = 16 * 1024 * 1024;
/// The request body limit for a batch of log events from the .NET server. A batch rarely takes more
/// than a few hundred kilobytes; the limit leaves room for a batch full of stack traces.
const LOG_EVENTS_BODY_LIMIT_BYTES: usize = 16 * 1024 * 1024;
/// The port used for the runtime API server. In the development environment, we use a fixed
/// port, in the production environment we use the next available port. This differentiation
/// is necessary because we cannot communicate the port to the .NET server in the development
@@ -34,6 +39,7 @@ pub static API_SERVER_PORT: Lazy<u16> = Lazy::new(|| {
/// Creates the router with every route of the runtime API, each of which requires the API token.
fn create_router() -> Router {
let router = Router::new()
.route("/system/alive", get(is_alive))
.route("/system/dotnet/port", get(crate::dotnet::dotnet_port))
.route("/system/dotnet/ready", get(crate::dotnet::dotnet_ready))
.route("/system/qdrant-edge/info", get(crate::qdrant_edge_database::qdrant_edge_info))
@@ -91,7 +97,13 @@ fn create_router() -> Router {
.route("/image/prepare", post(crate::image::prepare_image))
.route("/image/prepare-for-model", post(crate::image::prepare_image_for_model))
.route("/log/paths", get(crate::log::get_log_paths))
.route("/log/event", post(crate::log::log_event))
//
// A batch holds up to a few hundred log events of the .NET server, some with a stack trace,
// which can exceed Axum's 2 MB default. The runtime would refuse such a batch with 413, and
// its events would be lost.
//
.route("/log/events", post(crate::log::log_events)
.layer(DefaultBodyLimit::max(LOG_EVENTS_BODY_LIMIT_BYTES)))
.route("/tokenizer/count", post(crate::tokenizer::token_count))
.route("/tokenizer/validate", post(crate::tokenizer::validate_tokenizer))
.route("/tokenizer/store", post(crate::tokenizer::store_tokenizer))
@@ -116,6 +128,15 @@ fn require_api_token(router: Router) -> Router {
router.route_layer(middleware::from_extractor::<APIToken>())
}
/// Tells the .NET server that the runtime is alive.
///
/// The .NET server asks this route over a connection of its own whenever a call to the runtime
/// failed. The handler does no work at all, so an answer proves exactly what the server wants to
/// know: the runtime accepts a new connection and runs a handler. Nothing else can make it fail.
async fn is_alive() -> StatusCode {
StatusCode::NO_CONTENT
}
/// Starts the runtime API server. The server is used to communicate with the .NET server and
/// to provide additional functionality to the Tauri app.
pub fn start_runtime_api() {
@@ -294,6 +315,12 @@ mod tests {
assert!(unprotected_routes.is_empty(), "These routes answer without the API token: {unprotected_routes:#?}");
}
#[tokio::test]
async fn the_alive_route_answers_only_with_the_token() {
assert_eq!(send(create_router(), request("GET", "/system/alive", None, "")).await, StatusCode::UNAUTHORIZED);
assert_eq!(send(create_router(), request("GET", "/system/alive", Some(API_TOKEN.to_hex_text()), "")).await, StatusCode::NO_CONTENT);
}
#[tokio::test]
async fn a_valid_token_gets_through_to_the_handler() {
// The handler fails on the incomplete body, before it touches any file.