fix: reduce TUI idle CPU and improve server error banners

- Replace non-blocking try_recv() event loop with blocking recv() to
  eliminate idle spin; the sender tick timeout still drives minimum
  wakeup rate so the UI stays responsive
- Lower default tick rate from 50 ms to 100 ms (10 ticks/sec vs 20);
  add MANAGARR_TICK_RATE_MS env var for runtime tuning
- Move terminal draws to event boundaries (key + tick) instead of every
  loop pass, reducing unnecessary redraws
- In network error handling, prefer concise JSON fields (message /
  errorMessage / error) over the raw HTTP body, so Radarr ASP.NET
  stack traces don't flood the TUI banner; full body still logged
- Add unit tests for tick-rate parsing and Radarr-style JSON error body

Observed: ~0.6% total CPU at idle vs measurably higher with prod defaults
This commit is contained in:
Jonathan McCumber
2026-06-28 12:35:37 -05:00
parent 6e7707f6df
commit 6c41e0704e
4 changed files with 114 additions and 10 deletions
+19 -4
View File
@@ -9,6 +9,7 @@ use regex::Regex;
use reqwest::{Client, RequestBuilder};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use sonarr_network::SonarrEvent;
use strum_macros::Display;
use tokio::select;
@@ -142,11 +143,8 @@ impl<'a, 'b> Network<'a, 'b> {
}
} else {
let status = response.status();
let whitespace_regex = Regex::new(r"\s+")?;
let response_body = response.text().await.unwrap_or_default();
let error_body = whitespace_regex
.replace_all(&response_body.replace('\n', " "), " ")
.to_string();
let error_body = format_error_body(&response_body)?;
error!("Request failed. Received {status} response code with body: {response_body}");
self.app.lock().await.handle_error(anyhow!("Request failed. Received {status} response code with body: {error_body}"));
@@ -279,6 +277,23 @@ impl<'a, 'b> Network<'a, 'b> {
}
}
fn format_error_body(response_body: &str) -> Result<String> {
let whitespace_regex = Regex::new(r"\s+")?;
let body = serde_json::from_str::<Value>(response_body)
.ok()
.and_then(|value| {
value
.get("message")
.or_else(|| value.get("errorMessage"))
.or_else(|| value.get("error"))
.and_then(Value::as_str)
.map(ToOwned::to_owned)
})
.unwrap_or_else(|| response_body.replace('\n', " "));
Ok(whitespace_regex.replace_all(&body, " ").to_string())
}
#[derive(Clone, Copy, Debug, Display, PartialEq, Eq)]
pub enum RequestMethod {
Get,
+42
View File
@@ -353,6 +353,48 @@ mod tests {
);
}
#[tokio::test]
async fn test_handle_request_non_success_code_uses_json_message_for_error_body() {
let mut server = Server::new_async().await;
let async_server = server
.mock("GET", "/test")
.match_header("X-Api-Key", "test1234")
.with_status(500)
.with_body(json!({
"message": "database is locked\ndatabase is locked",
"description": "at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker"
}).to_string())
.create_async()
.await;
let app_arc = Arc::new(Mutex::new(App::test_default()));
let mut network = test_network(&app_arc);
let resp = network
.handle_request::<(), Test>(
RequestProps {
uri: format!("{}/test", server.url()),
method: RequestMethod::Get,
body: None,
api_token: "test1234".to_owned(),
ignore_status_code: false,
custom_headers: HeaderMap::new(),
},
|response, mut app| app.error = HorizontallyScrollableText::from(response.value),
)
.await;
async_server.assert_async().await;
assert_str_eq!(
app_arc.lock().await.error.text,
"Request failed. Received 500 Internal Server Error response code with body: database is locked database is locked"
);
assert!(resp.is_err());
assert_str_eq!(
resp.unwrap_err().to_string(),
"Request failed. Received 500 Internal Server Error response code with body: database is locked database is locked"
);
}
#[rstest]
#[tokio::test]
async fn test_call_api(