tus-protocol 0.1.0

Rust implementation of the TUS resumable upload protocol
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
use chrono::{DateTime, Utc};

use crate::error::{Error, Result};
use crate::locking::Locker;
use crate::state::StateStore;
use crate::storage::Storage;

use super::prepare_upload_reclamation_access;

/// Outcomes produced by an expired upload reclamation scan.
#[derive(Debug, Default)]
pub struct ExpiredUploadReclamationReport {
    outcomes: Vec<ExpiredUploadReclamationOutcome>,
}

impl ExpiredUploadReclamationReport {
    /// Returns the per-upload reclamation outcomes in candidate order.
    #[must_use]
    pub fn outcomes(&self) -> &[ExpiredUploadReclamationOutcome] {
        &self.outcomes
    }

    /// Returns the number of uploads whose data and state were removed.
    #[must_use]
    pub fn removed(&self) -> usize {
        self.outcomes
            .iter()
            .filter(|outcome| matches!(outcome, ExpiredUploadReclamationOutcome::Removed { .. }))
            .count()
    }

    /// Returns whether any candidate failed during reclamation.
    #[must_use]
    pub fn has_failures(&self) -> bool {
        self.outcomes
            .iter()
            .any(ExpiredUploadReclamationOutcome::is_failure)
    }

    fn push(&mut self, outcome: ExpiredUploadReclamationOutcome) {
        self.outcomes.push(outcome);
    }
}

/// Reclamation outcome for a single expired upload candidate.
#[derive(Debug)]
#[non_exhaustive]
pub enum ExpiredUploadReclamationOutcome {
    /// The upload data and state were removed.
    #[non_exhaustive]
    Removed {
        /// Candidate upload ID.
        upload_id: String,
    },
    /// The upload was locked by another operation and was not reclaimed.
    #[non_exhaustive]
    Locked {
        /// Candidate upload ID.
        upload_id: String,
    },
    /// The upload state disappeared after the candidate was listed.
    #[non_exhaustive]
    MissingState {
        /// Candidate upload ID.
        upload_id: String,
    },
    /// The upload state was no longer expired after locking and reloading it.
    #[non_exhaustive]
    NoLongerExpired {
        /// Candidate upload ID.
        upload_id: String,
    },
    /// Upload data deletion failed, so state deletion was not attempted.
    #[non_exhaustive]
    StorageDeleteFailed {
        /// Candidate upload ID.
        upload_id: String,
        /// Storage deletion error.
        error: Error,
    },
    /// Upload state deletion failed after upload data was deleted.
    #[non_exhaustive]
    StateDeleteFailed {
        /// Candidate upload ID.
        upload_id: String,
        /// State deletion error.
        error: Error,
    },
    /// Reclamation could not be attempted or completed because a preparatory
    /// step failed (locking, loading, or completion reconciliation). The scan
    /// records the failure and moves on to the next candidate.
    #[non_exhaustive]
    Failed {
        /// Candidate upload ID.
        upload_id: String,
        /// The error that prevented reclamation.
        error: Error,
    },
}

impl ExpiredUploadReclamationOutcome {
    /// Returns the candidate upload ID associated with this outcome.
    #[must_use]
    pub fn upload_id(&self) -> &str {
        match self {
            Self::Removed { upload_id }
            | Self::Locked { upload_id }
            | Self::MissingState { upload_id }
            | Self::NoLongerExpired { upload_id }
            | Self::StorageDeleteFailed { upload_id, .. }
            | Self::StateDeleteFailed { upload_id, .. }
            | Self::Failed { upload_id, .. } => upload_id,
        }
    }

    /// Returns whether the outcome represents a failed reclamation.
    #[must_use]
    pub fn is_failure(&self) -> bool {
        matches!(
            self,
            Self::StorageDeleteFailed { .. } | Self::StateDeleteFailed { .. } | Self::Failed { .. }
        )
    }
}

/// Reclaims protocol-expired uploads by deleting upload data before upload state.
///
/// Candidates are loaded from [`StateStore::list_expired`]. Each candidate is
/// locked with [`Locker::try_lock`], reloaded, checked for current expiration,
/// and then reclaimed. Per-candidate failures, whether a preparatory step
/// (locking, loading, completion reconciliation) or a deletion, are reported
/// as outcomes so the scan continues to the remaining candidates instead of
/// aborting and discarding the report. Only a failure to list candidates in the
/// first place propagates as an error.
///
/// Reclamation does not retain an expired partial upload because a planned final
/// upload references it, and does not cascade deletion to referencing final
/// uploads. A final upload that is itself expired is reclaimed as its own
/// candidate; otherwise protocol reads treat expired or missing referenced parts
/// as making the planned final upload expired until it has been materialized.
///
/// # Reclaiming a referenced partial (intentional)
///
/// This is a deliberate, stable stance: an expired partial is reclaimed even
/// while a not-yet-materialized final (Concatenation) upload still references
/// it. Once the part is gone, that final upload becomes permanently
/// unreadable, reads of it report [`Error::Expired`], so a concatenation
/// whose parts outlive their expiry before the final is materialized is lost,
/// not merely stale.
///
/// The alternatives were rejected as worse defaults: cascading deletion would
/// reach across references to delete finals that are not themselves expired,
/// and retaining referenced parts indefinitely would let never-materialized
/// finals pin their parts forever (a storage-leak / denial-of-service vector).
/// Materialize final uploads before their parts expire, or set an expiration
/// window that comfortably outlasts the client's concatenation flow.
///
/// [`Error::Expired`]: crate::Error::Expired
pub async fn reclaim_expired_uploads<S, St, L>(
    storage: &S,
    state_store: &St,
    locker: &L,
    before: DateTime<Utc>,
) -> Result<ExpiredUploadReclamationReport>
where
    S: Storage + ?Sized,
    St: StateStore + ?Sized,
    L: Locker + ?Sized,
{
    let mut report = ExpiredUploadReclamationReport::default();
    let upload_ids = state_store.list_expired(before).await?;

    for upload_id in upload_ids {
        report.push(reclaim_expired_upload(storage, state_store, locker, upload_id).await);
    }

    Ok(report)
}

async fn reclaim_expired_upload<S, St, L>(
    storage: &S,
    state_store: &St,
    locker: &L,
    upload_id: String,
) -> ExpiredUploadReclamationOutcome
where
    S: Storage + ?Sized,
    St: StateStore + ?Sized,
    L: Locker + ?Sized,
{
    let _guard = match locker.try_lock(&upload_id).await {
        Ok(Some(guard)) => guard,
        Ok(None) => return ExpiredUploadReclamationOutcome::Locked { upload_id },
        Err(error) => return ExpiredUploadReclamationOutcome::Failed { upload_id, error },
    };

    let mut state = match state_store.get(&upload_id).await {
        Ok(Some(state)) => state,
        Ok(None) => return ExpiredUploadReclamationOutcome::MissingState { upload_id },
        Err(error) => return ExpiredUploadReclamationOutcome::Failed { upload_id, error },
    };

    match prepare_upload_reclamation_access(storage, &mut state).await {
        Ok(true) => {}
        Ok(false) => return ExpiredUploadReclamationOutcome::NoLongerExpired { upload_id },
        Err(error) => return ExpiredUploadReclamationOutcome::Failed { upload_id, error },
    }

    if let Some(handle) = state.storage_handle()
        && let Err(error) = storage.delete(&handle).await
    {
        return ExpiredUploadReclamationOutcome::StorageDeleteFailed { upload_id, error };
    }

    if let Err(error) = state_store.delete(state.id()).await {
        return ExpiredUploadReclamationOutcome::StateDeleteFailed { upload_id, error };
    }

    ExpiredUploadReclamationOutcome::Removed { upload_id }
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};
    use std::sync::{Arc, Mutex};
    use std::time::Duration as StdDuration;

    use async_trait::async_trait;
    use chrono::Duration;

    use super::*;
    use crate::error::Error;
    use crate::locking::LockGuard;
    use crate::state::{UploadState, WriteMode};
    use crate::storage::{AppendRequest, ConcatRequest, StorageHandle};

    type OperationLog = Arc<Mutex<Vec<String>>>;

    #[tokio::test]
    async fn reclaim_expired_uploads_removes_storage_and_state() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        let state = expired_state("upload-1", "data-1");
        state_store.insert_candidate("upload-1");
        state_store.insert_state(state);

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 1);
        assert!(!report.has_failures());
        assert!(matches!(
            report.outcomes(),
            [ExpiredUploadReclamationOutcome::Removed { upload_id }]
                if upload_id == "upload-1"
        ));
        assert_eq!(storage.deleted(), vec!["data-1"]);
        assert_eq!(state_store.deleted(), vec!["upload-1"]);
        assert!(!state_store.contains("upload-1"));
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_locks_reloads_and_deletes_data_before_state() {
        let operations = Arc::new(Mutex::new(Vec::new()));
        let storage = TestStorage::with_operations(Arc::clone(&operations));
        let state_store = TestStateStore::with_operations(Arc::clone(&operations));
        let locker = TestLocker::with_operations(Arc::clone(&operations));
        state_store.insert_candidate("upload-1");
        state_store.insert_state(expired_state("upload-1", "data-1"));

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 1);
        assert_eq!(
            *operations.lock().unwrap(),
            vec![
                "list_expired".to_string(),
                "try_lock upload-1".to_string(),
                "get upload-1".to_string(),
                "delete_storage data-1".to_string(),
                "delete_state upload-1".to_string(),
            ]
        );
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_locked_uploads() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        state_store.insert_candidate("upload-1");
        state_store.insert_state(expired_state("upload-1", "data-1"));
        locker.mark_locked("upload-1");

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 0);
        assert!(matches!(
            report.outcomes(),
            [ExpiredUploadReclamationOutcome::Locked { upload_id }]
                if upload_id == "upload-1"
        ));
        assert!(storage.deleted().is_empty());
        assert!(state_store.deleted().is_empty());
        assert!(state_store.contains("upload-1"));
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_missing_state_after_listing() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        state_store.insert_candidate("upload-1");

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 0);
        assert!(matches!(
            report.outcomes(),
            [ExpiredUploadReclamationOutcome::MissingState { upload_id }]
                if upload_id == "upload-1"
        ));
        assert!(storage.deleted().is_empty());
        assert!(state_store.deleted().is_empty());
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_no_longer_expired_after_locking() {
        let operations = Arc::new(Mutex::new(Vec::new()));
        let storage = TestStorage::with_operations(Arc::clone(&operations));
        let state_store = TestStateStore::with_operations(Arc::clone(&operations));
        let locker = TestLocker::with_operations(Arc::clone(&operations));
        state_store.insert_candidate("upload-1");
        state_store.insert_state(active_state("upload-1", "data-1"));

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 0);
        assert!(matches!(
            report.outcomes(),
            [ExpiredUploadReclamationOutcome::NoLongerExpired { upload_id }]
                if upload_id == "upload-1"
        ));
        assert!(storage.deleted().is_empty());
        assert!(state_store.deleted().is_empty());
        assert!(state_store.contains("upload-1"));
        assert_eq!(
            *operations.lock().unwrap(),
            vec![
                "list_expired".to_string(),
                "try_lock upload-1".to_string(),
                "get upload-1".to_string(),
            ]
        );
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_passes_storage_owned_handle_facts_to_delete() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        let mut handle = StorageHandle::new("data-1");
        handle.set_internal("multipart-upload-id", "session-1");
        let mut state =
            UploadState::new("upload-1").with_expiration(Utc::now() - Duration::hours(1));
        state.set_storage_handle(handle.clone());
        state_store.insert_candidate("upload-1");
        state_store.insert_state(state);

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 1);
        assert_eq!(storage.deleted_handles(), vec![handle]);
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_does_not_retain_or_cascade_referenced_partials() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        let partial = expired_state("part-1", "part-data").with_partial();
        let mut final_upload = active_state("final-1", "final-data")
            .with_length(10)
            .with_final(vec!["part-1".to_string()]);
        final_upload.set_offset(5);
        state_store.insert_candidate("part-1");
        state_store.insert_state(partial);
        state_store.insert_state(final_upload);

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 1);
        assert_eq!(storage.deleted(), vec!["part-data"]);
        assert!(!state_store.contains("part-1"));
        assert!(state_store.contains("final-1"));
    }

    #[tokio::test]
    async fn reclaim_does_not_reclaim_or_persist_storage_completed_upload() {
        // Stored bytes reached the declared length but the completing state
        // write never landed. Reclamation must recognize this as completed
        // content and leave it alone (not reclaimable). Crucially, it must NOT
        // persist the completion: this scan has no hook context, and finalizing
        // the upload here would permanently skip its PreFinish/PostFinish hooks.
        // The completion is left for the next client request to persist and fire
        // the finish gate.
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        let mut state = expired_state("upload-1", "data-1").with_length(5);
        state.set_offset(0);
        state_store.insert_candidate("upload-1");
        state_store.insert_state(state);
        storage.set_size("data-1", 5);

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();
        let recovered = state_store.get("upload-1").await.unwrap().unwrap();

        assert_eq!(report.removed(), 0);
        assert!(matches!(
            report.outcomes(),
            [ExpiredUploadReclamationOutcome::NoLongerExpired { upload_id }]
                if upload_id == "upload-1"
        ));
        assert!(storage.deleted().is_empty());
        assert!(state_store.deleted().is_empty());
        // Completion is intentionally left unpersisted so the finish hooks fire
        // on the next HEAD/PATCH/GET rather than being silently skipped here.
        assert_eq!(recovered.offset(), 0);
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_delete_failures() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        state_store.insert_candidate("storage-fails");
        state_store.insert_candidate("state-fails");
        state_store.insert_state(expired_state("storage-fails", "data-storage-fails"));
        state_store.insert_state(expired_state("state-fails", "data-state-fails"));
        storage.fail_delete("data-storage-fails");
        state_store.fail_delete("state-fails");

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 0);
        assert!(report.has_failures());
        assert!(matches!(
            &report.outcomes()[0],
            ExpiredUploadReclamationOutcome::StorageDeleteFailed { upload_id, error }
                if upload_id == "storage-fails"
                    && error.to_string().contains("storage delete failed")
        ));
        assert!(matches!(
            &report.outcomes()[1],
            ExpiredUploadReclamationOutcome::StateDeleteFailed { upload_id, error }
                if upload_id == "state-fails"
                    && error.to_string().contains("state delete failed")
        ));
        assert_eq!(storage.deleted(), vec!["data-state-fails"]);
        assert!(state_store.deleted().is_empty());
        assert!(state_store.contains("storage-fails"));
        assert!(state_store.contains("state-fails"));
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_preparatory_failures_and_continues() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        // First candidate cannot be locked (transient locker error); the scan
        // must record the failure and still reclaim the second candidate.
        state_store.insert_candidate("lock-fails");
        state_store.insert_candidate("upload-2");
        state_store.insert_state(expired_state("lock-fails", "data-1"));
        state_store.insert_state(expired_state("upload-2", "data-2"));
        locker.fail_lock("lock-fails");

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 1);
        assert!(report.has_failures());
        assert!(matches!(
            &report.outcomes()[0],
            ExpiredUploadReclamationOutcome::Failed { upload_id, .. }
                if upload_id == "lock-fails"
        ));
        assert!(matches!(
            &report.outcomes()[1],
            ExpiredUploadReclamationOutcome::Removed { upload_id }
                if upload_id == "upload-2"
        ));
        assert_eq!(storage.deleted(), vec!["data-2"]);
    }

    #[tokio::test]
    async fn reclaim_expired_uploads_reports_state_load_failures() {
        let storage = TestStorage::default();
        let state_store = TestStateStore::default();
        let locker = TestLocker::default();
        state_store.insert_candidate("get-fails");
        state_store.insert_state(expired_state("get-fails", "data-1"));
        state_store.fail_get("get-fails");

        let report = reclaim_expired_uploads(&storage, &state_store, &locker, Utc::now())
            .await
            .unwrap();

        assert_eq!(report.removed(), 0);
        assert!(report.has_failures());
        assert!(matches!(
            &report.outcomes()[0],
            ExpiredUploadReclamationOutcome::Failed { upload_id, .. }
                if upload_id == "get-fails"
        ));
    }

    fn expired_state(id: &str, storage_key: &str) -> UploadState {
        let mut state = UploadState::new(id).with_expiration(Utc::now() - Duration::hours(1));
        state.set_storage_handle(StorageHandle::new(storage_key));
        state
    }

    fn active_state(id: &str, storage_key: &str) -> UploadState {
        let mut state = UploadState::new(id).with_expiration(Utc::now() + Duration::hours(1));
        state.set_storage_handle(StorageHandle::new(storage_key));
        state
    }

    #[derive(Default)]
    struct TestStorage {
        deleted: Mutex<Vec<StorageHandle>>,
        fail_delete: Mutex<HashSet<String>>,
        sizes: Mutex<HashMap<String, u64>>,
        operations: Option<OperationLog>,
    }

    impl TestStorage {
        fn with_operations(operations: OperationLog) -> Self {
            Self {
                operations: Some(operations),
                ..Self::default()
            }
        }

        fn set_size(&self, key: &str, size: u64) {
            self.sizes.lock().unwrap().insert(key.to_string(), size);
        }

        fn fail_delete(&self, key: &str) {
            self.fail_delete.lock().unwrap().insert(key.to_string());
        }

        fn deleted(&self) -> Vec<String> {
            self.deleted
                .lock()
                .unwrap()
                .iter()
                .map(|handle| handle.key().to_string())
                .collect()
        }

        fn deleted_handles(&self) -> Vec<StorageHandle> {
            self.deleted.lock().unwrap().clone()
        }

        fn record(&self, operation: impl Into<String>) {
            if let Some(operations) = &self.operations {
                operations.lock().unwrap().push(operation.into());
            }
        }
    }

    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    impl Storage for TestStorage {
        fn name(&self) -> &'static str {
            "test"
        }

        async fn create(&self, upload_id: &str) -> Result<StorageHandle> {
            Ok(StorageHandle::new(upload_id))
        }

        async fn append(&self, request: AppendRequest) -> Result<StorageHandle> {
            Ok(request.handle)
        }

        async fn concat(&self, request: ConcatRequest) -> Result<StorageHandle> {
            Ok(request.target)
        }

        async fn delete(&self, handle: &StorageHandle) -> Result<()> {
            if self.fail_delete.lock().unwrap().contains(handle.key()) {
                return Err(Error::Internal(format!(
                    "storage delete failed for {}",
                    handle.key()
                )));
            }

            self.record(format!("delete_storage {}", handle.key()));
            self.deleted.lock().unwrap().push(handle.clone());
            Ok(())
        }

        async fn size(&self, handle: &StorageHandle) -> Result<Option<u64>> {
            Ok(self.sizes.lock().unwrap().get(handle.key()).copied())
        }
    }

    #[derive(Default)]
    struct TestStateStore {
        states: Mutex<HashMap<String, UploadState>>,
        expired: Mutex<Vec<String>>,
        deleted: Mutex<Vec<String>>,
        fail_delete: Mutex<HashSet<String>>,
        fail_get: Mutex<HashSet<String>>,
        operations: Option<OperationLog>,
    }

    impl TestStateStore {
        fn with_operations(operations: OperationLog) -> Self {
            Self {
                operations: Some(operations),
                ..Self::default()
            }
        }

        fn insert_candidate(&self, upload_id: &str) {
            self.expired.lock().unwrap().push(upload_id.to_string());
        }

        fn insert_state(&self, state: UploadState) {
            self.states
                .lock()
                .unwrap()
                .insert(state.id().to_string(), state);
        }

        fn fail_delete(&self, upload_id: &str) {
            self.fail_delete
                .lock()
                .unwrap()
                .insert(upload_id.to_string());
        }

        fn fail_get(&self, upload_id: &str) {
            self.fail_get.lock().unwrap().insert(upload_id.to_string());
        }

        fn deleted(&self) -> Vec<String> {
            self.deleted.lock().unwrap().clone()
        }

        fn contains(&self, upload_id: &str) -> bool {
            self.states.lock().unwrap().contains_key(upload_id)
        }

        fn record(&self, operation: impl Into<String>) {
            if let Some(operations) = &self.operations {
                operations.lock().unwrap().push(operation.into());
            }
        }
    }

    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    impl StateStore for TestStateStore {
        fn name(&self) -> &'static str {
            "test"
        }

        async fn set(&self, state: &UploadState, mode: WriteMode) -> Result<()> {
            let mut states = self.states.lock().unwrap();
            if mode == WriteMode::CreateNew && states.contains_key(state.id()) {
                return Err(Error::AlreadyExists(state.id().to_string()));
            }
            states.insert(state.id().to_string(), state.clone());
            Ok(())
        }

        async fn get(&self, id: &str) -> Result<Option<UploadState>> {
            self.record(format!("get {id}"));
            if self.fail_get.lock().unwrap().contains(id) {
                return Err(Error::Internal(format!("state get failed for {id}")));
            }
            Ok(self.states.lock().unwrap().get(id).cloned())
        }

        async fn delete(&self, id: &str) -> Result<()> {
            if self.fail_delete.lock().unwrap().contains(id) {
                return Err(Error::Internal(format!("state delete failed for {id}")));
            }

            self.record(format!("delete_state {id}"));
            self.deleted.lock().unwrap().push(id.to_string());
            self.states.lock().unwrap().remove(id);
            Ok(())
        }

        async fn list_expired(&self, _before: DateTime<Utc>) -> Result<Vec<String>> {
            self.record("list_expired");
            Ok(self.expired.lock().unwrap().clone())
        }
    }

    #[derive(Default)]
    struct TestLocker {
        locked: Mutex<HashSet<String>>,
        fail_lock: Mutex<HashSet<String>>,
        operations: Option<OperationLog>,
    }

    impl TestLocker {
        fn with_operations(operations: OperationLog) -> Self {
            Self {
                operations: Some(operations),
                ..Self::default()
            }
        }

        fn mark_locked(&self, upload_id: &str) {
            self.locked.lock().unwrap().insert(upload_id.to_string());
        }

        fn fail_lock(&self, upload_id: &str) {
            self.fail_lock.lock().unwrap().insert(upload_id.to_string());
        }

        fn record(&self, operation: impl Into<String>) {
            if let Some(operations) = &self.operations {
                operations.lock().unwrap().push(operation.into());
            }
        }
    }

    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    impl Locker for TestLocker {
        fn name(&self) -> &'static str {
            "test"
        }

        async fn lock(&self, upload_id: &str, _timeout: StdDuration) -> Result<LockGuard> {
            Ok(LockGuard::new(upload_id))
        }

        async fn try_lock(&self, upload_id: &str) -> Result<Option<LockGuard>> {
            self.record(format!("try_lock {upload_id}"));
            if self.fail_lock.lock().unwrap().contains(upload_id) {
                return Err(Error::Internal(format!("try_lock failed for {upload_id}")));
            }
            if self.locked.lock().unwrap().contains(upload_id) {
                return Ok(None);
            }

            Ok(Some(LockGuard::new(upload_id)))
        }
    }
}