Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/okena-core/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,10 @@ pub enum ActionRequest {
project_id: String,
relative_path: String,
},
ReadFileBytes {
project_id: String,
relative_path: String,
},
FileSize {
project_id: String,
relative_path: String,
Expand Down
101 changes: 84 additions & 17 deletions crates/okena-core/src/remote_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,66 @@

use crate::api::ActionRequest;

/// A shared blocking HTTP client (connection pooling across all calls).
fn shared_client() -> &'static reqwest::blocking::Client {
/// Total request timeout for "fast" actions (terminal control, listings,
/// metadata). 10 s is generous for these; longer would mask real failures.
const FAST_TIMEOUT_SECS: u64 = 10;

/// Total request timeout for byte-payload reads (ReadFileBytes). A 20 MB
/// image base64-encodes to ~27 MB; over a 5 Mbit/s link that's ~45 s on the
/// wire alone, which would time out the fast client with no useful signal.
const BYTES_TIMEOUT_SECS: u64 = 90;

/// Hard ceiling on response body size accepted by the remote bridge. Cuts
/// off arbitrarily large or runaway responses before they're buffered into
/// memory (peak resident is ~4× the file size while the base64 + JSON +
/// decoded Vec all co-exist). Mirrors the server-side cap in
/// `src/workspace/actions/execute/files.rs`.
const MAX_RESPONSE_BYTES: u64 = 32 * 1024 * 1024;

/// Build a reqwest blocking client. Returns Err on TLS backend init
/// failure (corrupt cert store, sandboxed Keychain denial, FIPS mode
/// rejecting default ciphers, container without ca-certificates). Caller
/// is expected to surface the error to the user — a panic here would
/// abort the whole app at first remote probe and OnceLock-poison every
/// retry.
fn build_client(timeout_secs: u64) -> Result<reqwest::blocking::Client, String> {
reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(timeout_secs))
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.map_err(|e| format!("Cannot initialise HTTP client: {}", e))
}

/// Cached fast-action client. We store the build result so a TLS init
/// failure surfaces as a recoverable error rather than poisoning the
/// OnceLock and panicking every retry.
fn shared_client() -> Result<&'static reqwest::blocking::Client, String> {
use std::sync::OnceLock;
static CLIENT: OnceLock<Result<reqwest::blocking::Client, String>> = OnceLock::new();
match CLIENT.get_or_init(|| build_client(FAST_TIMEOUT_SECS)) {
Ok(c) => Ok(c),
Err(e) => Err(e.clone()),
}
}

/// Cached bytes-action client with a longer timeout, for ReadFileBytes.
fn bytes_client() -> Result<&'static reqwest::blocking::Client, String> {
use std::sync::OnceLock;
static CLIENT: OnceLock<reqwest::blocking::Client> = OnceLock::new();
CLIENT.get_or_init(|| {
#[allow(
clippy::expect_used,
reason = "reqwest client build only fails on TLS backend init — nothing recoverable at this call site"
)]
reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.expect("Failed to build HTTP client")
})
static CLIENT: OnceLock<Result<reqwest::blocking::Client, String>> = OnceLock::new();
match CLIENT.get_or_init(|| build_client(BYTES_TIMEOUT_SECS)) {
Ok(c) => Ok(c),
Err(e) => Err(e.clone()),
}
}

/// Pick the right client for the action. Bytes-bearing actions get the
/// larger timeout so a slow remote doesn't surface as a generic transport
/// error mid-download.
fn client_for(action: &ActionRequest) -> Result<&'static reqwest::blocking::Client, String> {
match action {
ActionRequest::ReadFileBytes { .. } => bytes_client(),
_ => shared_client(),
}
}

/// Post an action request to a remote server and return the JSON response body.
Expand All @@ -27,7 +72,7 @@ pub fn post_action(
action: ActionRequest,
) -> Result<Option<serde_json::Value>, String> {
let url = format!("http://{}:{}/v1/actions", host, port);
let client = shared_client();
let client = client_for(&action)?;
let resp = client
.post(&url)
.bearer_auth(token)
Expand All @@ -41,8 +86,30 @@ pub fn post_action(
return Err(format!("Server returned {}: {}", status, body));
}

let body: serde_json::Value =
resp.json().map_err(|e| format!("Failed to parse response: {}", e))?;
// Cap how much body we buffer. A hostile / older / desync'd server can't
// make us swallow a multi-GB JSON+base64 stream into memory. Content-Length
// is only a hint; we still bound the actual read.
if let Some(len) = resp.content_length()
&& len > MAX_RESPONSE_BYTES {
return Err(format!(
"Response too large ({:.1} MB). Max {} MB.",
len as f64 / 1024.0 / 1024.0,
MAX_RESPONSE_BYTES / 1024 / 1024
));
}
use std::io::Read as _;
let mut body_bytes = Vec::new();
resp.take(MAX_RESPONSE_BYTES + 1)
.read_to_end(&mut body_bytes)
.map_err(|e| format!("Failed to read response: {}", e))?;
if body_bytes.len() as u64 > MAX_RESPONSE_BYTES {
return Err(format!(
"Response too large (>{} MB).",
MAX_RESPONSE_BYTES / 1024 / 1024
));
}
let body: serde_json::Value = serde_json::from_slice(&body_bytes)
.map_err(|e| format!("Failed to parse response: {}", e))?;

if let Some(error) = body.get("error").and_then(|e| e.as_str()) {
return Err(error.to_string());
Expand Down
5 changes: 5 additions & 0 deletions crates/okena-files/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ nucleo-matcher = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
log = "0.4"
base64 = "0.22"
usvg = { version = "0.45", default-features = false }
ttf-parser = "0.25"
woff2 = { package = "woff2-patched", version = "0.4" }
image = { version = "0.25", default-features = false }

[dev-dependencies]
tempfile = "3"
Loading
Loading