-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathupload.rs
More file actions
3025 lines (2675 loc) · 110 KB
/
Copy pathupload.rs
File metadata and controls
3025 lines (2675 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// credit @filleduchaos
use crate::{
UploadProgress, VideoUploadInfo,
api::{self, PresignedS3PutRequest, PresignedS3PutRequestMethod, S3VideoMeta, UploadedPart},
http_client::{HttpClient, RetryableHttpClient},
posthog::{PostHogEvent, async_capture_event},
web_api::{AuthedApiError, ManagerExt},
};
use async_stream::{stream, try_stream};
use bytes::Bytes;
use cap_project::{RecordingMeta, S3UploadMeta, UploadMeta};
use cap_utils::spawn_actor;
use ffmpeg::ffi::AV_TIME_BASE;
use flume::Receiver;
use futures::future::join;
use futures::{Stream, StreamExt, TryStreamExt, stream};
use image::{ImageReader, codecs::jpeg::JpegEncoder};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::{
collections::HashMap,
io,
path::{Path, PathBuf},
pin::pin,
sync::{Arc, Mutex, PoisonError},
time::Duration,
};
use tauri::{AppHandle, Manager, ipc::Channel};
use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_specta::Event;
use tokio::{
fs::File,
io::{AsyncReadExt, AsyncSeekExt, BufReader},
task::{self, JoinHandle},
time::{self, Instant, timeout},
};
use tokio_util::io::ReaderStream;
use tracing::{Span, debug, error, info, info_span, instrument, trace, warn};
use tracing_futures::Instrument;
pub struct UploadedItem {
pub link: String,
pub id: String,
// #[allow(unused)]
// pub config: S3UploadMeta,
}
#[derive(Clone, Serialize, Type, tauri_specta::Event)]
pub struct UploadProgressEvent {
video_id: String,
uploaded: String,
total: String,
}
const MIN_CHUNK_SIZE: u64 = 5 * 1024 * 1024;
const MAX_CHUNK_SIZE: u64 = 15 * 1024 * 1024;
const NETWORK_RECOVERY_TIMEOUT: Duration = Duration::from_secs(5 * 60);
const CONNECTIVITY_PROBE_INITIAL_DELAY: Duration = Duration::from_secs(2);
const CONNECTIVITY_PROBE_MAX_DELAY: Duration = Duration::from_secs(30);
fn is_google_drive_resumable_url(url: &str) -> bool {
let Ok(url) = reqwest::Url::parse(url) else {
return false;
};
url.host_str().is_some_and(|host| {
(host == "googleapis.com" || host.ends_with(".googleapis.com"))
&& url.path().starts_with("/upload/drive/")
})
}
fn is_google_drive_upload(provider: Option<&str>, upload_id: &str) -> bool {
provider == Some("googleDrive") || is_google_drive_resumable_url(upload_id)
}
fn with_drive_content_range(
request: reqwest::RequestBuilder,
url: &str,
offset: u64,
size: u64,
total_size: u64,
) -> reqwest::RequestBuilder {
if !is_google_drive_resumable_url(url) || size == 0 {
return request;
}
let end = offset.saturating_add(size).saturating_sub(1);
request.header(
"Content-Range",
format!("bytes {offset}-{end}/{total_size}"),
)
}
fn is_upload_response_accepted(
url: &str,
status: StatusCode,
offset: u64,
size: u64,
total_size: u64,
) -> bool {
status.is_success()
|| (is_google_drive_resumable_url(url)
&& status == StatusCode::PERMANENT_REDIRECT
&& offset.saturating_add(size) < total_size)
}
#[instrument(skip(app, channel, file_path, screenshot_path))]
pub async fn upload_video(
app: &AppHandle,
video_id: String,
file_path: PathBuf,
screenshot_path: PathBuf,
meta: S3VideoMeta,
channel: Option<Channel<UploadProgress>>,
) -> Result<UploadedItem, AuthedApiError> {
info!("Uploading video {video_id}...");
let start = Instant::now();
let upload = api::upload_multipart_initiate(app, &video_id).await?;
let is_drive_upload = is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id);
let upload_id = upload.upload_id;
let video_fut = async {
let failed_chunks: Arc<Mutex<Vec<FailedChunkInfo>>> = Arc::new(Mutex::new(Vec::new()));
let stream = progress(
app.clone(),
video_id.clone(),
multipart_uploader(
app.clone(),
video_id.clone(),
upload_id.clone(),
is_drive_upload,
from_pending_file_to_chunks(file_path.clone(), None),
failed_chunks.clone(),
),
);
let stream = if let Some(channel) = channel {
tauri_channel_progress(channel, stream).boxed()
} else {
stream.boxed()
};
let mut parts = stream.try_collect::<Vec<_>>().await?;
let failed =
std::mem::take(&mut *failed_chunks.lock().unwrap_or_else(PoisonError::into_inner));
if !failed.is_empty() {
info!(
count = failed.len(),
"Retrying {} failed chunk(s) after main upload pass",
failed.len()
);
let retry_parts =
retry_failed_chunks(app, &video_id, &upload_id, &file_path, failed).await?;
parts.extend(retry_parts);
}
let mut deduplicated_parts = HashMap::new();
for part in parts {
deduplicated_parts.insert(part.part_number, part);
}
parts = deduplicated_parts.into_values().collect::<Vec<_>>();
parts.sort_by_key(|part| part.part_number);
let metadata = build_video_meta(&file_path)
.map_err(|e| error!("Failed to get video metadata: {e}"))
.ok();
api::upload_multipart_complete(app, &video_id, &upload_id, &parts, metadata.clone())
.await?;
Ok(metadata)
};
// TODO: We don't report progress on image upload
let bytes = compress_image(screenshot_path).await?;
let thumbnail_fut = singlepart_uploader(
app.clone(),
PresignedS3PutRequest {
video_id: video_id.clone(),
subpath: "screenshot/screen-capture.jpg".to_string(),
method: PresignedS3PutRequestMethod::Put,
meta: None,
},
bytes.len() as u64,
stream::once(async move { Ok::<_, std::io::Error>(bytes::Bytes::from(bytes)) }),
);
let (video_result, thumbnail_result): (Result<_, AuthedApiError>, Result<_, AuthedApiError>) =
tokio::join!(video_fut, thumbnail_fut);
emit_upload_complete(app, &video_id);
async_capture_event(
app,
match &video_result {
Ok(meta) => PostHogEvent::MultipartUploadComplete {
duration: start.elapsed(),
length: meta
.as_ref()
.map(|v| Duration::from_secs(v.duration_in_secs as u64))
.unwrap_or_default(),
size: std::fs::metadata(file_path)
.map(|m| ((m.len() as f64) / 1_000_000.0) as u64)
.unwrap_or_default(),
},
Err(err) => PostHogEvent::MultipartUploadFailed {
duration: start.elapsed(),
error: err.to_string(),
},
},
);
let _ = (video_result?, thumbnail_result?);
Ok(UploadedItem {
link: app.make_app_url(format!("/s/{video_id}")).await,
id: video_id,
})
}
/// Open a file and construct a stream to it.
async fn file_reader_stream(path: impl AsRef<Path>) -> Result<(ReaderStream<File>, u64), String> {
let file = File::open(path)
.await
.map_err(|e| format!("Failed to open file: {e}"))?;
let metadata = file
.metadata()
.await
.map_err(|e| format!("Failed to get file metadata: {e}"))?;
Ok((ReaderStream::new(file), metadata.len()))
}
#[instrument(skip(app))]
pub async fn upload_image(
app: &AppHandle,
file_path: PathBuf,
) -> Result<UploadedItem, AuthedApiError> {
let file_name = file_path
.file_name()
.and_then(|name| name.to_str())
.ok_or("Invalid file path")?
.to_string();
let s3_config = create_or_get_video(app, true, None, None, None, None).await?;
let (stream, total_size) = file_reader_stream(file_path).await?;
singlepart_uploader(
app.clone(),
PresignedS3PutRequest {
video_id: s3_config.id.clone(),
subpath: file_name,
method: PresignedS3PutRequestMethod::Put,
meta: None,
},
total_size,
stream,
)
.await?;
Ok(UploadedItem {
link: app.make_app_url(format!("/s/{}", &s3_config.id)).await,
id: s3_config.id,
})
}
#[instrument(skip(app))]
pub async fn create_or_get_video(
app: &AppHandle,
is_screenshot: bool,
video_id: Option<String>,
name: Option<String>,
meta: Option<S3VideoMeta>,
organization_id: Option<String>,
) -> Result<S3UploadMeta, AuthedApiError> {
create_or_get_video_with_mode(
app,
is_screenshot,
video_id,
name,
meta,
organization_id,
"desktopMP4",
)
.await
}
#[instrument(skip(app))]
pub async fn create_or_get_video_with_mode(
app: &AppHandle,
is_screenshot: bool,
video_id: Option<String>,
name: Option<String>,
meta: Option<S3VideoMeta>,
organization_id: Option<String>,
recording_mode: &str,
) -> Result<S3UploadMeta, AuthedApiError> {
let mut s3_config_url = if let Some(id) = video_id {
format!("/api/desktop/video/create?recordingMode={recording_mode}&videoId={id}")
} else if is_screenshot {
format!("/api/desktop/video/create?recordingMode={recording_mode}&isScreenshot=true")
} else {
format!("/api/desktop/video/create?recordingMode={recording_mode}")
};
if let Some(name) = name {
s3_config_url.push_str(&format!("&name={name}"));
}
if let Some(meta) = meta {
s3_config_url.push_str(&format!("&durationInSecs={}", meta.duration_in_secs));
s3_config_url.push_str(&format!("&width={}", meta.width));
s3_config_url.push_str(&format!("&height={}", meta.height));
if let Some(fps) = meta.fps {
s3_config_url.push_str(&format!("&fps={fps}"));
}
}
if let Some(org_id) = organization_id {
s3_config_url.push_str(&format!("&orgId={org_id}"));
}
let response = app
.authed_api_request(s3_config_url, |client, url| client.get(url))
.await?;
if response.status() != StatusCode::OK {
#[derive(Deserialize, Clone, Debug)]
pub struct CreateErrorResponse {
error: String,
}
let status = response.status();
let body = response.text().await;
if let Some(error) = body
.as_ref()
.ok()
.and_then(|body| serde_json::from_str::<CreateErrorResponse>(body).ok())
&& status == StatusCode::FORBIDDEN
&& error.error == "upgrade_required"
{
return Err(AuthedApiError::UpgradeRequired);
}
return Err(format!("create_or_get_video/error/{status}: {body:?}").into());
}
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response body: {e}"))?;
let config = serde_json::from_str::<S3UploadMeta>(&response_text).map_err(|e| {
format!("Failed to deserialize response: {e}. Response body: {response_text}")
})?;
Ok(config)
}
#[instrument]
pub fn build_video_meta(path: &PathBuf) -> Result<S3VideoMeta, String> {
let input =
ffmpeg::format::input(path).map_err(|e| format!("Failed to read input file: {e}"))?;
let video_stream = input
.streams()
.best(ffmpeg::media::Type::Video)
.ok_or_else(|| "Failed to find appropriate video stream in file".to_string())?;
let video_codec = ffmpeg::codec::context::Context::from_parameters(video_stream.parameters())
.map_err(|e| format!("Unable to read video codec information: {e}"))?;
let video = video_codec
.decoder()
.video()
.map_err(|e| format!("Unable to get video decoder: {e}"))?;
Ok(S3VideoMeta {
duration_in_secs: input.duration() as f64 / AV_TIME_BASE as f64,
width: video.width(),
height: video.height(),
fps: video
.frame_rate()
.map(|v| v.numerator() as f32 / v.denominator() as f32),
})
}
pub fn try_repair_corrupt_mp4(path: &Path) -> Result<(), String> {
let repaired_path = path.with_extension("repaired.mp4");
info!(
original = %path.display(),
repaired = %repaired_path.display(),
"Attempting to repair corrupt MP4 via FFmpeg remux"
);
cap_enc_ffmpeg::remux::remux_file(path, &repaired_path)
.map_err(|e| format!("FFmpeg remux repair failed for {}: {e}", path.display()))?;
let repaired_size = std::fs::metadata(&repaired_path)
.map(|m| m.len())
.unwrap_or(0);
if repaired_size == 0 {
let _ = std::fs::remove_file(&repaired_path);
return Err("Repaired file is empty — no recoverable data".to_string());
}
std::fs::rename(&repaired_path, path).map_err(|e| {
let _ = std::fs::remove_file(&repaired_path);
format!("Failed to replace original file with repaired version: {e}")
})?;
info!(
repaired_size_mb = repaired_size as f64 / 1_000_000.0,
"Successfully replaced corrupt file with repaired version"
);
Ok(())
}
#[instrument]
pub async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {
task::spawn_blocking(move || {
let img = ImageReader::open(&path)
.map_err(|e| format!("Failed to open image: {e}"))?
.decode()
.map_err(|e| format!("Failed to decode image: {e}"))?;
let resized_img = img.resize(
img.width() / 2,
img.height() / 2,
image::imageops::FilterType::Nearest,
);
let mut buffer = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut buffer, 30);
encoder
.encode(
resized_img.as_bytes(),
resized_img.width(),
resized_img.height(),
resized_img.color().into(),
)
.map_err(|e| format!("Failed to compress image: {e}"))?;
Ok(buffer)
})
.await
.map_err(|e| format!("Failed to compress image: {e}"))?
}
pub struct InstantMultipartUpload {
pub handle: tokio::task::JoinHandle<Result<(), AuthedApiError>>,
}
impl InstantMultipartUpload {
/// starts a progressive (multipart) upload that runs until recording stops
/// and the file has stabilized (no additional data is being written).
pub fn spawn(
app: AppHandle,
file_path: PathBuf,
pre_created_video: VideoUploadInfo,
recording_dir: PathBuf,
realtime_upload_done: Option<Receiver<()>>,
) -> Self {
Self {
handle: spawn_actor(async move {
let start = Instant::now();
let result = Self::run(
app.clone(),
file_path.clone(),
pre_created_video,
recording_dir,
realtime_upload_done,
)
.await;
async_capture_event(
&app,
match &result {
Ok(meta) => PostHogEvent::MultipartUploadComplete {
duration: start.elapsed(),
length: meta
.as_ref()
.map(|v| Duration::from_secs(v.duration_in_secs as u64))
.unwrap_or_default(),
size: std::fs::metadata(file_path)
.map(|m| ((m.len() as f64) / 1_000_000.0) as u64)
.unwrap_or_default(),
},
Err(err) => PostHogEvent::MultipartUploadFailed {
duration: start.elapsed(),
error: err.to_string(),
},
},
);
result.map(|_| ())
}),
}
}
pub async fn run(
app: AppHandle,
file_path: PathBuf,
pre_created_video: VideoUploadInfo,
recording_dir: PathBuf,
realtime_video_done: Option<Receiver<()>>,
) -> Result<Option<S3VideoMeta>, AuthedApiError> {
let video_id = pre_created_video.id.clone();
debug!("Initiating multipart upload for {video_id}...");
let mut project_meta = RecordingMeta::load_for_project(&recording_dir).map_err(|err| {
format!("Error reading project meta from {recording_dir:?} for upload init: {err}")
})?;
project_meta.upload = Some(UploadMeta::MultipartUpload {
video_id: video_id.clone(),
file_path: file_path.clone(),
pre_created_video: pre_created_video.clone(),
recording_dir: recording_dir.clone(),
});
project_meta
.save_for_project()
.map_err(|e| error!("Failed to save recording meta: {e}"))
.ok();
let upload = api::upload_multipart_initiate(&app, &video_id).await?;
let is_drive_upload = is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id);
let upload_id = upload.upload_id;
let failed_chunks: Arc<Mutex<Vec<FailedChunkInfo>>> = Arc::new(Mutex::new(Vec::new()));
let mut parts = progress(
app.clone(),
video_id.clone(),
multipart_uploader(
app.clone(),
video_id.clone(),
upload_id.clone(),
is_drive_upload,
from_pending_file_to_chunks(file_path.clone(), realtime_video_done),
failed_chunks.clone(),
),
)
.try_collect::<Vec<_>>()
.await?;
let failed =
std::mem::take(&mut *failed_chunks.lock().unwrap_or_else(PoisonError::into_inner));
if !failed.is_empty() {
info!(
count = failed.len(),
"Retrying {} failed chunk(s) after main upload pass",
failed.len()
);
let retry_parts =
retry_failed_chunks(&app, &video_id, &upload_id, &file_path, failed).await?;
parts.extend(retry_parts);
}
let mut deduplicated_parts = HashMap::new();
for part in parts {
deduplicated_parts.insert(part.part_number, part);
}
parts = deduplicated_parts.into_values().collect::<Vec<_>>();
parts.sort_by_key(|part| part.part_number);
let metadata = match build_video_meta(&file_path) {
Ok(meta) => Some(meta),
Err(e) => {
error!("Failed to get video metadata: {e}");
warn!("Output file may be corrupt, attempting FFmpeg remux repair for {video_id}");
match try_repair_corrupt_mp4(&file_path) {
Ok(()) => {
info!("Successfully repaired corrupt recording for {video_id}");
match build_video_meta(&file_path) {
Ok(meta) => Some(meta),
Err(repair_meta_err) => {
error!(
"File still unreadable after repair attempt: {repair_meta_err}"
);
return Err(format!(
"Recording file could not be salvaged after encoder failure. \
Original error: {e}, Post-repair error: {repair_meta_err}"
)
.into());
}
}
}
Err(repair_err) => {
error!("FFmpeg repair also failed: {repair_err}");
return Err(format!(
"Recording file could not be salvaged after encoder failure. \
Original error: {e}, Repair error: {repair_err}"
)
.into());
}
}
}
};
api::upload_multipart_complete(&app, &video_id, &upload_id, &parts, metadata.clone())
.await?;
info!("Multipart upload complete for {video_id}.");
emit_upload_complete(&app, &video_id);
let mut project_meta = RecordingMeta::load_for_project(&recording_dir).map_err(|err| {
format!("Error reading project meta from {recording_dir:?} for upload complete: {err}")
})?;
project_meta.upload = Some(UploadMeta::Complete);
project_meta
.save_for_project()
.map_err(|err| format!("Error reading project meta from {recording_dir:?}: {err}"))?;
let _ = app.clipboard().write_text(pre_created_video.link.clone());
Ok(metadata)
}
}
pub struct SegmentUploader {
pub handle: tokio::task::JoinHandle<Result<(), AuthedApiError>>,
}
struct SegmentUploadState {
uploaded_video_segments: std::collections::HashMap<u32, f64>,
uploaded_audio_segments: std::collections::HashMap<u32, f64>,
video_init_uploaded: bool,
audio_init_uploaded: bool,
failed_segments: Vec<FailedSegmentInfo>,
total_bytes_uploaded: u64,
}
#[derive(Clone)]
struct FailedSegmentInfo {
subpath: String,
file_path: PathBuf,
is_init: bool,
media_type: cap_enc_ffmpeg::segmented_stream::SegmentMediaType,
index: u32,
duration: f64,
expected_size: u64,
}
impl SegmentUploadState {
fn new() -> Self {
Self {
uploaded_video_segments: std::collections::HashMap::new(),
uploaded_audio_segments: std::collections::HashMap::new(),
video_init_uploaded: false,
audio_init_uploaded: false,
failed_segments: Vec::new(),
total_bytes_uploaded: 0,
}
}
fn to_manifest(&self) -> SegmentUploadManifest {
let mut video_segments: Vec<SegmentManifestEntry> = self
.uploaded_video_segments
.iter()
.map(|(&index, &duration)| SegmentManifestEntry { index, duration })
.collect();
video_segments.sort_by_key(|s| s.index);
let mut audio_segments: Vec<SegmentManifestEntry> = self
.uploaded_audio_segments
.iter()
.map(|(&index, &duration)| SegmentManifestEntry { index, duration })
.collect();
audio_segments.sort_by_key(|s| s.index);
SegmentUploadManifest {
version: 2,
video_init_uploaded: self.video_init_uploaded,
audio_init_uploaded: self.audio_init_uploaded,
video_segments,
audio_segments,
is_complete: false,
}
}
fn to_complete_manifest(&self) -> SegmentUploadManifest {
let mut manifest = self.to_manifest();
manifest.is_complete = true;
manifest
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct SegmentManifestEntry {
index: u32,
duration: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct SegmentUploadManifest {
version: u32,
video_init_uploaded: bool,
audio_init_uploaded: bool,
video_segments: Vec<SegmentManifestEntry>,
audio_segments: Vec<SegmentManifestEntry>,
is_complete: bool,
}
impl SegmentUploadManifest {
fn has_video_content(&self) -> bool {
self.video_init_uploaded && !self.video_segments.is_empty()
}
}
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,
video_id: String,
segment_rx: std::sync::mpsc::Receiver<
cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent,
>,
recording_done: Option<flume::Receiver<()>>,
recording_dir: PathBuf,
pre_created_video: VideoUploadInfo,
) -> Self {
Self {
handle: spawn_actor(async move {
let start = Instant::now();
let result = Self::run(
app.clone(),
video_id.clone(),
segment_rx,
recording_done,
recording_dir.clone(),
pre_created_video,
)
.await;
async_capture_event(
&app,
match &result {
Ok(total_bytes) => PostHogEvent::MultipartUploadComplete {
duration: start.elapsed(),
length: start.elapsed(),
size: total_bytes / (1024 * 1024),
},
Err(err) => PostHogEvent::MultipartUploadFailed {
duration: start.elapsed(),
error: err.to_string(),
},
},
);
result.map(|_| ())
}),
}
}
async fn read_segment_data(
file_path: &Path,
subpath: &str,
expected_size: u64,
) -> Result<Bytes, AuthedApiError> {
const FILE_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
const DATA_WAIT_TIMEOUT: Duration = Duration::from_secs(30);
let start = Instant::now();
let actual_path = loop {
if file_path.exists() {
break file_path.to_path_buf();
}
if start.elapsed() > FILE_WAIT_TIMEOUT {
return Err(format!(
"segment_upload/timeout/{subpath}: file not found after {:?} ({})",
FILE_WAIT_TIMEOUT,
file_path.display()
)
.into());
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
let start = Instant::now();
let file_data = loop {
let data = tokio::fs::read(&actual_path).await.map_err(|e| {
format!(
"segment_upload/read/{subpath}: {e} ({})",
actual_path.display()
)
})?;
let size_ok = expected_size == 0 || data.len() as u64 >= expected_size;
if !data.is_empty() && size_ok {
break data;
}
if start.elapsed() > DATA_WAIT_TIMEOUT {
if data.is_empty() {
warn!(
subpath,
path = %actual_path.display(),
"Segment file still empty after {:?}, skipping upload",
DATA_WAIT_TIMEOUT
);
return Ok(Bytes::new());
}
break data;
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
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 = match cached_url.take() {
Some(url) => url,
None => url_cache.get_or_fetch(app, video_id, subpath).await?,
};
let client = app
.state::<RetryableHttpClient>()
.as_ref()
.map_err(|err| format!("segment_upload/client: {err:?}"))?
.clone();
let send_result = client
.put(&presigned_url)
.header("Content-Length", file_size)
.timeout(Duration::from_secs(5 * 60))
.body(file_bytes.clone())
.send()
.await;
match send_result {
Ok(resp) if resp.status().is_success() => {
return Ok(file_size as u64);
}
Ok(resp) => {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
if attempt < MAX_RETRIES - 1 {
warn!(
attempt = attempt + 1,
subpath,
status = %status,
"Segment upload failed, retrying"
);
tokio::time::sleep(Duration::from_millis(500 * (1 << attempt) as u64))
.await;
continue;
}
return Err(format!("segment_upload/{subpath}/error: {status} {body}").into());
}
Err(err) if is_reqwest_network_error(&err) => {
if attempt < MAX_RETRIES - 1 {
warn!(
attempt = attempt + 1,
subpath,
error = %err,
"Segment upload network error, retrying"
);
if !wait_for_network_recovery(app, video_id).await {
return Err(
format!("segment_upload/{subpath}/network_timeout: {err}").into()
);
}
continue;
}
return Err(format!("segment_upload/{subpath}/network_error: {err}").into());
}
Err(err) => {
return Err(format!("segment_upload/{subpath}/error: {err}").into());
}
}
}
Err(format!("segment_upload/{subpath}/exhausted_retries").into())
}
async fn upload_manifest(
app: &AppHandle,
video_id: &str,
manifest: &SegmentUploadManifest,
) -> Result<(), AuthedApiError> {
let json = serde_json::to_string_pretty(manifest)
.map_err(|e| format!("segment_upload/manifest/serialize: {e}"))?;
let presigned_url = api::upload_signed(
app,
api::PresignedS3PutRequest {
video_id: video_id.to_string(),
subpath: "segments/manifest.json".to_string(),
method: api::PresignedS3PutRequestMethod::Put,
meta: None,
},
)
.await?;
let client = app
.state::<RetryableHttpClient>()
.as_ref()