Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(desktop-gpui): upload multipart parts one at a time over per-upload clients

Richie McIlroy82e7165b802b
diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rs
index a54faada6..fdf03f9c0 100644
--- a/apps/desktop-gpui/src/upload.rs
+++ b/apps/desktop-gpui/src/upload.rs
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -21,7 +21,6 @@ pub(crate) mod queue;
const MIN_CHUNK_SIZE: u64 = 5 * 1024 * 1024;
const MAX_CHUNK_SIZE: u64 = 15 * 1024 * 1024;
-const MAX_CONCURRENT_PARTS: usize = 4;
const MAX_SEGMENT_UPLOADS: usize = 6;
const SEGMENT_URL_PREFETCH: u32 = 20;
const SEGMENT_UPLOAD_ATTEMPTS: u32 = 3;
@@ -1646,6 +1645,7 @@ async fn multipart_initiate(
}
async fn multipart_presign(
+ client: &reqwest::Client,
video_id: &str,
upload_id: &str,
part_number: u32,
@@ -1666,7 +1666,8 @@ async fn multipart_presign(
body.insert("md5Sum".into(), json!(md5_sum));
}
- let response = auth::authed_request(
+ let response = auth::authed_request_with(
+ client,
reqwest::Method::POST,
"/api/upload/multipart/presign-part",
Some(Value::Object(body)),
@@ -1770,13 +1771,14 @@ async fn upload_parts(
upload_id,
is_drive,
use_md5: auth::is_server_url_custom(),
+ api: auth::api_client()?,
+ storage: reqwest::Client::new(),
};
upload_file_parts(
&transport,
file_path,
file_size,
chunk_size_for(file_size),
- PartConcurrency::new(is_drive, MAX_CONCURRENT_PARTS),
progress,
cancel,
replacement_source,
@@ -1784,63 +1786,6 @@ async fn upload_parts(
.await
}
-const PARTS_UNKNOWN: u8 = 0;
-const PARTS_CONCURRENT: u8 = 1;
-const PARTS_SEQUENTIAL: u8 = 2;
-
-/// How many parts may be in flight. Drive resumable sessions take
-/// Content-Range bytes strictly in order, and a part is Drive when either the
-/// initiate response or its own presigned URL says so. Parts therefore go one
-/// at a time until the first presigned URL proves the upload is S3-style, and
-/// any Drive URL drops the upload back to one part at a time for good.
-struct PartConcurrency {
- is_drive: bool,
- max: usize,
- mode: AtomicU8,
- changed: tokio::sync::Notify,
-}
-
-impl PartConcurrency {
- fn new(is_drive: bool, max: usize) -> Self {
- Self {
- is_drive,
- max: max.max(1),
- mode: AtomicU8::new(if is_drive {
- PARTS_SEQUENTIAL
- } else {
- PARTS_UNKNOWN
- }),
- changed: tokio::sync::Notify::new(),
- }
- }
-
- fn observe_url(&self, url: &str) {
- let changed = if self.is_drive || is_google_drive_resumable_url(url) {
- self.mode.swap(PARTS_SEQUENTIAL, Ordering::AcqRel) != PARTS_SEQUENTIAL
- } else {
- self.mode
- .compare_exchange(
- PARTS_UNKNOWN,
- PARTS_CONCURRENT,
- Ordering::AcqRel,
- Ordering::Acquire,
- )
- .is_ok()
- };
- if changed {
- self.changed.notify_one();
- }
- }
-
- fn limit(&self) -> usize {
- if self.mode.load(Ordering::Acquire) == PARTS_CONCURRENT {
- self.max
- } else {
- 1
- }
- }
-}
-
struct PartChunk {
part_number: u32,
offset: u64,
@@ -1867,11 +1812,17 @@ trait PartTransport: Sync {
) -> impl Future<Output = Result<UploadedPart, AuthApiError>> + Send;
}
+/// Every part of one upload goes through the same two clients, so parts after
+/// the first reuse the open API and storage connections. The clients live only
+/// as long as the upload, so a later upload never starts on a pooled
+/// connection from an earlier network.
struct LivePartTransport<'a> {
video_id: &'a str,
upload_id: &'a str,
is_drive: bool,
use_md5: bool,
+ api: reqwest::Client,
+ storage: reqwest::Client,
}
impl PartTransport for LivePartTransport<'_> {
@@ -1883,6 +1834,7 @@ impl PartTransport for LivePartTransport<'_> {
let md5 = self.use_md5.then(|| md5_base64(&chunk.bytes));
let url = checked_upload_step(cancel, || {
multipart_presign(
+ &self.api,
self.video_id,
self.upload_id,
chunk.part_number,
@@ -1901,7 +1853,7 @@ impl PartTransport for LivePartTransport<'_> {
cancel: &AtomicBool,
) -> Result<UploadedPart, AuthApiError> {
put_presigned_part(
- multipart_upload_client(),
+ &self.storage,
&presigned.url,
chunk,
total_size,
@@ -1913,119 +1865,78 @@ impl PartTransport for LivePartTransport<'_> {
}
}
+/// Part requests only observe cancellation between requests, so this races
+/// them against the cancel flag to drop an in-flight part promptly.
async fn upload_part_chunk(
transport: &impl PartTransport,
- concurrency: &PartConcurrency,
- chunk: PartChunk,
+ chunk: &PartChunk,
total_size: u64,
cancel: &AtomicBool,
-) -> (PartChunk, Result<UploadedPart, AuthApiError>) {
- let result = async {
- let presigned = transport.presign(&chunk, cancel).await?;
- concurrency.observe_url(&presigned.url);
- transport.put(&presigned, &chunk, total_size, cancel).await
+) -> Result<UploadedPart, AuthApiError> {
+ tokio::select! {
+ biased;
+ () = wait_for_export_cancel(cancel) => Err(AuthApiError::Other("Export cancelled".into())),
+ result = async {
+ let presigned = transport.presign(chunk, cancel).await?;
+ transport.put(&presigned, chunk, total_size, cancel).await
+ } => result,
}
- .await;
- (chunk, result)
}
-/// Resolves once `cancel` is set. Part PUTs only observe cancellation between
-/// requests, so the pipeline races this to drop in-flight parts promptly.
async fn wait_for_export_cancel(cancel: &AtomicBool) {
while !cancel.load(Ordering::Acquire) {
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
-/// Reads, replacement checks and part numbering stay strictly in order; only
-/// the presign and PUT of different parts overlap.
-#[allow(clippy::too_many_arguments)]
+/// Parts go strictly one at a time, so an interrupted connection only ever
+/// loses the one part that was in flight.
async fn upload_file_parts(
transport: &impl PartTransport,
file_path: &Path,
file_size: u64,
chunk_size: u64,
- concurrency: PartConcurrency,
progress: &impl Fn(f64),
cancel: &AtomicBool,
mut replacement_source: Option<&mut ReplacementUploadSource>,
) -> Result<Vec<UploadedPart>, AuthApiError> {
- let concurrency = &concurrency;
let mut parts = Vec::new();
let mut failed = Vec::new();
- let mut in_flight = FuturesUnordered::new();
let mut offset = 0u64;
let mut part_number = 1u32;
- let mut settled = 0u64;
- loop {
- while in_flight.len() < concurrency.limit() && offset < file_size {
- if cancel.load(Ordering::Relaxed) {
- return Err(AuthApiError::Other("Export cancelled".into()));
- }
- let size = (file_size - offset).min(chunk_size) as usize;
- let chunk = read_chunk(file_path, offset, size)?;
- if let Some(source) = &mut replacement_source {
- source.check_chunk(part_number, offset, &chunk, file_size)?;
- }
- in_flight.push(upload_part_chunk(
- transport,
- concurrency,
- PartChunk {
- part_number,
- offset,
- bytes: chunk.into(),
- },
- file_size,
- cancel,
- ));
- offset += size as u64;
- part_number += 1;
- }
- let next = tokio::select! {
- biased;
- () = wait_for_export_cancel(cancel) => {
- return Err(AuthApiError::Other("Export cancelled".into()));
- }
- next = in_flight.next() => Some(next),
- // A presigned URL can raise the limit while parts are still in flight.
- () = concurrency.changed.notified(), if offset < file_size => None,
- };
- let Some(next) = next else {
- continue;
- };
- let Some((chunk, result)) = next else {
- break;
+ while offset < file_size {
+ if cancel.load(Ordering::Relaxed) {
+ return Err(AuthApiError::Other("Export cancelled".into()));
+ }
+ let size = (file_size - offset).min(chunk_size) as usize;
+ let chunk = read_chunk(file_path, offset, size)?;
+ if let Some(source) = &mut replacement_source {
+ source.check_chunk(part_number, offset, &chunk, file_size)?;
+ }
+ let chunk = PartChunk {
+ part_number,
+ offset,
+ bytes: chunk.into(),
};
- settled += chunk.bytes.len() as u64;
- match result {
+ match upload_part_chunk(transport, &chunk, file_size, cancel).await {
Ok(part) => parts.push(part),
Err(error) => {
check_export_cancelled(cancel)?;
- tracing::warn!(
- part_number = chunk.part_number,
- error = %error,
- "chunk upload failed; will retry"
- );
+ tracing::warn!(part_number, error = %error, "chunk upload failed; will retry");
failed.push((chunk, error));
}
}
- progress((settled as f64 / file_size as f64).min(0.99));
+ offset += size as u64;
+ part_number += 1;
+ progress((offset as f64 / file_size as f64).min(0.99));
}
- failed.sort_by_key(|(chunk, _)| chunk.part_number);
for (chunk, first_error) in failed {
if cancel.load(Ordering::Relaxed) {
return Err(AuthApiError::Other("Export cancelled".into()));
}
- let (_, result) = tokio::select! {
- biased;
- () = wait_for_export_cancel(cancel) => {
- return Err(AuthApiError::Other("Export cancelled".into()));
- }
- result = upload_part_chunk(transport, concurrency, chunk, file_size, cancel) => result,
- };
- match result {
+ match upload_part_chunk(transport, &chunk, file_size, cancel).await {
Ok(part) => parts.push(part),
Err(_) => {
check_export_cancelled(cancel)?;
@@ -2044,11 +1955,6 @@ async fn upload_file_parts(
Ok(parts)
}
-fn multipart_upload_client() -> &'static reqwest::Client {
- static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
- CLIENT.get_or_init(reqwest::Client::new)
-}
-
async fn put_presigned_part(
client: &reqwest::Client,
url: &str,
diff --git a/apps/desktop-gpui/src/upload/multipart_tests.rs b/apps/desktop-gpui/src/upload/multipart_tests.rs
index 59f120f12..dc399850d 100644
--- a/apps/desktop-gpui/src/upload/multipart_tests.rs
+++ b/apps/desktop-gpui/src/upload/multipart_tests.rs
@@ -36,24 +36,18 @@ impl Drop for InFlight<'_> {
}
const S3_URL: &str = "https://cap-test.s3.us-east-1.amazonaws.com/export.mp4?partNumber=";
-const DRIVE_URL: &str =
- "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=";
#[derive(Default)]
struct FakeParts {
/// Every part PUT in start order, with the bytes it sent.
started: Mutex<Vec<(u32, u64, Vec<u8>)>>,
- /// (event, part) in order: "presign", "presigned", "put".
+ /// (event, part) in order: "presign", "put".
events: Mutex<Vec<(&'static str, u32)>>,
- /// PUTs in flight when each part's PUT started, itself included.
- put_in_flight: Mutex<Vec<(u32, usize)>>,
in_flight: AtomicUsize,
max_in_flight: AtomicUsize,
fail_once: Mutex<HashSet<u32>>,
fail_always: HashSet<u32>,
hang_from: Option<u32>,
- drive_from: Option<u32>,
- presign_delay: Duration,
}
impl FakeParts {
@@ -65,15 +59,6 @@ impl FakeParts {
.map(|(part, _, _)| *part)
.collect()
}
-
- fn event_index(&self, event: &str, part: u32) -> usize {
- self.events
- .lock()
- .unwrap()
- .iter()
- .position(|entry| *entry == (event, part))
- .unwrap()
- }
}
impl PartTransport for FakeParts {
@@ -86,23 +71,8 @@ impl PartTransport for FakeParts {
.lock()
.unwrap()
.push(("presign", chunk.part_number));
- if !self.presign_delay.is_zero() {
- tokio::time::sleep(self.presign_delay).await;
- }
- self.events
- .lock()
- .unwrap()
- .push(("presigned", chunk.part_number));
- let base = if self
- .drive_from
- .is_some_and(|from| chunk.part_number >= from)
- {
- DRIVE_URL
- } else {
- S3_URL
- };
Ok(PresignedPart {
- url: format!("{base}{}", chunk.part_number),
+ url: format!("{S3_URL}{}", chunk.part_number),
md5: None,
})
}
@@ -122,15 +92,10 @@ impl PartTransport for FakeParts {
let now = self.in_flight.fetch_add(1, Ordering::AcqRel) + 1;
let _guard = InFlight(&self.in_flight);
self.max_in_flight.fetch_max(now, Ordering::AcqRel);
- self.put_in_flight
- .lock()
- .unwrap()
- .push((chunk.part_number, now));
if self.hang_from.is_some_and(|from| chunk.part_number >= from) {
std::future::pending::<()>().await;
}
- // Later parts in each window finish first, so completions arrive out of order.
- tokio::time::sleep(Duration::from_millis(u64::from(4 - chunk.part_number % 4))).await;
+ tokio::time::sleep(Duration::from_millis(1)).await;
if self.fail_always.contains(&chunk.part_number)
|| self.fail_once.lock().unwrap().remove(&chunk.part_number)
{
@@ -148,15 +113,10 @@ impl PartTransport for FakeParts {
}
}
-fn s3() -> PartConcurrency {
- PartConcurrency::new(false, MAX_CONCURRENT_PARTS)
-}
-
async fn run(
transport: &impl PartTransport,
export: &TempExport,
chunk_size: u64,
- concurrency: PartConcurrency,
cancel: &AtomicBool,
source: Option<&mut ReplacementUploadSource>,
) -> (Result<Vec<UploadedPart>, AuthApiError>, Vec<f64>) {
@@ -167,7 +127,6 @@ async fn run(
&export.0,
size,
chunk_size,
- concurrency,
&|value| progress.lock().unwrap().push(value),
cancel,
source,
@@ -188,117 +147,20 @@ fn assert_parts(parts: &[UploadedPart], sizes: &[usize]) {
assert_eq!(serde_json::to_value(parts).unwrap(), Value::Array(expected));
}
-#[test]
-fn part_concurrency_follows_the_initiate_response_and_every_presigned_url() {
- const { assert!(MAX_CONCURRENT_PARTS > 1) };
- let s3_url = format!("{S3_URL}1");
- let drive_url = format!("{DRIVE_URL}1");
-
- let drive = PartConcurrency::new(true, MAX_CONCURRENT_PARTS);
- assert_eq!(drive.limit(), 1);
- drive.observe_url(&s3_url);
- assert_eq!(drive.limit(), 1);
-
- let unknown = s3();
- assert_eq!(unknown.limit(), 1);
- unknown.observe_url(&s3_url);
- assert_eq!(unknown.limit(), MAX_CONCURRENT_PARTS);
- unknown.observe_url(&drive_url);
- assert_eq!(unknown.limit(), 1);
- unknown.observe_url(&s3_url);
- assert_eq!(unknown.limit(), 1);
-
- let drive_url_first = s3();
- drive_url_first.observe_url(&drive_url);
- assert_eq!(drive_url_first.limit(), 1);
- drive_url_first.observe_url(&s3_url);
- assert_eq!(drive_url_first.limit(), 1);
-}
-
-#[tokio::test]
-async fn parts_stay_one_at_a_time_until_the_first_presigned_url_is_known() {
- let export = TempExport::new(&export_bytes(40));
- let transport = FakeParts {
- presign_delay: Duration::from_millis(5),
- ..FakeParts::default()
- };
- let (result, _) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
- assert_parts(&result.unwrap(), &[4; 10]);
- // Part 1 alone until its URL is known, then the other three slots fill at once.
- assert_eq!(
- transport.events.lock().unwrap()[..6],
- [
- ("presign", 1),
- ("presigned", 1),
- ("put", 1),
- ("presign", 2),
- ("presign", 3),
- ("presign", 4),
- ]
- );
-}
-
#[tokio::test]
-async fn drive_urls_without_a_drive_initiate_upload_sequentially_with_serial_progress() {
- let export = TempExport::new(&export_bytes(18));
- let transport = FakeParts {
- drive_from: Some(1),
- ..FakeParts::default()
- };
- let (result, progress) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
+async fn parts_upload_one_at_a_time_in_order_with_serial_progress() {
+ let bytes = export_bytes(18);
+ let export = TempExport::new(&bytes);
+ let transport = FakeParts::default();
+ let (result, progress) = run(&transport, &export, 4, &AtomicBool::new(false), None).await;
assert_parts(&result.unwrap(), &[4, 4, 4, 4, 2]);
assert_eq!(transport.max_in_flight.load(Ordering::Acquire), 1);
assert_eq!(
*transport.events.lock().unwrap(),
(1..=5)
- .flat_map(|part| [("presign", part), ("presigned", part), ("put", part)])
+ .flat_map(|part| [("presign", part), ("put", part)])
.collect::<Vec<_>>()
);
- assert_eq!(
- progress,
- [4.0 / 18.0, 8.0 / 18.0, 12.0 / 18.0, 16.0 / 18.0, 0.99]
- );
-}
-
-#[tokio::test]
-async fn late_drive_url_drains_in_flight_parts_then_continues_one_at_a_time() {
- let export = TempExport::new(&export_bytes(48));
- let transport = FakeParts {
- drive_from: Some(6),
- ..FakeParts::default()
- };
- let (result, _) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
- assert_parts(&result.unwrap(), &[4; 12]);
- assert_eq!(transport.max_in_flight.load(Ordering::Acquire), 4);
- // At most MAX_CONCURRENT_PARTS parts (6 and up to three after it) can be in
- // flight when part 6's Drive URL arrives; every part after those is read
- // only once the in-flight parts have drained, and then runs alone.
- let first_after_switch = 6 + MAX_CONCURRENT_PARTS as u32;
- let switched = transport.event_index("presigned", 6);
- let put_in_flight = transport.put_in_flight.lock().unwrap();
- for part in first_after_switch..=12 {
- assert!(transport.event_index("presign", part) > switched);
- assert!(
- put_in_flight.contains(&(part, 1)),
- "part {part} overlapped: {put_in_flight:?}"
- );
- }
- assert_eq!(transport.started_parts(), (1..=12).collect::<Vec<_>>());
-}
-
-#[tokio::test]
-async fn concurrent_parts_complete_sorted_with_bounded_in_flight() {
- let bytes = export_bytes(42);
- let export = TempExport::new(&bytes);
- let transport = FakeParts::default();
- let (result, _) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
- let parts = result.unwrap();
- let mut sizes = vec![4; 10];
- sizes.push(2);
- assert_parts(&parts, &sizes);
- assert_eq!(transport.max_in_flight.load(Ordering::Acquire), 4);
- assert_eq!(transport.in_flight.load(Ordering::Acquire), 0);
- assert_eq!(transport.started_parts(), (1..=11).collect::<Vec<_>>());
for (part, offset, chunk) in transport.started.lock().unwrap().iter() {
assert_eq!(*offset, u64::from(part - 1) * 4);
let start = *offset as usize;
@@ -307,41 +169,12 @@ async fn concurrent_parts_complete_sorted_with_bounded_in_flight() {
&bytes[start..(start + 4).min(bytes.len())]
);
}
-}
-
-#[tokio::test]
-async fn drive_parts_upload_sequentially_in_order_with_serial_progress() {
- let export = TempExport::new(&export_bytes(18));
- let transport = FakeParts::default();
- let (result, progress) = run(
- &transport,
- &export,
- 4,
- PartConcurrency::new(true, MAX_CONCURRENT_PARTS),
- &AtomicBool::new(false),
- None,
- )
- .await;
- assert_parts(&result.unwrap(), &[4, 4, 4, 4, 2]);
- assert_eq!(transport.max_in_flight.load(Ordering::Acquire), 1);
- assert_eq!(transport.started_parts(), [1, 2, 3, 4, 5]);
assert_eq!(
progress,
[4.0 / 18.0, 8.0 / 18.0, 12.0 / 18.0, 16.0 / 18.0, 0.99]
);
}
-#[tokio::test]
-async fn concurrent_progress_is_monotonic_and_reaches_the_serial_final_value() {
- let export = TempExport::new(&export_bytes(64));
- let transport = FakeParts::default();
- let (result, progress) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
- assert_eq!(result.unwrap().len(), 16);
- assert_eq!(progress.len(), 16);
- assert!(progress.windows(2).all(|pair| pair[0] <= pair[1]));
- assert_eq!(progress.last().copied(), Some(0.99));
-}
-
#[tokio::test]
async fn failed_part_is_retried_after_the_rest_and_upload_completes() {
let export = TempExport::new(&export_bytes(40));
@@ -349,7 +182,7 @@ async fn failed_part_is_retried_after_the_rest_and_upload_completes() {
fail_once: Mutex::new(HashSet::from([3, 6])),
..FakeParts::default()
};
- let (result, progress) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
+ let (result, progress) = run(&transport, &export, 4, &AtomicBool::new(false), None).await;
assert_parts(&result.unwrap(), &[4; 10]);
let started = transport.started_parts();
assert_eq!(started.len(), 12);
@@ -366,7 +199,7 @@ async fn part_failing_its_retry_returns_the_first_error() {
fail_always: HashSet::from([2]),
..FakeParts::default()
};
- let (result, _) = run(&transport, &export, 4, s3(), &AtomicBool::new(false), None).await;
+ let (result, _) = run(&transport, &export, 4, &AtomicBool::new(false), None).await;
assert_eq!(
result.unwrap_err().to_string(),
"uploader/part/2/status/500"
@@ -375,7 +208,7 @@ async fn part_failing_its_retry_returns_the_first_error() {
}
#[tokio::test]
-async fn cancel_mid_upload_drops_in_flight_parts_and_starts_no_more() {
+async fn cancel_mid_upload_drops_the_in_flight_part_and_starts_no_more() {
let export = TempExport::new(&export_bytes(40));
let transport = FakeParts {
hang_from: Some(3),
@@ -383,33 +216,32 @@ async fn cancel_mid_upload_drops_in_flight_parts_and_starts_no_more() {
};
let cancel = AtomicBool::new(false);
let started = Instant::now();
- let (result, progress) =
- tokio::join!(run(&transport, &export, 4, s3(), &cancel, None), async {
- while transport.started_parts().len() < 6 {
- tokio::time::sleep(Duration::from_millis(1)).await;
- }
- cancel.store(true, Ordering::Release);
- })
- .0;
+ let (result, progress) = tokio::join!(run(&transport, &export, 4, &cancel, None), async {
+ while transport.started_parts().len() < 3 {
+ tokio::time::sleep(Duration::from_millis(1)).await;
+ }
+ cancel.store(true, Ordering::Release);
+ })
+ .0;
assert!(result.unwrap_err().to_string().contains("Export cancelled"));
assert!(started.elapsed() < Duration::from_secs(2));
- assert_eq!(transport.started_parts(), [1, 2, 3, 4, 5, 6]);
+ assert_eq!(transport.started_parts(), [1, 2, 3]);
assert_eq!(transport.in_flight.load(Ordering::Acquire), 0);
- assert!(progress.windows(2).all(|pair| pair[0] <= pair[1]));
+ assert_eq!(progress, [0.1, 0.2]);
}
#[tokio::test]
async fn cancelled_before_start_reads_no_parts() {
let export = TempExport::new(&export_bytes(40));
let transport = FakeParts::default();
- let (result, progress) = run(&transport, &export, 4, s3(), &AtomicBool::new(true), None).await;
+ let (result, progress) = run(&transport, &export, 4, &AtomicBool::new(true), None).await;
assert!(result.unwrap_err().to_string().contains("Export cancelled"));
assert!(transport.started_parts().is_empty());
assert!(progress.is_empty());
}
#[tokio::test]
-async fn concurrent_replacement_upload_checks_reads_in_order_and_seals() {
+async fn replacement_upload_checks_reads_in_order_and_seals() {
let export = TempExport::new(&export_bytes(22));
let mut source = ReplacementUploadSource::new(&export.0).unwrap();
let transport = FakeParts::default();
@@ -417,7 +249,6 @@ async fn concurrent_replacement_upload_checks_reads_in_order_and_seals() {
&transport,
&export,
4,
- s3(),
&AtomicBool::new(false),
Some(&mut source),
)
@@ -438,7 +269,6 @@ async fn concurrent_replacement_upload_checks_reads_in_order_and_seals() {
&restarted,
&export,
4,
- s3(),
&AtomicBool::new(false),
Some(&mut source),
)
@@ -447,7 +277,6 @@ async fn concurrent_replacement_upload_checks_reads_in_order_and_seals() {
serde_json::to_value(result.unwrap()).unwrap(),
serde_json::to_value(&parts).unwrap()
);
- assert_eq!(restarted.max_in_flight.load(Ordering::Acquire), 4);
std::fs::write(&export.0, &export_bytes(23)[1..]).unwrap();
let changed = FakeParts::default();
@@ -455,7 +284,6 @@ async fn concurrent_replacement_upload_checks_reads_in_order_and_seals() {
&changed,
&export,
4,
- s3(),
&AtomicBool::new(false),
Some(&mut source),
)
@@ -668,13 +496,14 @@ fn local_client() -> reqwest::Client {
reqwest::Client::builder().no_proxy().build().unwrap()
}
-/// Presigns over a fresh client per part, like `auth::authed_request`, then
-/// runs the real part PUT on either a fresh client per part (the previous
-/// behaviour) or one shared client. With `drive_urls`, presigning returns
-/// Google Drive resumable URLs that the shared client resolves to the server.
+/// Presigns and PUTs over real HTTP, either on a fresh client per request (the
+/// previous behaviour, where `auth::authed_request` and every part built their
+/// own client) or on one API client and one storage client for the upload.
+/// With `drive_urls`, presigning returns Google Drive resumable URLs that the
+/// storage client resolves to the server.
struct MockPartTransport {
addr: std::net::SocketAddr,
- shared: Option<reqwest::Client>,
+ shared: Option<(reqwest::Client, reqwest::Client)>,
drive_urls: bool,
}
@@ -699,7 +528,15 @@ impl PartTransport for MockPartTransport {
md5: None,
});
}
- let url = local_client()
+ let fresh;
+ let client = match &self.shared {
+ Some((api, _)) => api,
+ None => {
+ fresh = local_client();
+ &fresh
+ }
+ };
+ let url = client
.post(format!(
"http://{}/presign/{}",
self.addr, chunk.part_number
@@ -724,7 +561,7 @@ impl PartTransport for MockPartTransport {
) -> Result<UploadedPart, AuthApiError> {
let fresh;
let client = match &self.shared {
- Some(client) => client,
+ Some((_, storage)) => storage,
None => {
fresh = local_client();
&fresh
@@ -759,24 +596,17 @@ async fn drive_urls_without_a_drive_initiate_are_put_in_order_with_content_range
let server = mock_network::start(fast_local_profile());
let transport = MockPartTransport {
addr: server.addr,
- shared: Some(
+ shared: Some((
+ local_client(),
reqwest::Client::builder()
.no_proxy()
.resolve("www.googleapis.com", server.addr)
.build()
.unwrap(),
- ),
+ )),
drive_urls: true,
};
- let (result, progress) = run(
- &transport,
- &export,
- 1000,
- s3(),
- &AtomicBool::new(false),
- None,
- )
- .await;
+ let (result, progress) = run(&transport, &export, 1000, &AtomicBool::new(false), None).await;
let parts = result.unwrap();
assert_eq!(
parts
@@ -809,32 +639,24 @@ async fn drive_urls_without_a_drive_initiate_are_put_in_order_with_content_range
}
#[tokio::test]
-async fn s3_urls_are_put_concurrently_over_http_without_content_range() {
+async fn s3_urls_reuse_one_connection_per_client_one_part_at_a_time() {
let export = TempExport::new(&export_bytes(8000));
let server = mock_network::start(fast_local_profile());
let transport = MockPartTransport {
addr: server.addr,
- shared: Some(local_client()),
+ shared: Some((local_client(), local_client())),
drive_urls: false,
};
- let (result, _) = run(
- &transport,
- &export,
- 1000,
- s3(),
- &AtomicBool::new(false),
- None,
- )
- .await;
+ let (result, _) = run(&transport, &export, 1000, &AtomicBool::new(false), None).await;
assert_parts(&result.unwrap(), &[1000; 8]);
let puts = server.recorded.puts.lock().unwrap();
- assert_eq!(puts.len(), 8);
- assert!(puts.iter().all(|(_, range)| range.is_none()));
- let max_active = server.recorded.max_active_puts.load(Ordering::Acquire);
- assert!(
- (2..=MAX_CONCURRENT_PARTS).contains(&max_active),
- "{max_active}"
+ assert_eq!(
+ puts.iter().map(|(part, _)| *part).collect::<Vec<_>>(),
+ (1..=8).collect::<Vec<_>>()
);
+ assert!(puts.iter().all(|(_, range)| range.is_none()));
+ assert_eq!(server.recorded.max_active_puts.load(Ordering::Acquire), 1);
+ assert_eq!(server.connections.load(Ordering::Acquire), 2);
}
/// `cargo test --bin cap-gpui multipart_mock_network_benchmark -- --ignored --nocapture`
@@ -868,10 +690,8 @@ async fn multipart_mock_network_benchmark() {
"{megabytes} MB export, {part_count} parts of {} MB; window 2 MiB, TCP+TLS handshake 2 RTT, presign server 20 ms",
chunk_size / 1_000_000
);
- println!(
- "| RTT | link | serial, fresh client (before) | serial, shared client | 4 parts, shared client (after) | speedup |"
- );
- println!("|---|---|---|---|---|---|");
+ println!("| RTT | link | fresh clients (before) | shared clients (after) | speedup |");
+ println!("|---|---|---|---|---|");
for (rtt_ms, mbps) in [(50u64, 100.0f64), (150, 100.0), (50, 500.0), (150, 20.0)] {
let profile = mock_network::Profile {
rtt: Duration::from_millis(rtt_ms),
@@ -881,11 +701,11 @@ async fn multipart_mock_network_benchmark() {
presign_server_time: Duration::from_millis(20),
};
let mut times = Vec::new();
- for (concurrency, shared) in [(1, false), (1, true), (MAX_CONCURRENT_PARTS, true)] {
+ for shared in [false, true] {
let server = mock_network::start(profile);
let transport = MockPartTransport {
addr: server.addr,
- shared: shared.then(local_client),
+ shared: shared.then(|| (local_client(), local_client())),
drive_urls: false,
};
let progress = Mutex::new(Vec::new());
@@ -895,7 +715,6 @@ async fn multipart_mock_network_benchmark() {
&export.0,
file_size,
chunk_size,
- PartConcurrency::new(false, concurrency),
&|value| progress.lock().unwrap().push(value),
&AtomicBool::new(false),
None,
@@ -921,21 +740,21 @@ async fn multipart_mock_network_benchmark() {
.sum::<usize>() as u64,
file_size
);
+ assert_eq!(server.recorded.max_active_puts.load(Ordering::Acquire), 1);
let progress = progress.into_inner().unwrap();
assert!(progress.windows(2).all(|pair| pair[0] <= pair[1]));
assert_eq!(progress.last().copied(), Some(0.99));
eprintln!(
- "rtt {rtt_ms} ms, {mbps} Mbps, concurrency {concurrency}, shared {shared}: {elapsed:.1?}, {} connections",
+ "rtt {rtt_ms} ms, {mbps} Mbps, shared {shared}: {elapsed:.1?}, {} connections",
server.connections.load(Ordering::Acquire)
);
times.push(elapsed.as_secs_f64());
}
println!(
- "| {rtt_ms} ms | {mbps} Mbps | {:.1} s | {:.1} s | {:.1} s | {:.1}x |",
+ "| {rtt_ms} ms | {mbps} Mbps | {:.1} s | {:.1} s | {:.2}x |",
times[0],
times[1],
- times[2],
- times[0] / times[2]
+ times[0] / times[1]
);
}
}