mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Route pet asset downloads through the shared HTTP client (#36008)
## Why Built-in pet downloads used a standalone blocking client, so CDN redirects did not use Codex's configured route handling. ## What changed - Download pet spritesheets asynchronously with a reusable `RouteAwareClientPool`. - Keep cache validation, asset installation, and pet decoding off the async runtime while sharing one asset-and-load path across startup, previews, and selection. - Preserve the download size limit while consuming streamed response chunks, and remove the TUI's direct `reqwest` dependency. ## Testing Add coverage for oversized response chunks, cached built-in assets, pet loads without an existing Tokio runtime, and stale preview and selection completions. GitOrigin-RevId: 725e76f3ddb7e84b7212769892f28dc0add15741
This commit is contained in:
1 parent
ad6fc66b6d
commit
09cf609218
11 files changed
+293
-95
No files matched your search
@@ -11,7 +11,6 @@
|
||||
//! built-in pet is safe to persist to config.
|
||||
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
@@ -19,6 +18,7 @@ use std::time::Duration;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -42,44 +42,58 @@ pub(crate) fn builtin_spritesheet_path(codex_home: &Path, file: &str) -> PathBuf
|
||||
/// validates the decoded image dimensions, and installs it atomically. Callers
|
||||
/// should treat any error here as "the asset is unavailable", not as a partial
|
||||
/// install they can safely ignore.
|
||||
pub(crate) fn ensure_builtin_pet(codex_home: &Path, pet: catalog::BuiltinPet) -> Result<()> {
|
||||
pub(crate) async fn ensure_builtin_pet(
|
||||
codex_home: &Path,
|
||||
pet: catalog::BuiltinPet,
|
||||
http_client: &RouteAwareClientPool,
|
||||
) -> Result<()> {
|
||||
let destination = builtin_spritesheet_path(codex_home, pet.spritesheet_file);
|
||||
if validate_cached_spritesheet(&destination).is_ok() {
|
||||
let cache_destination = destination.clone();
|
||||
let cache_valid = tokio::task::spawn_blocking(move || {
|
||||
validate_cached_spritesheet(&cache_destination).is_ok()
|
||||
})
|
||||
.await
|
||||
.context("join pet spritesheet cache validation task")?;
|
||||
if cache_valid {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let url = builtin_pet_url(pet)?;
|
||||
let bytes = download_bytes_with_limit(&url, PET_MAX_DOWNLOAD_BYTES)?;
|
||||
let parent = destination
|
||||
.parent()
|
||||
.context("pet spritesheet path should include an assets directory")?;
|
||||
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
||||
let bytes = download_bytes_with_limit(http_client, &url, PET_MAX_DOWNLOAD_BYTES).await?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let parent = destination
|
||||
.parent()
|
||||
.context("pet spritesheet path should include an assets directory")?;
|
||||
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
||||
|
||||
let staging = destination.with_file_name(format!(
|
||||
".{}.download-{}.webp",
|
||||
pet.spritesheet_file,
|
||||
Uuid::new_v4()
|
||||
));
|
||||
fs::write(&staging, &bytes).with_context(|| format!("write {}", staging.display()))?;
|
||||
if let Err(err) = validate_cached_spritesheet(&staging) {
|
||||
let _ = fs::remove_file(&staging);
|
||||
return Err(err);
|
||||
}
|
||||
let staging = destination.with_file_name(format!(
|
||||
".{}.download-{}.webp",
|
||||
pet.spritesheet_file,
|
||||
Uuid::new_v4()
|
||||
));
|
||||
fs::write(&staging, &bytes).with_context(|| format!("write {}", staging.display()))?;
|
||||
if let Err(err) = validate_cached_spritesheet(&staging) {
|
||||
let _ = fs::remove_file(&staging);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
if install_downloaded_spritesheet(&staging, &destination).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
if install_downloaded_spritesheet(&staging, &destination).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if validate_cached_spritesheet(&destination).is_ok() {
|
||||
let _ = fs::remove_file(&staging);
|
||||
return Ok(());
|
||||
}
|
||||
if validate_cached_spritesheet(&destination).is_ok() {
|
||||
let _ = fs::remove_file(&staging);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if destination.exists() {
|
||||
fs::remove_file(&destination)
|
||||
.with_context(|| format!("remove {}", destination.display()))?;
|
||||
}
|
||||
install_downloaded_spritesheet(&staging, &destination)
|
||||
if destination.exists() {
|
||||
fs::remove_file(&destination)
|
||||
.with_context(|| format!("remove {}", destination.display()))?;
|
||||
}
|
||||
install_downloaded_spritesheet(&staging, &destination)
|
||||
})
|
||||
.await
|
||||
.context("join pet spritesheet install task")?
|
||||
}
|
||||
|
||||
fn builtin_pet_url(pet: catalog::BuiltinPet) -> Result<String> {
|
||||
@@ -92,14 +106,17 @@ fn pack_dir(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(PET_PACK_DIR).join(PET_PACK_VERSION)
|
||||
}
|
||||
|
||||
fn download_bytes_with_limit(url: &str, max_bytes: u64) -> Result<Vec<u8>> {
|
||||
async fn download_bytes_with_limit(
|
||||
http_client: &RouteAwareClientPool,
|
||||
url: &str,
|
||||
max_bytes: u64,
|
||||
) -> Result<Vec<u8>> {
|
||||
validate_download_url(url)?;
|
||||
let response = reqwest::blocking::Client::builder()
|
||||
.timeout(PET_DOWNLOAD_TIMEOUT)
|
||||
.build()
|
||||
.context("build pet asset download client")?
|
||||
let mut response = http_client
|
||||
.get(url)
|
||||
.timeout(PET_DOWNLOAD_TIMEOUT)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("download pet asset from {url}"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("download pet asset from {url}"))?;
|
||||
@@ -110,16 +127,29 @@ fn download_bytes_with_limit(url: &str, max_bytes: u64) -> Result<Vec<u8>> {
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
response
|
||||
.take(max_bytes.saturating_add(/*rhs*/ 1))
|
||||
.read_to_end(&mut bytes)
|
||||
.with_context(|| format!("read pet asset download from {url}"))?;
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
bail!("pet asset download from {url} exceeded {max_bytes} bytes");
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.with_context(|| format!("read pet asset download from {url}"))?
|
||||
{
|
||||
append_download_chunk(&mut bytes, &chunk, max_bytes, url)?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn append_download_chunk(
|
||||
bytes: &mut Vec<u8>,
|
||||
chunk: &[u8],
|
||||
max_bytes: u64,
|
||||
url: &str,
|
||||
) -> Result<()> {
|
||||
if (bytes.len() as u64).saturating_add(chunk.len() as u64) > max_bytes {
|
||||
bail!("pet asset download from {url} exceeded {max_bytes} bytes");
|
||||
}
|
||||
bytes.extend_from_slice(chunk);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install_downloaded_spritesheet(staging: &Path, destination: &Path) -> Result<()> {
|
||||
fs::rename(staging, destination).with_context(|| format!("install {}", destination.display()))
|
||||
}
|
||||
@@ -175,6 +205,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_download_chunk_is_rejected() {
|
||||
let url = "https://example.com/pet.webp";
|
||||
let mut bytes = Vec::new();
|
||||
|
||||
append_download_chunk(&mut bytes, b"1234", /*max_bytes*/ 8, url).unwrap();
|
||||
let error = append_download_chunk(&mut bytes, b"56789", /*max_bytes*/ 8, url)
|
||||
.expect_err("chunk should exceed the download limit");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"pet asset download from https://example.com/pet.webp exceeded 8 bytes"
|
||||
);
|
||||
assert_eq!(bytes, b"1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_test_pack_installs_all_builtins() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
//! resolving a selected pet id, preparing frames for terminal image protocols,
|
||||
//! rendering the ambient sprite and picker preview, and preserving enough
|
||||
//! metadata for `/pets` to behave like a first-class configuration surface.
|
||||
//! It does not own config persistence or popup orchestration; callers must
|
||||
//! ensure a built-in asset exists before loading it and must persist the final
|
||||
//! selection only after the load succeeds.
|
||||
//! It prepares built-in assets before loading pets, but does not own config
|
||||
//! persistence or popup orchestration; callers must persist the final selection
|
||||
//! only after the load succeeds.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
@@ -27,6 +27,10 @@ mod sixel;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use crate::tui::FrameRequester;
|
||||
|
||||
pub(crate) use ambient::AmbientPet;
|
||||
pub(crate) use ambient::AmbientPetDraw;
|
||||
@@ -53,20 +57,41 @@ pub(crate) const DISABLED_PET_ID: &str = "disabled";
|
||||
/// Ensure that a selected built-in pet has a locally cached spritesheet.
|
||||
///
|
||||
/// Custom pets are intentionally a no-op here because their source of truth is
|
||||
/// already local. Callers should invoke this before loading a built-in pet for
|
||||
/// preview or selection; skipping it would make first-use preview and
|
||||
/// persistence failures depend on deeper image-loading errors instead of the
|
||||
/// asset-fetch boundary.
|
||||
pub(crate) fn ensure_builtin_pack_for_pet(
|
||||
/// already local. Preparing this before loading keeps first-use preview and
|
||||
/// persistence failures at the asset-fetch boundary rather than surfacing as
|
||||
/// deeper image-loading errors.
|
||||
async fn ensure_builtin_pack_for_pet(
|
||||
pet_id: &str,
|
||||
codex_home: &std::path::Path,
|
||||
http_client: &RouteAwareClientPool,
|
||||
) -> Result<()> {
|
||||
if let Some(pet) = catalog::builtin_pet(pet_id) {
|
||||
asset_pack::ensure_builtin_pet(codex_home, pet)?;
|
||||
asset_pack::ensure_builtin_pet(codex_home, pet, http_client).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prepare a pet's built-in assets and load its synchronous state off the runtime.
|
||||
pub(crate) async fn load_pet_with_assets(
|
||||
pet_id: String,
|
||||
codex_home: AbsolutePathBuf,
|
||||
frame_requester: FrameRequester,
|
||||
animations_enabled: bool,
|
||||
http_client: &RouteAwareClientPool,
|
||||
) -> Result<AmbientPet> {
|
||||
ensure_builtin_pack_for_pet(&pet_id, &codex_home, http_client).await?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
AmbientPet::load(
|
||||
Some(&pet_id),
|
||||
&codex_home,
|
||||
frame_requester,
|
||||
animations_enabled,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.context("join pet load task")?
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum PetImageRenderError {
|
||||
Terminal(std::io::Error),
|
||||
|
||||
Reference in new issue
Block a user