diff --git a/Cargo.toml b/Cargo.toml index 2197053..3a1480d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,8 @@ clap = { version = "4.6", features = ["derive", "env"] } crossterm = "0.29" futures-util = { version = "0.3", features = ["sink"] } httpdate = "1.0" +hex = "0.4" +sha2 = "0.11" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" @@ -33,8 +35,6 @@ uuid = { version = "1.27", features = ["v4", "serde"] } [target.'cfg(unix)'.dependencies] flate2 = "1" -hex = "0.4" -sha2 = "0.11" tar = "0.4" libc = "0.2" diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 77b71ff..e7dfa4d 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -397,7 +397,10 @@ adapt files get SANDBOX_ID /app/result.bin ./result.bin adapt files get SANDBOX_ID /app/result.bin - > result.bin ``` -The transfer limit is 16 MiB per file. +For local regular files larger than 16 MiB, `files put` hashes the file and streams +it to the sandbox in 8 MiB ranges. On a brief disconnect it asks the node which +bytes arrived and resumes there. This requires a node with large-upload support. +Downloads and uploads from stdin have a 16 MiB limit. Parent directories must exist in the sandbox. Use `-` for the local path to read stdin or write stdout. The CLI writes a download to its destination file only after the transfer completes. diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index 3c91282..b8e9f0c 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -113,7 +113,7 @@ adapt endpoints get ENDPOINT_ID adapt endpoints request ENDPOINT_ID /path --new-token ``` -File transfers are limited to 16 MiB and guest parent directories must exist. +Large regular files upload in resumable ranges. Downloads and stdin uploads are limited to 16 MiB. Guest parent directories must exist. Downloads refuse to overwrite local files unless `--force` is given. Hosted apps must listen on `0.0.0.0`. Endpoint tokens authenticate the hosted app with `X-Adapt-Authorization: Bearer TOKEN`; they are not Platform API credentials. diff --git a/src/api.rs b/src/api.rs index 14069ff..69c87fe 100644 --- a/src/api.rs +++ b/src/api.rs @@ -218,7 +218,7 @@ impl Api { } } -fn read_retry_delay(error: &anyhow::Error, backoff: Duration) -> Option { +pub(crate) fn read_retry_delay(error: &anyhow::Error, backoff: Duration) -> Option { if let Some(error) = error.downcast_ref::() { if !matches!(error.status.as_u16(), 408 | 429 | 500 | 502 | 503 | 504) { return None; diff --git a/src/commands.rs b/src/commands.rs index 6f2939f..65dd23d 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -605,6 +605,13 @@ pub(crate) async fn files(api: &Api, command: FileCommand) -> Result { local, remote, } => { + if local != Path::new("-") + && std::fs::metadata(&local) + .is_ok_and(|m| m.is_file() && m.len() > input::MAX_FILE_BYTES) + { + let id = crate::upload::put(api, &sandbox, &local, &remote).await?; + return Ok(json!({"uploaded":remote,"sandboxId":id})); + } let data = input::bytes(&local, input::MAX_FILE_BYTES)?; let response = api .request(Method::PUT, &format!("/v1/sandboxes/{sandbox}/files"))? diff --git a/src/main.rs b/src/main.rs index ee4a910..8241e7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ mod runtime; mod shell; mod skill; mod stream; +mod upload; use clap::{CommandFactory, Parser}; use cli::Cli; diff --git a/src/upload.rs b/src/upload.rs new file mode 100644 index 0000000..37f573b --- /dev/null +++ b/src/upload.rs @@ -0,0 +1,117 @@ +//! A seekable file can be checksummed once and replayed at the node's byte offset. +use crate::{ + api::{self, Api}, + input::ResourceRef, +}; +use anyhow::{Context, Result, ensure}; +use reqwest::Method; +use serde::Deserialize; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::{ + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, + time::Duration, +}; +use uuid::Uuid; + +const PART_BYTES: usize = 8 * 1024 * 1024; +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Progress { + offset: u64, + complete: bool, + sandbox_id: Uuid, +} + +pub(crate) async fn put( + api: &Api, + sandbox: &ResourceRef, + local: &Path, + remote: &str, +) -> Result { + let path = local.to_path_buf(); + let (mut file, size, digest) = tokio::task::spawn_blocking(move || -> Result<_> { + let mut file = File::open(path)?; + let size = file.metadata()?.len(); + let mut hash = Sha256::new(); + let mut block = vec![0; 256 * 1024]; + loop { + let n = file.read(&mut block)?; + if n == 0 { + break; + } + hash.update(&block[..n]); + } + Ok((file, size, hex::encode(hash.finalize()))) + }) + .await??; + let route = format!("/v1/sandboxes/{sandbox}/file-uploads/{}", Uuid::new_v4()); + let input = json!({"path":remote,"size":size,"sha256":digest}); + let mut progress: Option = None; + let mut retries = 0; + loop { + let attempt: Result = async { + let Some(current) = &progress else { + return Ok(serde_json::from_value( + api.json(Method::PUT, &route, Some(&input), &[], None) + .await?, + )?); + }; + let length = (size - current.offset).min(PART_BYTES as u64) as usize; + file.seek(SeekFrom::Start(current.offset))?; + let mut data = vec![0; length]; + file.read_exact(&mut data) + .context("Local file changed during upload")?; + let response = api + .request(Method::PUT, &format!("{route}/data"))? + .query(&[("offset", current.offset), ("length", length as u64)]) + .header("Content-Type", "application/octet-stream") + .body(data) + .timeout(api.timeout) + .send() + .await?; + let bytes = api::limited_bytes(api::ensure_success(response).await?, 8192).await?; + let next: Progress = serde_json::from_slice(&bytes)?; + ensure!( + next.complete || next.offset > current.offset, + "The upload made no progress" + ); + Ok(next) + } + .await; + match attempt { + Ok(next) => { + ensure!( + next.offset <= size && (!next.complete || next.offset == size), + "Invalid upload acknowledgement" + ); + if next.complete { + return Ok(next.sandbox_id); + } + if progress.is_some() { + retries = 0; + } + progress = Some(next); + } + Err(error) => { + let backoff = Duration::from_millis(250 << retries); + let conflict = error + .downcast_ref::() + .is_some_and(|e| matches!(e.status.as_u16(), 404 | 409)); + let delay = if conflict { + Some(backoff) + } else { + api::read_retry_delay(&error, backoff) + }; + let Some(delay) = delay.filter(|delay| retries < 3 && *delay < api.timeout) else { + return Err(error); + }; + retries += 1; + tokio::time::sleep(delay).await; + progress = None; + } + } + } +} diff --git a/tests/cli.rs b/tests/cli.rs index aad7f3a..d367e2d 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -884,3 +884,71 @@ fn missing_default_profile_and_profile_listing_do_not_warn() { success(&output); assert!(output.stderr.is_empty(), "{:?}", output.stderr); } + +#[test] +fn large_files_resume_at_acknowledged_bytes_and_return_full_sandbox_id() { + use sha2::{Digest, Sha256}; + const CHUNK: usize = 8 * 1024 * 1024; + const SIZE: usize = 2 * CHUNK + 3; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("large.bin"); + let data = vec![0x7a; SIZE]; + std::fs::write(&path, &data).unwrap(); + let digest = hex::encode(Sha256::digest(&data)); + let receipt = |offset: usize| { + Reply::json( + 200, + json!({"offset":offset,"complete":offset==SIZE,"sandboxId":ID}), + ) + }; + let server = Server::start(vec![ + Box::new(move |r| { + assert_eq!(r.method, "PUT"); + assert!(r.target.starts_with("/v1/sandboxes/11111111/file-uploads/")); + assert_eq!( + r.json(), + json!({"path":"/tmp/a","size":SIZE,"sha256":digest}) + ); + receipt(0) + }), + Box::new(move |r| { + assert_eq!(r.body.len(), CHUNK); + assert!(r.target.ends_with("/data?offset=0&length=8388608")); + Reply::json( + 502, + json!({"error":{"code":"BACKEND_ERROR","message":"response lost"}}), + ) + }), + Box::new(move |r| { + assert!(!r.target.contains("/data")); + receipt(CHUNK) + }), + Box::new(move |r| { + assert!(r.target.ends_with("/data?offset=8388608&length=8388608")); + assert!(r.body.iter().all(|b| *b == 0x7a)); + receipt(2 * CHUNK) + }), + Box::new(move |r| { + assert_eq!(r.body, vec![0x7a; 3]); + receipt(SIZE) + }), + ]); + let result = run( + dir.path(), + &server.url, + &[ + "--json", + "files", + "put", + "11111111", + path.to_str().unwrap(), + "/tmp/a", + ], + ); + success(&result); + assert_eq!( + serde_json::from_slice::(&result.stdout).unwrap(), + json!({"uploaded":"/tmp/a","sandboxId":ID}) + ); + server.finish(); +}