| 1 | #[cfg(test)] |
| 2 | use crate::stdio::{emit_stdio_event, interrupt_turn_request}; |
| 3 | #[cfg(test)] |
| 4 | use crate::turns::{RuntimeTurnInput, extract_runtime_thread_id, turn_terminal_status}; |
| 5 | use crate::{AppState, DispatchError, RuntimeBridge, SharedRuntimeBridge, thread_control}; |
| 6 | #[cfg(test)] |
| 7 | use crate::{ |
| 8 | InFlightTurn, MAX_SSE_FRAME_BYTES, RuntimeThreadHint, TurnExecutionOwner, TurnRegistry, |
| 9 | TurnTerminalStatus, TurnTranscript, |
| 10 | }; |
| 11 | use anyhow::Context as _; |
| 12 | use anyhow::{Result, anyhow, bail}; |
| 13 | #[cfg(test)] |
| 14 | use codewhale_protocol::{EventFrame, ResponseChannel}; |
| 15 | use serde_json::{Value, json}; |
| 16 | #[cfg(test)] |
| 17 | use std::collections::HashMap; |
| 18 | #[cfg(test)] |
| 19 | use std::path::Path; |
| 20 | #[cfg(test)] |
| 21 | use std::path::PathBuf; |
| 22 | #[cfg(test)] |
| 23 | use std::process::{Command, Stdio}; |
| 24 | #[cfg(all(test, unix))] |
| 25 | use std::sync::Arc; |
| 26 | use std::time::Duration; |
| 27 | #[cfg(test)] |
| 28 | use tokio::io::AsyncWrite; |
| 29 | #[cfg(all(test, unix))] |
| 30 | use tokio::sync::Mutex; |
| 31 | |
| 32 | /// Historical cold-child cache comparator. It has no production producer. |
| 33 | #[cfg(all(test, unix))] |
| 34 | pub(crate) async fn acquire_historical_runtime_bridge<F, Fut>( |
| 35 | state: &AppState, |
| 36 | start: F, |
| 37 | ) -> std::result::Result<SharedRuntimeBridge, DispatchError> |
| 38 | where |
| 39 | F: FnOnce() -> Fut, |
| 40 | Fut: std::future::Future<Output = Result<RuntimeBridge>>, |
| 41 | { |
| 42 | if let Some(bridge) = state.runtime_bridge.lock().await.as_ref() { |
| 43 | return Ok(bridge.clone()); |
| 44 | } |
| 45 | if state.captured_owner.is_some() { |
| 46 | return Err(DispatchError::runtime_unavailable( |
| 47 | "the captured Runtime owner is unavailable; refusing another owner", |
| 48 | )); |
| 49 | } |
| 50 | let bridge = |
| 51 | Arc::new(Mutex::new(start().await.map_err(|err| { |
| 52 | DispatchError::runtime_unavailable(err.to_string()) |
| 53 | })?)); |
| 54 | let mut slot = state.runtime_bridge.lock().await; |
| 55 | // Prefer a bridge cached by a concurrent caller while we were spawning; |
| 56 | // dropping our unused one kills the extra child via `Drop`. |
| 57 | Ok(slot.get_or_insert_with(|| bridge.clone()).clone()) |
| 58 | } |
| 59 | |
| 60 | /// Use the exact bridge installed by the held canonical owner. No process, |
| 61 | /// store or transcript can be created when this captured connection is absent. |
| 62 | pub(crate) async fn acquire_runtime_bridge( |
| 63 | state: &AppState, |
| 64 | ) -> std::result::Result<SharedRuntimeBridge, DispatchError> { |
| 65 | state |
| 66 | .runtime_bridge |
| 67 | .lock() |
| 68 | .await |
| 69 | .as_ref() |
| 70 | .cloned() |
| 71 | .ok_or_else(|| { |
| 72 | DispatchError::runtime_unavailable( |
| 73 | "the captured Runtime owner is unavailable; refusing another owner", |
| 74 | ) |
| 75 | }) |
| 76 | } |
| 77 | |
| 78 | #[cfg(test)] |
| 79 | pub(crate) async fn acquire_live_runtime_bridge( |
| 80 | state: &AppState, |
| 81 | ) -> std::result::Result<tokio::sync::OwnedMutexGuard<RuntimeBridge>, DispatchError> { |
| 82 | Ok(acquire_runtime_bridge(state).await?.lock_owned().await) |
| 83 | } |
| 84 | |
| 85 | /// Historical respawn comparison; all actual frontends use the held owner. |
| 86 | #[cfg(all(test, unix))] |
| 87 | pub(crate) async fn acquire_live_runtime_bridge_with<F, Fut>( |
| 88 | state: &AppState, |
| 89 | start: F, |
| 90 | ) -> std::result::Result<tokio::sync::OwnedMutexGuard<RuntimeBridge>, DispatchError> |
| 91 | where |
| 92 | F: Fn() -> Fut, |
| 93 | Fut: std::future::Future<Output = Result<RuntimeBridge>>, |
| 94 | { |
| 95 | for _ in 0..2 { |
| 96 | let shared = acquire_historical_runtime_bridge(state, &start).await?; |
| 97 | let mut bridge = shared.clone().lock_owned().await; |
| 98 | if !bridge.child_exited() { |
| 99 | return Ok(bridge); |
| 100 | } |
| 101 | drop(bridge); |
| 102 | let mut slot = state.runtime_bridge.lock().await; |
| 103 | // Evict only the dead bridge: a concurrent caller may already have |
| 104 | // replaced it with a live one. |
| 105 | if slot |
| 106 | .as_ref() |
| 107 | .is_some_and(|cached| Arc::ptr_eq(cached, &shared)) |
| 108 | { |
| 109 | *slot = None; |
| 110 | } |
| 111 | } |
| 112 | Err(DispatchError::runtime_unavailable( |
| 113 | "runtime API bridge exited immediately after starting", |
| 114 | )) |
| 115 | } |
| 116 | |
| 117 | /// Historical config/cache comparator. Captured owners retain their bridge. |
| 118 | #[cfg(test)] |
| 119 | pub(crate) async fn invalidate_runtime_bridge(state: &AppState) { |
| 120 | if state.captured_owner.is_some() { |
| 121 | return; |
| 122 | } |
| 123 | let mut bridge = state.runtime_bridge.lock().await; |
| 124 | *bridge = None; |
| 125 | } |
| 126 | |
| 127 | impl RuntimeBridge { |
| 128 | /// The child binds an ephemeral loopback port itself (`--port 0`) and |
| 129 | /// reports it on stdout; the parent never reserves a port for it to race. |
| 130 | #[cfg(test)] |
| 131 | pub(crate) fn runtime_command(config_path: Option<&Path>, auth_token: &str) -> Result<Command> { |
| 132 | let current_exe = std::env::current_exe().ok(); |
| 133 | let mut command = if let Some(path) = current_exe { |
| 134 | Command::new(path) |
| 135 | } else { |
| 136 | Command::new("codewhale") |
| 137 | }; |
| 138 | // Pass the runtime auth token out-of-band via env (not argv) so local |
| 139 | // `ps` cannot read credential material from the child command line. |
| 140 | // The TUI/runtime server already accepts CODEWHALE_RUNTIME_TOKEN / |
| 141 | // DEEPSEEK_RUNTIME_TOKEN when --auth-token is absent. |
| 142 | command |
| 143 | .arg("app-server") |
| 144 | .arg("--http") |
| 145 | .arg("--host") |
| 146 | .arg("127.0.0.1") |
| 147 | .arg("--port") |
| 148 | .arg("0") |
| 149 | .env("CODEWHALE_RUNTIME_TOKEN", auth_token) |
| 150 | .env("DEEPSEEK_RUNTIME_TOKEN", auth_token) |
| 151 | .stdin(Stdio::null()) |
| 152 | .stdout(Stdio::piped()) |
| 153 | .stderr(Stdio::null()); |
| 154 | if let Some(config_path) = config_path { |
| 155 | command.arg("--config").arg(config_path); |
| 156 | } |
| 157 | Ok(command) |
| 158 | } |
| 159 | |
| 160 | pub(crate) fn authed(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder { |
| 161 | match self.auth_token.as_deref() { |
| 162 | Some(token) => builder.bearer_auth(token), |
| 163 | None => builder, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | pub(crate) async fn request_json(&self, builder: reqwest::RequestBuilder) -> Result<Value> { |
| 168 | thread_control::read_json_response(builder.send().await?).await |
| 169 | } |
| 170 | |
| 171 | /// Resolve `stdio_thread_id` to a runtime thread, minting one only when |
| 172 | /// `thread_map` has no entry. The map lives on [`AppState`] and outlives |
| 173 | /// this bridge, so a thread created under a previous child keeps its id |
| 174 | /// here as long as the store it was persisted to is shared (#6246). |
| 175 | #[cfg(test)] |
| 176 | pub(crate) async fn ensure_runtime_thread( |
| 177 | &mut self, |
| 178 | thread_map: &mut HashMap<String, String>, |
| 179 | stdio_thread_id: &str, |
| 180 | hint: Option<RuntimeThreadHint>, |
| 181 | ) -> Result<String> { |
| 182 | if let Some(runtime_thread_id) = thread_map.get(stdio_thread_id) { |
| 183 | return Ok(runtime_thread_id.clone()); |
| 184 | } |
| 185 | let hint = hint.unwrap_or_default(); |
| 186 | let runtime_thread_id = self |
| 187 | .create_runtime_thread(hint.model, hint.workspace) |
| 188 | .await?; |
| 189 | thread_map.insert(stdio_thread_id.to_string(), runtime_thread_id.clone()); |
| 190 | Ok(runtime_thread_id) |
| 191 | } |
| 192 | |
| 193 | #[cfg(test)] |
| 194 | async fn create_runtime_thread( |
| 195 | &mut self, |
| 196 | model: Option<String>, |
| 197 | workspace: Option<PathBuf>, |
| 198 | ) -> Result<String> { |
| 199 | let record = self |
| 200 | .request_json( |
| 201 | self.authed(self.client.post(format!("{}/v1/threads", self.base_url))) |
| 202 | .json(&json!({ |
| 203 | "model": model, |
| 204 | "workspace": workspace, |
| 205 | "mode": "agent", |
| 206 | "archived": false, |
| 207 | })), |
| 208 | ) |
| 209 | .await?; |
| 210 | let thread_id = extract_runtime_thread_id(&record)?.to_string(); |
| 211 | self.last_seq_by_thread |
| 212 | .entry(thread_id.clone()) |
| 213 | .or_insert(0); |
| 214 | Ok(thread_id) |
| 215 | } |
| 216 | |
| 217 | /// Run one turn to completion, streaming its events to `writer`. |
| 218 | /// |
| 219 | /// `registration` is `Some` on the stdio path: it publishes the live turn |
| 220 | /// so an `thread/interrupt` arriving mid-stream can reach the runtime |
| 221 | /// without waiting on the bridge mutex this call holds. |
| 222 | #[cfg(test)] |
| 223 | pub(crate) async fn message_thread<W: AsyncWrite + Unpin>( |
| 224 | &mut self, |
| 225 | thread_id: &str, |
| 226 | input: RuntimeTurnInput<'_>, |
| 227 | writer: &mut W, |
| 228 | registration: Option<(TurnRegistry, String)>, |
| 229 | mut transcript: Option<&mut TurnTranscript>, |
| 230 | ) -> Result<Value> { |
| 231 | let RuntimeTurnInput { |
| 232 | input, |
| 233 | images, |
| 234 | max_output_tokens, |
| 235 | expected_workspace, |
| 236 | cancellation: _, |
| 237 | } = input; |
| 238 | let mut request = json!({ "prompt": input, "allowed_tools": [] }); |
| 239 | if let Some(workspace) = expected_workspace { |
| 240 | request["expected_workspace"] = json!(workspace); |
| 241 | } |
| 242 | if !images.is_empty() { |
| 243 | let info = self |
| 244 | .request_json( |
| 245 | self.authed( |
| 246 | self.client |
| 247 | .get(format!("{}/v1/runtime/info", self.base_url)), |
| 248 | ), |
| 249 | ) |
| 250 | .await?; |
| 251 | if info |
| 252 | .pointer("/capabilities/turn_image_inputs") |
| 253 | .and_then(Value::as_bool) |
| 254 | != Some(true) |
| 255 | { |
| 256 | bail!( |
| 257 | "Runtime image input is unavailable; update the Runtime before sending attachments" |
| 258 | ); |
| 259 | } |
| 260 | request["images"] = json!(images); |
| 261 | } |
| 262 | if let Some(limit) = max_output_tokens { |
| 263 | request["maxOutputTokens"] = json!(limit); |
| 264 | } |
| 265 | let turn = self |
| 266 | .request_json( |
| 267 | self.authed( |
| 268 | self.client |
| 269 | .post(format!("{}/v1/threads/{thread_id}/turns", self.base_url)), |
| 270 | ) |
| 271 | .json(&request), |
| 272 | ) |
| 273 | .await?; |
| 274 | let turn_id = turn |
| 275 | .pointer("/turn/id") |
| 276 | .and_then(Value::as_str) |
| 277 | .ok_or_else(|| anyhow!("runtime API turn response missing turn.id"))? |
| 278 | .to_string(); |
| 279 | let response_id = format!("{thread_id}:{turn_id}"); |
| 280 | |
| 281 | if let Some(transcript) = transcript.as_deref_mut() { |
| 282 | transcript.model = turn |
| 283 | .pointer("/thread/model") |
| 284 | .and_then(Value::as_str) |
| 285 | .map(str::to_string); |
| 286 | transcript.events.push(EventFrame::ResponseStart { |
| 287 | response_id: response_id.clone(), |
| 288 | }); |
| 289 | } |
| 290 | |
| 291 | if let Err(error) = emit_stdio_event( |
| 292 | writer, |
| 293 | json!({ |
| 294 | "type": "response_start", |
| 295 | "response_id": response_id, |
| 296 | }), |
| 297 | ) |
| 298 | .await |
| 299 | { |
| 300 | let orphan = InFlightTurn { |
| 301 | owner: TurnExecutionOwner::HistoricalHttp { |
| 302 | base_url: self.base_url.clone(), |
| 303 | auth_token: self.auth_token.clone(), |
| 304 | }, |
| 305 | runtime_thread_id: thread_id.to_string(), |
| 306 | turn_id: turn_id.clone(), |
| 307 | connection: None, |
| 308 | }; |
| 309 | if let Err(interrupt) = interrupt_turn_request(&orphan).await { |
| 310 | tracing::warn!( |
| 311 | thread_id, |
| 312 | turn_id = %turn_id, |
| 313 | "failed to interrupt a turn whose response_start could not be written: {}", |
| 314 | interrupt.wire.message |
| 315 | ); |
| 316 | } |
| 317 | return Err(error); |
| 318 | } |
| 319 | |
| 320 | // Publish the turn only for the streaming window, and take it back |
| 321 | // before any `?` below: a turn that has already finished must never |
| 322 | // look cancellable. |
| 323 | if let Some((registry, key)) = registration.as_ref() { |
| 324 | registry.lock().await.insert( |
| 325 | key.clone(), |
| 326 | InFlightTurn { |
| 327 | owner: TurnExecutionOwner::HistoricalHttp { |
| 328 | base_url: self.base_url.clone(), |
| 329 | auth_token: self.auth_token.clone(), |
| 330 | }, |
| 331 | runtime_thread_id: thread_id.to_string(), |
| 332 | turn_id: turn_id.clone(), |
| 333 | connection: None, |
| 334 | }, |
| 335 | ); |
| 336 | } |
| 337 | |
| 338 | let since_seq = self.last_seq_by_thread.get(thread_id).copied().unwrap_or(0); |
| 339 | let stream_result = self |
| 340 | .stream_turn_events( |
| 341 | thread_id, |
| 342 | &turn_id, |
| 343 | &response_id, |
| 344 | writer, |
| 345 | since_seq, |
| 346 | transcript.as_deref_mut(), |
| 347 | ) |
| 348 | .await; |
| 349 | |
| 350 | if let Some((registry, key)) = registration.as_ref() { |
| 351 | registry.lock().await.remove(key); |
| 352 | } |
| 353 | |
| 354 | if stream_result.is_ok() { |
| 355 | emit_stdio_event( |
| 356 | writer, |
| 357 | json!({ |
| 358 | "type": "response_end", |
| 359 | "response_id": response_id, |
| 360 | }), |
| 361 | ) |
| 362 | .await?; |
| 363 | if let Some(transcript) = transcript { |
| 364 | transcript.events.push(EventFrame::ResponseEnd { |
| 365 | response_id: response_id.clone(), |
| 366 | }); |
| 367 | } |
| 368 | } else { |
| 369 | // The stream broke before `turn.completed` (transport error, |
| 370 | // oversized or invalid frame, a writer that went away). Ending |
| 371 | // the response here reported success ahead of the error, and the |
| 372 | // runtime turn kept running with nothing left able to interrupt |
| 373 | // it (the registry entry is gone), so the thread refused its next |
| 374 | // message until the orphan finished. Stop it, best effort, and |
| 375 | // let the error below be the only outcome the client sees. |
| 376 | let orphan = InFlightTurn { |
| 377 | owner: TurnExecutionOwner::HistoricalHttp { |
| 378 | base_url: self.base_url.clone(), |
| 379 | auth_token: self.auth_token.clone(), |
| 380 | }, |
| 381 | runtime_thread_id: thread_id.to_string(), |
| 382 | turn_id: turn_id.clone(), |
| 383 | connection: None, |
| 384 | }; |
| 385 | if let Err(error) = interrupt_turn_request(&orphan).await { |
| 386 | tracing::warn!( |
| 387 | thread_id, |
| 388 | turn_id = %turn_id, |
| 389 | "failed to interrupt a turn whose event stream broke: {}", |
| 390 | error.wire.message |
| 391 | ); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | let (last_seq, status, error) = stream_result?; |
| 396 | self.last_seq_by_thread |
| 397 | .insert(thread_id.to_string(), last_seq); |
| 398 | |
| 399 | match status { |
| 400 | TurnTerminalStatus::Completed => Ok(json!({ |
| 401 | "thread_id": thread_id, |
| 402 | "status": "accepted", |
| 403 | "thread": Value::Null, |
| 404 | "threads": [], |
| 405 | "model": Value::Null, |
| 406 | "model_provider": Value::Null, |
| 407 | "cwd": Value::Null, |
| 408 | "approval_policy": Value::Null, |
| 409 | "sandbox": Value::Null, |
| 410 | "events": [], |
| 411 | "data": { "turn_id": turn_id }, |
| 412 | })), |
| 413 | TurnTerminalStatus::Failed => Err(anyhow!( |
| 414 | "{}", |
| 415 | error.unwrap_or_else(|| "turn failed".to_string()) |
| 416 | )), |
| 417 | TurnTerminalStatus::Interrupted => Err(anyhow!( |
| 418 | "{}", |
| 419 | error.unwrap_or_else(|| "turn interrupted".to_string()) |
| 420 | )), |
| 421 | TurnTerminalStatus::Canceled => Err(anyhow!( |
| 422 | "{}", |
| 423 | error.unwrap_or_else(|| "turn canceled".to_string()) |
| 424 | )), |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | #[cfg(test)] |
| 429 | async fn stream_turn_events<W: AsyncWrite + Unpin>( |
| 430 | &self, |
| 431 | thread_id: &str, |
| 432 | turn_id: &str, |
| 433 | response_id: &str, |
| 434 | writer: &mut W, |
| 435 | since_seq: u64, |
| 436 | mut transcript: Option<&mut TurnTranscript>, |
| 437 | ) -> Result<(u64, TurnTerminalStatus, Option<String>)> { |
| 438 | let mut response = self |
| 439 | .authed(self.client.get(format!( |
| 440 | "{}/v1/threads/{thread_id}/events?since_seq={since_seq}", |
| 441 | self.base_url |
| 442 | ))) |
| 443 | .send() |
| 444 | .await? |
| 445 | .error_for_status()?; |
| 446 | |
| 447 | let mut buffer = Vec::new(); |
| 448 | let mut last_seq = since_seq; |
| 449 | |
| 450 | while let Some(chunk) = response.chunk().await? { |
| 451 | buffer.extend_from_slice(&chunk); |
| 452 | if buffer.len() > MAX_SSE_FRAME_BYTES { |
| 453 | bail!( |
| 454 | "runtime SSE frame exceeded {MAX_SSE_FRAME_BYTES} bytes without a frame delimiter" |
| 455 | ); |
| 456 | } |
| 457 | while let Some(frame_bytes) = take_sse_frame(&mut buffer) { |
| 458 | let Some((event_name, frame_data)) = parse_sse_frame(&frame_bytes) else { |
| 459 | continue; |
| 460 | }; |
| 461 | let envelope: Value = serde_json::from_str(&frame_data) |
| 462 | .with_context(|| format!("invalid SSE json for {event_name}: {frame_data}"))?; |
| 463 | if let Some(seq) = envelope.get("seq").and_then(Value::as_u64) { |
| 464 | last_seq = last_seq.max(seq); |
| 465 | } |
| 466 | if envelope.get("turn_id").and_then(Value::as_str) != Some(turn_id) { |
| 467 | continue; |
| 468 | } |
| 469 | let payload = envelope.get("payload").cloned().unwrap_or(Value::Null); |
| 470 | match event_name.as_str() { |
| 471 | "approval.required" | "user_input.required" => { |
| 472 | bail!( |
| 473 | "interactive_execution_unsupported: Runtime requested interaction during a tool-free compatibility turn; use codewhale app-server --http and /v1/*" |
| 474 | ); |
| 475 | } |
| 476 | "item.delta" => { |
| 477 | let kind = payload |
| 478 | .get("kind") |
| 479 | .and_then(Value::as_str) |
| 480 | .unwrap_or_default(); |
| 481 | if kind == "agent_message" |
| 482 | && let Some(delta) = payload.get("delta").and_then(Value::as_str) |
| 483 | && !delta.is_empty() |
| 484 | { |
| 485 | emit_stdio_event( |
| 486 | writer, |
| 487 | json!({ |
| 488 | "type": "response_delta", |
| 489 | "response_id": response_id, |
| 490 | "delta": delta, |
| 491 | }), |
| 492 | ) |
| 493 | .await?; |
| 494 | if let Some(transcript) = transcript.as_deref_mut() { |
| 495 | transcript.text.push_str(delta); |
| 496 | transcript.events.push(EventFrame::ResponseDelta { |
| 497 | response_id: response_id.to_string(), |
| 498 | delta: delta.to_string(), |
| 499 | channel: ResponseChannel::Text, |
| 500 | }); |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | "turn.completed" => { |
| 505 | let status = turn_terminal_status(&payload)?; |
| 506 | let error = payload |
| 507 | .pointer("/turn/error") |
| 508 | .and_then(Value::as_str) |
| 509 | .map(str::to_string); |
| 510 | return Ok((last_seq, status, error)); |
| 511 | } |
| 512 | _ => {} |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | bail!("runtime event stream ended before turn.completed") |
| 518 | } |
| 519 | |
| 520 | #[cfg(test)] |
| 521 | pub(crate) fn from_base_url_for_test(base_url: String) -> Self { |
| 522 | install_rustls_crypto_provider(); |
| 523 | Self { |
| 524 | base_url, |
| 525 | client: codewhale_release::platform_http_client_builder() |
| 526 | .timeout(Duration::from_secs(5)) |
| 527 | .build() |
| 528 | .expect("build reqwest test client"), |
| 529 | auth_token: None, |
| 530 | child: None, |
| 531 | last_seq_by_thread: HashMap::new(), |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | #[cfg(test)] |
| 537 | impl RuntimeBridge { |
| 538 | /// Whether the historical fixture child has exited. A bridge without a child (tests, |
| 539 | /// or an externally managed runtime) never reports exited. A `try_wait` |
| 540 | /// error counts as exited: with `WNOHANG` it only fails when the pid is no |
| 541 | /// longer this process's child (already reaped elsewhere), and such a |
| 542 | /// child can neither be tracked nor killed on drop. |
| 543 | #[cfg(unix)] |
| 544 | fn child_exited(&mut self) -> bool { |
| 545 | self.child |
| 546 | .as_mut() |
| 547 | .is_some_and(|child| !matches!(child.try_wait(), Ok(None))) |
| 548 | } |
| 549 | |
| 550 | /// Kills the managed runtime child and reaps it on a detached thread so |
| 551 | /// neither an explicit shutdown nor Drop blocks a Tokio runtime thread. |
| 552 | fn shutdown_child(&mut self) { |
| 553 | if let Some(mut child) = self.child.take() { |
| 554 | let _ = child.kill(); |
| 555 | std::thread::spawn(move || { |
| 556 | let _ = child.wait(); |
| 557 | }); |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | #[cfg(test)] |
| 563 | impl Drop for RuntimeBridge { |
| 564 | fn drop(&mut self) { |
| 565 | self.shutdown_child(); |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// The line the Runtime prints once it holds its listener (the Runtime's |
| 570 | /// `RUNTIME_LISTENING_PREFIX`; this crate does not depend on that one). |
| 571 | #[cfg(test)] |
| 572 | pub(crate) const RUNTIME_LISTENING_PREFIX: &str = "Runtime API listening on http://"; |
| 573 | |
| 574 | /// The endpoint line is short and comes first; anything larger is not it. |
| 575 | #[cfg(test)] |
| 576 | pub(crate) const RUNTIME_READY_MAX_BYTES: usize = 1024; |
| 577 | |
| 578 | /// The endpoint a Runtime child reports for itself: exactly a nonzero port on |
| 579 | /// `127.0.0.1`, the host the parent asked it to bind. |
| 580 | #[cfg(test)] |
| 581 | pub(crate) fn parse_runtime_endpoint(line: &str) -> Result<std::net::SocketAddr> { |
| 582 | let address = line |
| 583 | .trim_end() |
| 584 | .strip_prefix(RUNTIME_LISTENING_PREFIX) |
| 585 | .context("runtime API bridge did not report its endpoint")?; |
| 586 | let endpoint: std::net::SocketAddr = address |
| 587 | .parse() |
| 588 | .context("runtime API bridge reported an invalid endpoint")?; |
| 589 | if endpoint.ip() != std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST) || endpoint.port() == 0 |
| 590 | { |
| 591 | bail!("runtime API bridge reported an endpoint that is not a loopback port"); |
| 592 | } |
| 593 | Ok(endpoint) |
| 594 | } |
| 595 | |
| 596 | /// Read the first stdout line, bounded. |
| 597 | #[cfg(test)] |
| 598 | pub(crate) fn read_runtime_ready_line(stdout: &mut impl std::io::Read) -> Result<String> { |
| 599 | let mut line = Vec::new(); |
| 600 | let mut byte = [0u8; 1]; |
| 601 | loop { |
| 602 | if stdout.read(&mut byte)? == 0 { |
| 603 | bail!("runtime API bridge closed stdout before reporting its endpoint"); |
| 604 | } |
| 605 | if byte[0] == b'\n' { |
| 606 | break; |
| 607 | } |
| 608 | if line.len() >= RUNTIME_READY_MAX_BYTES { |
| 609 | bail!("runtime API bridge sent an oversized readiness line"); |
| 610 | } |
| 611 | line.push(byte[0]); |
| 612 | } |
| 613 | String::from_utf8(line).context("runtime API bridge readiness line is not UTF-8") |
| 614 | } |
| 615 | |
| 616 | pub(crate) fn install_rustls_crypto_provider() { |
| 617 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 618 | } |
| 619 | |
| 620 | #[cfg(test)] |
| 621 | pub(crate) fn take_sse_frame(buffer: &mut Vec<u8>) -> Option<Vec<u8>> { |
| 622 | if let Some(pos) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { |
| 623 | return Some(buffer.drain(..pos + 4).collect()); |
| 624 | } |
| 625 | buffer |
| 626 | .windows(2) |
| 627 | .position(|window| window == b"\n\n") |
| 628 | .map(|pos| buffer.drain(..pos + 2).collect()) |
| 629 | } |
| 630 | |
| 631 | #[cfg(test)] |
| 632 | pub(crate) fn parse_sse_frame(frame_bytes: &[u8]) -> Option<(String, String)> { |
| 633 | let text = String::from_utf8(frame_bytes.to_vec()).ok()?; |
| 634 | let mut event_name = None; |
| 635 | let mut data_lines = Vec::new(); |
| 636 | for raw_line in text.lines() { |
| 637 | let line = raw_line.trim_end_matches('\r'); |
| 638 | if let Some(value) = line.strip_prefix("event:") { |
| 639 | event_name = Some(value.trim().to_string()); |
| 640 | } else if let Some(value) = line.strip_prefix("data:") { |
| 641 | data_lines.push(value.trim_start().to_string()); |
| 642 | } |
| 643 | } |
| 644 | match (event_name, data_lines.is_empty()) { |
| 645 | (Some(event), false) => Some((event, data_lines.join("\n"))), |
| 646 | _ => None, |
| 647 | } |
| 648 | } |
| 649 |