Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Improve segment upload concurrency and URL prefetch
Richie McIlroyb3393cf6acfe
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex eaf30f877..ecfb33be7 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -656,6 +656,90 @@ struct SegmentUploadManifest {is_complete: bool,}+struct PresignedUrlCache {+ urls: tokio::sync::Mutex<HashMap<String, String>>,+}++impl PresignedUrlCache {+ fn new() -> Self {+ Self {+ urls: tokio::sync::Mutex::new(HashMap::new()),+ }+ }++ async fn prefetch(&self, app: &AppHandle, video_id: &str, segment_count: u32) {+ let mut subpaths = Vec::with_capacity((segment_count as usize) * 2 + 3);+ subpaths.push("segments/video/init.mp4".to_string());+ subpaths.push("segments/audio/init.mp4".to_string());+ subpaths.push("segments/manifest.json".to_string());+ for i in 1..=segment_count {+ subpaths.push(format!("segments/video/segment_{i:03}.m4s"));+ subpaths.push(format!("segments/audio/segment_{i:03}.m4s"));+ }++ match api::upload_signed_batch(app, video_id, &subpaths).await {+ Ok(urls) => {+ let mut cache = self.urls.lock().await;+ let count = urls.len();+ for (subpath, url) in urls {+ cache.insert(subpath, url);+ }+ info!(count, "Pre-fetched presigned URLs for segments");+ }+ Err(e) => {+ warn!("Failed to batch-prefetch presigned URLs: {e}");+ }+ }+ }++ async fn get_or_fetch(+ &self,+ app: &AppHandle,+ video_id: &str,+ subpath: &str,+ ) -> Result<String, AuthedApiError> {+ {+ let mut cache = self.urls.lock().await;+ if let Some(url) = cache.remove(subpath) {+ return Ok(url);+ }+ }++ api::upload_signed(+ app,+ api::PresignedS3PutRequest {+ video_id: video_id.to_string(),+ subpath: subpath.to_string(),+ method: api::PresignedS3PutRequestMethod::Put,+ meta: None,+ },+ )+ .await+ }++ async fn extend_prefetch(&self, app: &AppHandle, video_id: &str, from: u32, count: u32) {+ let mut subpaths = Vec::with_capacity((count as usize) * 2);+ for i in from..from + count {+ subpaths.push(format!("segments/video/segment_{i:03}.m4s"));+ subpaths.push(format!("segments/audio/segment_{i:03}.m4s"));+ }++ match api::upload_signed_batch(app, video_id, &subpaths).await {+ Ok(urls) => {+ let mut cache = self.urls.lock().await;+ let count = urls.len();+ for (subpath, url) in urls {+ cache.insert(subpath, url);+ }+ info!(count, from, "Extended presigned URL cache");+ }+ Err(e) => {+ warn!("Failed to extend presigned URL cache: {e}");+ }+ }+ }+}+impl SegmentUploader {pub fn spawn(app: AppHandle,@@ -700,14 +784,11 @@ impl SegmentUploader {}}- async fn upload_segment_file(- app: &AppHandle,- video_id: &str,- subpath: &str,+ async fn read_segment_data(file_path: &Path,+ subpath: &str,expected_size: u64,- ) -> Result<u64, AuthedApiError> {- const MAX_RETRIES: u32 = 3;+ ) -> Result<Bytes, AuthedApiError> {const FILE_WAIT_TIMEOUT: Duration = Duration::from_secs(10);const DATA_WAIT_TIMEOUT: Duration = Duration::from_secs(30);@@ -749,28 +830,34 @@ impl SegmentUploader {"Segment file still empty after {:?}, skipping upload",DATA_WAIT_TIMEOUT);- return Ok(0);+ return Ok(Bytes::new());}break data;}- tokio::time::sleep(Duration::from_millis(200)).await;+ tokio::time::sleep(Duration::from_millis(50)).await;};- let file_size = file_data.len();- let file_bytes = Bytes::from(file_data);+ Ok(Bytes::from(file_data))+ }++ async fn put_segment_to_s3(+ app: &AppHandle,+ video_id: &str,+ subpath: &str,+ file_bytes: Bytes,+ url_cache: &PresignedUrlCache,+ prefetched_url: Option<String>,+ ) -> Result<u64, AuthedApiError> {+ const MAX_RETRIES: u32 = 3;+ let file_size = file_bytes.len();+ let mut cached_url = prefetched_url;for attempt in 0..MAX_RETRIES {- let presigned_url = api::upload_signed(- app,- api::PresignedS3PutRequest {- video_id: video_id.to_string(),- subpath: subpath.to_string(),- method: api::PresignedS3PutRequestMethod::Put,- meta: None,- },- )- .await?;+ let presigned_url = match cached_url.take() {+ Some(url) => url,+ None => url_cache.get_or_fetch(app, video_id, subpath).await?,+ };let client = app.state::<RetryableHttpClient>()@@ -903,12 +990,64 @@ impl SegmentUploader {.ok();let state = Arc::new(Mutex::new(SegmentUploadState::new()));- let semaphore = Arc::new(tokio::sync::Semaphore::new(3));+ let semaphore = Arc::new(tokio::sync::Semaphore::new(6));+ let read_semaphore = Arc::new(tokio::sync::Semaphore::new(12));let consecutive_failures = Arc::new(std::sync::atomic::AtomicU32::new(0));let mut in_flight = futures::stream::FuturesUnordered::<tokio::task::JoinHandle<Result<(), AuthedApiError>>,>::new();+ let url_cache = Arc::new(PresignedUrlCache::new());+ {+ let cache = url_cache.clone();+ let app = app.clone();+ let vid = video_id.clone();+ tokio::spawn(async move {+ cache.prefetch(&app, &vid, 20).await;+ });+ }++ let manifest_dirty = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let manifest_shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let manifest_notify = Arc::new(tokio::sync::Notify::new());+ let manifest_handle = {+ let app = app.clone();+ let video_id = video_id.clone();+ let state = state.clone();+ let dirty = manifest_dirty.clone();+ let shutdown = manifest_shutdown.clone();+ let notify = manifest_notify.clone();+ tokio::spawn(async move {+ let mut interval = tokio::time::interval(Duration::from_secs(1));+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ tokio::select! {+ _ = interval.tick() => {}+ _ = notify.notified() => {}+ }+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ let manifest = state+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .to_manifest();+ if let Err(e) = Self::upload_manifest(&app, &video_id, &manifest).await {+ warn!("Periodic manifest upload failed: {e}");+ }+ }+ if shutdown.load(std::sync::atomic::Ordering::Acquire) {+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ let manifest = state+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .to_manifest();+ Self::upload_manifest(&app, &video_id, &manifest).await.ok();+ }+ break;+ }+ }+ })+ };+let (async_segment_tx, mut async_segment_rx) = tokio::sync::mpsc::unbounded_channel::<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent,>();@@ -920,7 +1059,7 @@ impl SegmentUploader {.name("segment-rx-bridge".to_string()).spawn(move || {loop {- match segment_rx.recv_timeout(std::time::Duration::from_millis(100)) {+ match segment_rx.recv_timeout(std::time::Duration::from_millis(20)) {Ok(event) => {if async_segment_tx.send(event).is_err() {break;@@ -984,11 +1123,11 @@ impl SegmentUploader {let video_id_clone = video_id.clone();let state_clone = state.clone();let failures_clone = consecutive_failures.clone();- let permit = semaphore- .clone()- .acquire_owned()- .await- .map_err(|e| format!("segment_upload/semaphore: {e}"))?;+ let semaphore_clone = semaphore.clone();+ let read_semaphore_clone = read_semaphore.clone();+ let url_cache_clone = url_cache.clone();+ let manifest_dirty_clone = manifest_dirty.clone();+ let manifest_notify_clone = manifest_notify.clone();let file_path = event.path.clone();let is_init = event.is_init;@@ -999,22 +1138,86 @@ impl SegmentUploader {let subpath_for_fail = subpath.clone();let handle = tokio::spawn(async move {- let _permit = permit;+ let _read_permit = read_semaphore_clone+ .acquire()+ .await+ .map_err(|e| format!("segment_upload/read_semaphore: {e}"))?;++ let (file_result, url_result) = tokio::join!(+ Self::read_segment_data(&file_path, &subpath, expected_size),+ url_cache_clone.get_or_fetch(+ &app_clone,+ &video_id_clone,+ &subpath+ ),+ );- let result =- Self::upload_segment_file(&app_clone, &video_id_clone, &subpath, &file_path, expected_size)- .await;+ let file_data = match file_result {+ Ok(data) if data.is_empty() => return Ok(()),+ Ok(data) => data,+ Err(e) => {+ let prev = failures_clone+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ warn!(+ subpath,+ error = %e,+ consecutive_failures = prev + 1,+ "Failed to read segment, queued for retry"+ );+ let mut s =+ state_clone.lock().unwrap_or_else(|e| e.into_inner());+ s.failed_segments.push(FailedSegmentInfo {+ subpath: subpath_for_fail,+ file_path,+ is_init,+ media_type,+ index,+ duration,+ expected_size,+ });+ return Ok(());+ }+ };++ let prefetched_url = match url_result {+ Ok(url) => Some(url),+ Err(e) => {+ warn!(subpath, error = %e, "Pre-fetch URL failed, will fetch on demand");+ None+ }+ };++ drop(_read_permit);++ let permit = semaphore_clone+ .acquire_owned()+ .await+ .map_err(|e| format!("segment_upload/semaphore: {e}"))?;++ let result = Self::put_segment_to_s3(+ &app_clone,+ &video_id_clone,+ &subpath,+ file_data,+ &url_cache_clone,+ prefetched_url,+ )+ .await;++ drop(permit);match result {Err(e) => {- let prev = failures_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let prev = failures_clone+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);warn!(subpath,error = %e,consecutive_failures = prev + 1,"Failed to upload segment, queued for retry");- let mut s = state_clone.lock().unwrap_or_else(|e| e.into_inner());+ let mut s =+ state_clone.lock().unwrap_or_else(|e| e.into_inner());s.failed_segments.push(FailedSegmentInfo {subpath: subpath_for_fail,file_path,@@ -1024,46 +1227,60 @@ impl SegmentUploader {duration,expected_size,});- return Ok(());}Ok(bytes) => {- failures_clone.store(0, std::sync::atomic::Ordering::Relaxed);- let mut s = state_clone.lock().unwrap_or_else(|e| e.into_inner());+ failures_clone+ .store(0, std::sync::atomic::Ordering::Relaxed);+ let mut s =+ state_clone.lock().unwrap_or_else(|e| e.into_inner());s.total_bytes_uploaded += bytes;if is_init {match media_type {- SegmentMediaType::Video => s.video_init_uploaded = true,- SegmentMediaType::Audio => s.audio_init_uploaded = true,+ SegmentMediaType::Video => {+ s.video_init_uploaded = true+ }+ SegmentMediaType::Audio => {+ s.audio_init_uploaded = true+ }}} else {match media_type {SegmentMediaType::Video => {- s.uploaded_video_segments.insert(index, duration);+ s.uploaded_video_segments+ .insert(index, duration);}SegmentMediaType::Audio => {- s.uploaded_audio_segments.insert(index, duration);+ s.uploaded_audio_segments+ .insert(index, duration);}}}+ manifest_dirty_clone+ .store(true, std::sync::atomic::Ordering::Release);+ manifest_notify_clone.notify_one();+ info!(subpath, "Segment uploaded successfully");}}- let manifest = state_clone- .lock()- .unwrap_or_else(|e| e.into_inner())- .to_manifest();- if let Err(e) = Self::upload_manifest(&app_clone, &video_id_clone, &manifest).await- {- warn!("Failed to upload manifest after segment: {e}");- }-- info!(subpath, "Segment uploaded successfully");-Ok(())});in_flight.push(handle);+ if !event.is_init+ && event.media_type == SegmentMediaType::Video+ && event.index > 0+ && event.index % 15 == 0+ {+ let cache = url_cache.clone();+ let app_ref = app.clone();+ let vid_ref = video_id.clone();+ let from = event.index + 1;+ tokio::spawn(async move {+ cache.extend_prefetch(&app_ref, &vid_ref, from, 20).await;+ });+ }+if consecutive_failures.load(std::sync::atomic::Ordering::Relaxed) >= CONSECUTIVE_FAILURE_LIMIT {warn!("Consecutive upload failures reached threshold, attempting network recovery");if !wait_for_network_recovery(&app, &video_id).await {@@ -1083,6 +1300,11 @@ impl SegmentUploader {let _ = bridge_handle.join();+ manifest_shutdown.store(true, std::sync::atomic::Ordering::Release);+ manifest_dirty.store(true, std::sync::atomic::Ordering::Release);+ manifest_notify.notify_one();+ manifest_handle.await.ok();+let failed = {let s = state.lock().unwrap_or_else(|e| e.into_inner());s.failed_segments.clone()@@ -1094,12 +1316,29 @@ impl SegmentUploader {"Retrying failed segment uploads before completing");for seg in failed {- match Self::upload_segment_file(+ let file_data =+ Self::read_segment_data(&seg.file_path, &seg.subpath, seg.expected_size).await;++ let file_data = match file_data {+ Ok(data) if data.is_empty() => continue,+ Ok(data) => data,+ Err(e) => {+ warn!(+ subpath = seg.subpath,+ error = %e,+ "Failed segment retry read failed, segment will be missing"+ );+ continue;+ }+ };++ match Self::put_segment_to_s3(&app,&video_id,&seg.subpath,- &seg.file_path,- seg.expected_size,+ file_data,+ &url_cache,+ None,).await{@@ -2048,3 +2287,591 @@ fn tauri_channel_progress<T: UploadedChunk, E>(}}}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;+ use std::sync::atomic::{AtomicU32, Ordering};++ #[tokio::test]+ async fn read_segment_data_returns_existing_file() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_001.m4s");+ std::fs::write(&path, b"fake segment data 12345").unwrap();++ let result =+ SegmentUploader::read_segment_data(&path, "segments/video/segment_001.m4s", 0).await;++ let data = result.unwrap();+ assert_eq!(data.as_ref(), b"fake segment data 12345");+ }++ #[tokio::test]+ async fn read_segment_data_waits_for_file_to_appear() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_002.m4s");++ let path_clone = path.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(200)).await;+ std::fs::write(&path_clone, b"delayed segment data").unwrap();+ });++ let start = Instant::now();+ let result =+ SegmentUploader::read_segment_data(&path, "segments/video/segment_002.m4s", 0).await;+ let elapsed = start.elapsed();++ let data = result.unwrap();+ assert_eq!(data.as_ref(), b"delayed segment data");+ assert!(+ elapsed >= Duration::from_millis(150),+ "should have waited for file: {elapsed:?}"+ );+ assert!(+ elapsed < Duration::from_secs(2),+ "should not have waited too long: {elapsed:?}"+ );+ }++ #[tokio::test]+ async fn read_segment_data_waits_for_expected_size() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_003.m4s");++ let mut file = std::fs::File::create(&path).unwrap();+ file.write_all(b"sm").unwrap();+ file.flush().unwrap();+ drop(file);++ let path_clone = path.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(200)).await;+ std::fs::write(&path_clone, b"full segment data here!").unwrap();+ });++ let result =+ SegmentUploader::read_segment_data(&path, "segments/video/segment_003.m4s", 20).await;++ let data = result.unwrap();+ assert!(data.len() >= 20);+ }++ #[tokio::test]+ async fn read_segment_data_returns_empty_bytes_for_empty_file_after_timeout() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_empty.m4s");+ std::fs::write(&path, b"").unwrap();++ let result = tokio::time::timeout(+ Duration::from_secs(35),+ SegmentUploader::read_segment_data(&path, "segments/video/segment_empty.m4s", 0),+ )+ .await+ .unwrap();++ let data = result.unwrap();+ assert!(data.is_empty());+ }++ #[tokio::test]+ async fn read_segment_data_polls_at_50ms_not_200ms() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_fast.m4s");++ let path_clone = path.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(120)).await;+ std::fs::write(&path_clone, b"fast poll data").unwrap();+ });++ let start = Instant::now();+ let result =+ SegmentUploader::read_segment_data(&path, "segments/video/segment_fast.m4s", 0).await;+ let elapsed = start.elapsed();++ assert!(result.is_ok());+ assert!(+ elapsed < Duration::from_millis(300),+ "50ms polling should detect file within ~170ms, got {elapsed:?}"+ );+ }++ #[tokio::test]+ async fn url_cache_returns_prefetched_url() {+ let cache = PresignedUrlCache::new();+ {+ let mut urls = cache.urls.lock().await;+ urls.insert(+ "segments/video/segment_001.m4s".to_string(),+ "https://s3.example.com/presigned/seg1".to_string(),+ );+ urls.insert(+ "segments/video/segment_002.m4s".to_string(),+ "https://s3.example.com/presigned/seg2".to_string(),+ );+ }++ let mut urls = cache.urls.lock().await;+ let url1 = urls.remove("segments/video/segment_001.m4s");+ let url2 = urls.remove("segments/video/segment_002.m4s");+ let url3 = urls.remove("segments/video/segment_003.m4s");+ drop(urls);++ assert_eq!(+ url1.as_deref(),+ Some("https://s3.example.com/presigned/seg1")+ );+ assert_eq!(+ url2.as_deref(),+ Some("https://s3.example.com/presigned/seg2")+ );+ assert!(url3.is_none(), "uncached key should return None");+ }++ #[tokio::test]+ async fn url_cache_consumes_entry_on_use() {+ let cache = PresignedUrlCache::new();+ {+ let mut urls = cache.urls.lock().await;+ urls.insert(+ "segments/video/init.mp4".to_string(),+ "https://s3.example.com/presigned/init".to_string(),+ );+ }++ let mut urls = cache.urls.lock().await;+ let first = urls.remove("segments/video/init.mp4");+ let second = urls.remove("segments/video/init.mp4");+ drop(urls);++ assert!(first.is_some(), "first access should hit cache");+ assert!(second.is_none(), "second access should miss (consumed)");+ }++ #[tokio::test]+ async fn semaphore_allows_six_concurrent_uploads() {+ let semaphore = Arc::new(tokio::sync::Semaphore::new(6));+ let active = Arc::new(AtomicU32::new(0));+ let peak = Arc::new(AtomicU32::new(0));+ let completed = Arc::new(AtomicU32::new(0));++ let mut handles = Vec::new();+ for _ in 0..12 {+ let sem = semaphore.clone();+ let active = active.clone();+ let peak = peak.clone();+ let completed = completed.clone();+ handles.push(tokio::spawn(async move {+ let _permit = sem.acquire().await.unwrap();+ let current = active.fetch_add(1, Ordering::SeqCst) + 1;+ peak.fetch_max(current, Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(50)).await;+ active.fetch_sub(1, Ordering::SeqCst);+ completed.fetch_add(1, Ordering::SeqCst);+ }));+ }++ for h in handles {+ h.await.unwrap();+ }++ assert_eq!(completed.load(Ordering::SeqCst), 12);+ assert_eq!(+ peak.load(Ordering::SeqCst),+ 6,+ "peak concurrency should be 6"+ );+ }++ #[tokio::test]+ async fn file_read_runs_outside_semaphore() {+ let semaphore = Arc::new(tokio::sync::Semaphore::new(2));+ let dir = tempfile::tempdir().unwrap();++ let read_start_times = Arc::new(tokio::sync::Mutex::new(Vec::<Instant>::new()));+ let overall_start = Instant::now();++ let mut handles = Vec::new();+ for i in 0..6u32 {+ let path = dir.path().join(format!("seg_{i:03}.m4s"));+ std::fs::write(&path, format!("data for segment {i}")).unwrap();++ let sem = semaphore.clone();+ let times = read_start_times.clone();+ handles.push(tokio::spawn(async move {+ {+ let mut t = times.lock().await;+ t.push(Instant::now());+ }+ let _data = tokio::fs::read(&path).await.unwrap();++ let _permit = sem.acquire().await.unwrap();+ tokio::time::sleep(Duration::from_millis(100)).await;+ }));+ }++ for h in handles {+ h.await.unwrap();+ }++ let times = read_start_times.lock().await;+ let max_read_delay = times+ .iter()+ .map(|t| t.duration_since(overall_start))+ .max()+ .unwrap();++ assert!(+ max_read_delay < Duration::from_millis(50),+ "all file reads should start nearly immediately (not blocked by semaphore), max delay was {max_read_delay:?}"+ );+ }++ #[tokio::test]+ async fn manifest_debounce_reduces_upload_count() {+ let dirty = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let notify = Arc::new(tokio::sync::Notify::new());+ let upload_count = Arc::new(AtomicU32::new(0));++ let manifest_handle = {+ let dirty = dirty.clone();+ let shutdown = shutdown.clone();+ let notify = notify.clone();+ let upload_count = upload_count.clone();+ tokio::spawn(async move {+ let mut interval = tokio::time::interval(Duration::from_millis(100));+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ tokio::select! {+ _ = interval.tick() => {}+ _ = notify.notified() => {}+ }+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ upload_count.fetch_add(1, Ordering::SeqCst);+ }+ if shutdown.load(std::sync::atomic::Ordering::Acquire) {+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ upload_count.fetch_add(1, Ordering::SeqCst);+ }+ break;+ }+ }+ })+ };++ for _ in 0..20 {+ dirty.store(true, std::sync::atomic::Ordering::Release);+ tokio::time::sleep(Duration::from_millis(10)).await;+ }++ tokio::time::sleep(Duration::from_millis(200)).await;++ shutdown.store(true, std::sync::atomic::Ordering::Release);+ dirty.store(true, std::sync::atomic::Ordering::Release);+ notify.notify_one();+ manifest_handle.await.unwrap();++ let count = upload_count.load(Ordering::SeqCst);+ assert!(+ count < 10,+ "debounce should batch 20 dirty flags into far fewer uploads, got {count}"+ );+ assert!(+ count >= 1,+ "should have uploaded manifest at least once, got {count}"+ );+ }++ #[tokio::test]+ async fn manifest_notify_wakes_immediately_on_shutdown() {+ let dirty = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let notify = Arc::new(tokio::sync::Notify::new());+ let upload_count = Arc::new(AtomicU32::new(0));++ let manifest_handle = {+ let dirty = dirty.clone();+ let shutdown = shutdown.clone();+ let notify = notify.clone();+ let upload_count = upload_count.clone();+ tokio::spawn(async move {+ let mut interval = tokio::time::interval(Duration::from_secs(60));+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ tokio::select! {+ _ = interval.tick() => {}+ _ = notify.notified() => {}+ }+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ upload_count.fetch_add(1, Ordering::SeqCst);+ }+ if shutdown.load(std::sync::atomic::Ordering::Acquire) {+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ upload_count.fetch_add(1, Ordering::SeqCst);+ }+ break;+ }+ }+ })+ };++ tokio::time::sleep(Duration::from_millis(50)).await;++ let start = Instant::now();+ shutdown.store(true, std::sync::atomic::Ordering::Release);+ dirty.store(true, std::sync::atomic::Ordering::Release);+ notify.notify_one();+ manifest_handle.await.unwrap();+ let elapsed = start.elapsed();++ assert!(+ elapsed < Duration::from_millis(100),+ "notify should wake task immediately, not wait for interval. took {elapsed:?}"+ );+ assert_eq!(upload_count.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn parallel_file_read_and_url_fetch() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("segment_001.m4s");+ std::fs::write(&path, vec![0u8; 4096]).unwrap();++ let start = Instant::now();+ let (file_result, url_result) = tokio::join!(+ async {+ tokio::time::sleep(Duration::from_millis(100)).await;+ tokio::fs::read(&path).await+ },+ async {+ tokio::time::sleep(Duration::from_millis(100)).await;+ Ok::<String, String>("https://s3.example.com/presigned".to_string())+ },+ );+ let elapsed = start.elapsed();++ assert!(file_result.is_ok());+ assert!(url_result.is_ok());+ assert!(+ elapsed < Duration::from_millis(180),+ "parallel operations (100ms each) should complete in ~100ms, not ~200ms. took {elapsed:?}"+ );+ }++ #[tokio::test]+ async fn new_architecture_faster_than_old() {+ let segment_count = 12u32;++ let old_start = Instant::now();+ {+ let semaphore = Arc::new(tokio::sync::Semaphore::new(3));+ let completed = Arc::new(AtomicU32::new(0));+ let mut in_flight = futures::stream::FuturesUnordered::new();++ for _ in 0..segment_count {+ let permit = semaphore.clone().acquire_owned().await.unwrap();+ let completed = completed.clone();+ in_flight.push(tokio::spawn(async move {+ let _permit = permit;+ tokio::time::sleep(Duration::from_millis(10)).await;+ tokio::time::sleep(Duration::from_millis(50)).await;+ tokio::time::sleep(Duration::from_millis(30)).await;+ completed.fetch_add(1, Ordering::SeqCst);+ }));+ }++ use futures::StreamExt;+ while let Some(_) = in_flight.next().await {}+ }+ let old_duration = old_start.elapsed();++ let new_start = Instant::now();+ {+ let semaphore = Arc::new(tokio::sync::Semaphore::new(6));+ let completed = Arc::new(AtomicU32::new(0));+ let manifest_uploads = Arc::new(AtomicU32::new(0));+ let mut in_flight = futures::stream::FuturesUnordered::new();++ for _ in 0..segment_count {+ let semaphore = semaphore.clone();+ let completed = completed.clone();+ let manifest_uploads = manifest_uploads.clone();+ in_flight.push(tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(10)).await;++ let _permit = semaphore.acquire_owned().await.unwrap();+ tokio::time::sleep(Duration::from_millis(50)).await;+ drop(_permit);++ completed.fetch_add(1, Ordering::SeqCst);+ let _ = &manifest_uploads;+ }));+ }++ use futures::StreamExt;+ while let Some(_) = in_flight.next().await {}+ }+ let new_duration = new_start.elapsed();++ assert!(+ new_duration < old_duration,+ "new architecture ({new_duration:?}) should be faster than old ({old_duration:?})"+ );++ let speedup =+ old_duration.as_secs_f64() / new_duration.as_secs_f64().max(f64::MIN_POSITIVE);+ assert!(+ speedup > 1.5,+ "expected at least 1.5x speedup, got {speedup:.2}x (old={old_duration:?}, new={new_duration:?})"+ );+ }++ #[tokio::test]+ async fn upload_state_manifest_generation() {+ let state = SegmentUploadState::new();+ let manifest = state.to_manifest();+ assert!(!manifest.is_complete);+ assert!(!manifest.video_init_uploaded);+ assert!(!manifest.audio_init_uploaded);+ assert!(manifest.video_segments.is_empty());+ assert!(manifest.audio_segments.is_empty());+ }++ #[tokio::test]+ async fn upload_state_tracks_segments() {+ let mut state = SegmentUploadState::new();+ state.video_init_uploaded = true;+ state.audio_init_uploaded = true;+ state.uploaded_video_segments.insert(1, 3.0);+ state.uploaded_video_segments.insert(2, 3.0);+ state.uploaded_audio_segments.insert(1, 3.0);++ let manifest = state.to_manifest();+ assert!(manifest.video_init_uploaded);+ assert!(manifest.audio_init_uploaded);+ assert_eq!(manifest.video_segments.len(), 2);+ assert_eq!(manifest.audio_segments.len(), 1);+ assert!(!manifest.is_complete);++ let complete = state.to_complete_manifest();+ assert!(complete.is_complete);+ assert_eq!(complete.video_segments.len(), 2);+ }++ #[tokio::test]+ async fn end_to_end_pipeline_simulation() {+ let segment_count = 10u32;+ let semaphore = Arc::new(tokio::sync::Semaphore::new(6));+ let state = Arc::new(Mutex::new(SegmentUploadState::new()));+ let manifest_dirty = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let manifest_shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let manifest_notify = Arc::new(tokio::sync::Notify::new());+ let manifest_upload_count = Arc::new(AtomicU32::new(0));++ let manifest_handle = {+ let dirty = manifest_dirty.clone();+ let shutdown = manifest_shutdown.clone();+ let notify = manifest_notify.clone();+ let count = manifest_upload_count.clone();+ tokio::spawn(async move {+ let mut interval = tokio::time::interval(Duration::from_millis(100));+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ tokio::select! {+ _ = interval.tick() => {}+ _ = notify.notified() => {}+ }+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ tokio::time::sleep(Duration::from_millis(20)).await;+ count.fetch_add(1, Ordering::SeqCst);+ }+ if shutdown.load(std::sync::atomic::Ordering::Acquire) {+ if dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {+ count.fetch_add(1, Ordering::SeqCst);+ }+ break;+ }+ }+ })+ };++ let dir = tempfile::tempdir().unwrap();+ let start = Instant::now();+ let mut handles = Vec::new();++ for i in 0..segment_count {+ let path = dir.path().join(format!("segment_{i:03}.m4s"));+ std::fs::write(&path, vec![0u8; 1024]).unwrap();++ let sem = semaphore.clone();+ let st = state.clone();+ let dirty = manifest_dirty.clone();+ let mn = manifest_notify.clone();+ handles.push(tokio::spawn(async move {+ let (_data, _url) = tokio::join!(tokio::fs::read(&path), async {+ Ok::<_, ()>("https://example.com/presigned")+ },);++ let _permit = sem.acquire_owned().await.unwrap();+ tokio::time::sleep(Duration::from_millis(50)).await;+ drop(_permit);++ {+ let mut s = st.lock().unwrap_or_else(|e| e.into_inner());+ s.uploaded_video_segments.insert(i, 3.0);+ s.total_bytes_uploaded += 1024;+ }+ dirty.store(true, std::sync::atomic::Ordering::Release);+ mn.notify_one();+ }));+ }++ for h in handles {+ h.await.unwrap();+ }++ let upload_duration = start.elapsed();++ let shutdown_start = Instant::now();+ manifest_shutdown.store(true, std::sync::atomic::Ordering::Release);+ manifest_dirty.store(true, std::sync::atomic::Ordering::Release);+ manifest_notify.notify_one();+ manifest_handle.await.unwrap();+ let shutdown_duration = shutdown_start.elapsed();++ let manifest_count = manifest_upload_count.load(Ordering::SeqCst);+ let final_state = state.lock().unwrap();++ assert_eq!(+ final_state.uploaded_video_segments.len(),+ segment_count as usize,+ "all segments should be tracked"+ );+ assert_eq!(+ final_state.total_bytes_uploaded,+ segment_count as u64 * 1024+ );+ assert!(+ manifest_count < segment_count,+ "manifest uploads ({manifest_count}) should be fewer than segment count ({segment_count})"+ );+ assert!(+ manifest_count >= 1,+ "at least one manifest upload should happen"+ );++ let per_segment_ms = upload_duration.as_millis() as f64 / segment_count as f64;+ assert!(+ per_segment_ms < 40.0,+ "with concurrency 6, per-segment time should be well under 50ms, got {per_segment_ms:.1}ms"+ );++ assert!(+ shutdown_duration < Duration::from_millis(200),+ "manifest shutdown should be near-instant via Notify, took {shutdown_duration:?}"+ );+ }+}