vdsl-sync 0.6.0

File synchronization engine — N-location, pluggable store & backend
Documentation
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
//! Transfer — 配送オブジェクト。
//!
//! 「1つのファイルを、あるlocationからあるlocationへ送る」という1回の配送行為。
//! 配送状況は自分自身が持つ。TrackedFileに問い合わせない。
//!
//! # 状態遷移
//!
//! ```text
//! Blocked → Queued → InFlight → Completed
//!                              → Failed → (retry()で新Transferを生成)
//!                                       → Completed (resolve(): 事後条件が既に満たされている場合)
//!                              → Cancelled (プロセス中断。終端状態。再実行されない)
//! ```
//!
//! Failedからの復帰は通常 `retry()` で新しいTransfer (attempt +1) を生成する。
//! 失敗した記録は不変のまま履歴に残る。
//!
//! 例外: Delete転送で対象ファイルが既にdestに存在しない場合、
//! 事後条件(ファイル不在)が満たされているため `resolve()` で
//! Failed → Completed に直接遷移できる。
//!
//! Cancelled: プロセスkill等でInFlightのまま残った転送を正式に終了させる。
//! 終端状態であり、retry対象にならない。sync開始時のorphaned InFlight処理で使用。

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;

use super::error::DomainError;
use super::location::LocationId;
use super::retry::{RetryPolicy, TransferErrorKind};

/// 配送の種類。
///
/// - `Sync` — ファイルをsrcからdestへ転送する(既存の動作)。
/// - `Delete` — dest上のファイルを削除する(削除伝播)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TransferKind {
    /// ファイル転送(追加/更新)。
    #[default]
    Sync,
    /// ファイル削除(削除伝播)。
    Delete,
}

impl TransferKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Sync => "sync",
            Self::Delete => "delete",
        }
    }
}

impl fmt::Display for TransferKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for TransferKind {
    type Err = DomainError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "sync" => Ok(Self::Sync),
            "delete" => Ok(Self::Delete),
            other => Err(DomainError::Validation {
                field: "transfer_kind".into(),
                reason: format!("unknown transfer kind: {other}"),
            }),
        }
    }
}

/// 配送の状態。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransferState {
    /// 依存先Transferの完了待ち。depends_onが全てCompletedになるまで実行不可。
    Blocked,
    /// 転送待ち。配送指示が作成されたがまだ実行されていない。
    Queued,
    /// 転送中。バックエンドがファイルを送信している。
    InFlight,
    /// 転送完了。destにファイルが到達した。
    Completed,
    /// 転送失敗。エラー理由が`error`フィールドに記録される。
    Failed,
    /// プロセス中断により転送が不完全に終了。終端状態。再実行されない。
    ///
    /// sync開始時にorphaned InFlight transfersを検出した場合に遷移する。
    /// retry対象外。必要であれば新しいTransferを作成すること。
    Cancelled,
}

impl TransferState {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Blocked => "blocked",
            Self::Queued => "queued",
            Self::InFlight => "in_flight",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
        }
    }

    /// まだ配送が必要な状態か。
    pub fn is_actionable(&self) -> bool {
        matches!(self, Self::Queued)
    }

    /// 終端状態か(Completed, Failed, Cancelled)。
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }
}

impl fmt::Display for TransferState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for TransferState {
    type Err = DomainError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "blocked" => Ok(Self::Blocked),
            "queued" => Ok(Self::Queued),
            "in_flight" => Ok(Self::InFlight),
            "completed" => Ok(Self::Completed),
            "failed" => Ok(Self::Failed),
            "cancelled" => Ok(Self::Cancelled),
            other => Err(DomainError::InvalidTransferState(other.to_string())),
        }
    }
}

/// 1回の配送行為。
///
/// TrackedFileとは参照関係のみ (`file_id`)。
/// 配送状態・エラー・タイムスタンプは全てTransfer自身が保持する。
///
/// # 不変条件
///
/// - `src != dest` (自己転送は無意味)
/// - 状態遷移は `Blocked → Queued → InFlight → Completed|Failed|Cancelled` の一方向のみ
/// - Failedからの復帰は `retry()` で新Transferを生成する
/// - Cancelledは終端状態。プロセス中断によるorphaned InFlightの正式な終了
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transfer {
    id: String,
    file_id: String,
    src: LocationId,
    dest: LocationId,
    #[serde(default)]
    kind: TransferKind,
    state: TransferState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_kind: Option<TransferErrorKind>,
    attempt: u32,
    created_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    started_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    finished_at: Option<DateTime<Utc>>,
    /// 先行Transfer ID。このTransferはdepends_onが全てCompletedになるまでBlockedのまま。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    depends_on: Option<String>,
}

impl Transfer {
    // =========================================================================
    // Factory
    // =========================================================================

    /// 新しい配送指示を作成。state = Queued, attempt = 1。
    ///
    /// # Errors
    ///
    /// - `file_id` が空文字列の場合
    /// - `src == dest` の場合(自己転送は無意味)
    pub fn new(file_id: String, src: LocationId, dest: LocationId) -> Result<Self, DomainError> {
        Self::with_kind(file_id, src, dest, TransferKind::Sync)
    }

    /// 削除伝播用の配送指示を作成。state = Queued, kind = Delete。
    pub fn new_delete(
        file_id: String,
        src: LocationId,
        dest: LocationId,
    ) -> Result<Self, DomainError> {
        Self::with_kind(file_id, src, dest, TransferKind::Delete)
    }

    /// 配送指示を作成(kind指定)。
    pub fn with_kind(
        file_id: String,
        src: LocationId,
        dest: LocationId,
        kind: TransferKind,
    ) -> Result<Self, DomainError> {
        if file_id.is_empty() {
            return Err(DomainError::Validation {
                field: "file_id".into(),
                reason: "must not be empty".into(),
            });
        }
        if src == dest {
            return Err(DomainError::Validation {
                field: "src/dest".into(),
                reason: format!("self-transfer is not allowed: {src}"),
            });
        }
        Ok(Self {
            id: uuid::Uuid::new_v4().to_string(),
            file_id,
            src,
            dest,
            kind,
            state: TransferState::Queued,
            error: None,
            error_kind: None,
            attempt: 1,
            created_at: Utc::now(),
            started_at: None,
            finished_at: None,
            depends_on: None,
        })
    }

    /// 依存付きTransferを作成。state = Blocked。
    ///
    /// `depends_on_id`のTransferがCompletedになるまでBlockedのまま。
    pub fn with_dependency(
        file_id: String,
        src: LocationId,
        dest: LocationId,
        kind: TransferKind,
        depends_on_id: String,
    ) -> Result<Self, DomainError> {
        if file_id.is_empty() {
            return Err(DomainError::Validation {
                field: "file_id".into(),
                reason: "must not be empty".into(),
            });
        }
        if src == dest {
            return Err(DomainError::Validation {
                field: "src/dest".into(),
                reason: format!("self-transfer is not allowed: {src}"),
            });
        }
        Ok(Self {
            id: uuid::Uuid::new_v4().to_string(),
            file_id,
            src,
            dest,
            kind,
            state: TransferState::Blocked,
            error: None,
            error_kind: None,
            attempt: 1,
            created_at: Utc::now(),
            started_at: None,
            finished_at: None,
            depends_on: Some(depends_on_id),
        })
    }

    /// テスト用再構成(depends_on=None)。本番はreconstitute_with_dependencyを使用。
    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn reconstitute(
        id: String,
        file_id: String,
        src: LocationId,
        dest: LocationId,
        kind: TransferKind,
        state: TransferState,
        error: Option<String>,
        error_kind: Option<TransferErrorKind>,
        attempt: u32,
        created_at: DateTime<Utc>,
        started_at: Option<DateTime<Utc>>,
        finished_at: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            id,
            file_id,
            src,
            dest,
            kind,
            state,
            error,
            error_kind,
            attempt,
            created_at,
            started_at,
            finished_at,
            depends_on: None,
        }
    }

    /// DB復元用(depends_on付き)。
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn reconstitute_with_dependency(
        id: String,
        file_id: String,
        src: LocationId,
        dest: LocationId,
        kind: TransferKind,
        state: TransferState,
        error: Option<String>,
        error_kind: Option<TransferErrorKind>,
        attempt: u32,
        created_at: DateTime<Utc>,
        started_at: Option<DateTime<Utc>>,
        finished_at: Option<DateTime<Utc>>,
        depends_on: Option<String>,
    ) -> Self {
        Self {
            id,
            file_id,
            src,
            dest,
            kind,
            state,
            error,
            error_kind,
            attempt,
            created_at,
            started_at,
            finished_at,
            depends_on,
        }
    }

    // =========================================================================
    // State transitions
    // =========================================================================

    /// 依存解除。Blocked → Queued。
    ///
    /// depends_onの先行Transferが完了した時に呼ばれる。
    /// Blocked以外の状態から呼ばれた場合はErrを返す。
    pub fn unblock(&mut self) -> Result<(), DomainError> {
        if self.state != TransferState::Blocked {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "queued (unblock)".to_string(),
            });
        }
        self.state = TransferState::Queued;
        Ok(())
    }

    /// 転送開始。Queued → InFlight。
    ///
    /// Queued以外の状態から呼ばれた場合はErrを返す。
    pub fn start(&mut self) -> Result<(), DomainError> {
        if self.state != TransferState::Queued {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "in_flight".to_string(),
            });
        }
        self.state = TransferState::InFlight;
        self.started_at = Some(Utc::now());
        Ok(())
    }

    /// 転送完了。InFlight → Completed。
    ///
    /// InFlight以外の状態から呼ばれた場合はErrを返す。
    pub fn complete(&mut self) -> Result<(), DomainError> {
        if self.state != TransferState::InFlight {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "completed".to_string(),
            });
        }
        self.state = TransferState::Completed;
        self.finished_at = Some(Utc::now());
        Ok(())
    }

    /// 転送失敗。InFlight → Failed。
    ///
    /// `kind` でエラーの種別を分類する:
    /// - [`Transient`](TransferErrorKind::Transient) — リトライ対象
    /// - [`Permanent`](TransferErrorKind::Permanent) — リトライ不要
    ///
    /// InFlight以外の状態から呼ばれた場合はErrを返す。
    pub fn fail(&mut self, error: String, kind: TransferErrorKind) -> Result<(), DomainError> {
        if self.state != TransferState::InFlight {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "failed".to_string(),
            });
        }
        self.state = TransferState::Failed;
        self.error = Some(error);
        self.error_kind = Some(kind);
        self.finished_at = Some(Utc::now());
        Ok(())
    }

    /// 事後条件による解決。Failed → Completed。
    ///
    /// 転送自体は失敗したが、転送の目的(事後条件)が既に
    /// 満たされている場合に使用する。
    ///
    /// 典型例: Delete転送が「object not found」で失敗したが、
    /// destにファイルが存在しない(=削除の目的が達成済み)。
    ///
    /// Failed以外の状態から呼ばれた場合はErrを返す。
    pub fn resolve(&mut self) -> Result<(), DomainError> {
        if self.state != TransferState::Failed {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "completed (resolve)".to_string(),
            });
        }
        self.state = TransferState::Completed;
        self.finished_at = Some(Utc::now());
        Ok(())
    }

    /// プロセス中断によるキャンセル。InFlight → Cancelled。
    ///
    /// sync開始時にorphaned InFlight transfersを検出した場合に使用。
    /// Cancelledは終端状態 — retry対象にならず、再実行もされない。
    /// 必要であれば新しいTransferを作成すること。
    ///
    /// InFlight以外の状態から呼ばれた場合はErrを返す。
    pub fn cancel(&mut self) -> Result<(), DomainError> {
        if self.state != TransferState::InFlight {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "cancelled".to_string(),
            });
        }
        self.state = TransferState::Cancelled;
        self.finished_at = Some(Utc::now());
        Ok(())
    }

    /// リトライ: この失敗Transferを元に新しいTransferを生成。
    ///
    /// attempt +1。元のTransferは不変のまま履歴に残る。
    /// Failed以外から呼ばれた場合はErrを返す。
    pub fn retry(&self) -> Result<Self, DomainError> {
        if self.state != TransferState::Failed {
            return Err(DomainError::InvalidStateTransition {
                from: self.state.as_str().to_string(),
                to: "queued (retry)".to_string(),
            });
        }
        Ok(Self {
            id: uuid::Uuid::new_v4().to_string(),
            file_id: self.file_id.clone(),
            src: self.src.clone(),
            dest: self.dest.clone(),
            kind: self.kind,
            state: TransferState::Queued,
            error: None,
            error_kind: None,
            attempt: self.attempt.saturating_add(1),
            created_at: Utc::now(),
            started_at: None,
            finished_at: None,
            depends_on: None,
        })
    }

    // =========================================================================
    // Retry domain logic
    // =========================================================================

    /// このTransferはリトライ対象か(ドメインルール)。
    ///
    /// 以下の全条件を満たす場合にtrue:
    /// 1. 状態がFailed
    /// 2. エラー種別がTransient(一時的エラー)
    /// 3. 試行回数がmax_attempts未満
    pub fn is_retryable(&self, policy: &RetryPolicy) -> bool {
        self.state == TransferState::Failed
            && self.error_kind == Some(TransferErrorKind::Transient)
            && self.attempt < policy.max_attempts()
    }

    /// リトライ上限に到達したか。
    ///
    /// Failedかつ以下のいずれか:
    /// - Permanentエラー(リトライ不要)
    /// - 試行回数がmax_attempts以上(Transientでも上限到達)
    pub fn is_exhausted(&self, policy: &RetryPolicy) -> bool {
        self.state == TransferState::Failed
            && (self.error_kind == Some(TransferErrorKind::Permanent)
                || self.attempt >= policy.max_attempts())
    }

    // =========================================================================
    // Queries
    // =========================================================================

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn file_id(&self) -> &str {
        &self.file_id
    }

    pub fn src(&self) -> &LocationId {
        &self.src
    }

    pub fn dest(&self) -> &LocationId {
        &self.dest
    }

    pub fn kind(&self) -> TransferKind {
        self.kind
    }

    pub fn is_delete(&self) -> bool {
        self.kind == TransferKind::Delete
    }

    pub fn state(&self) -> TransferState {
        self.state
    }

    pub fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }

    pub fn error_kind(&self) -> Option<TransferErrorKind> {
        self.error_kind
    }

    pub fn attempt(&self) -> u32 {
        self.attempt
    }

    pub fn created_at(&self) -> DateTime<Utc> {
        self.created_at
    }

    pub fn started_at(&self) -> Option<DateTime<Utc>> {
        self.started_at
    }

    pub fn finished_at(&self) -> Option<DateTime<Utc>> {
        self.finished_at
    }

    pub fn depends_on(&self) -> Option<&str> {
        self.depends_on.as_deref()
    }

    /// Serialize to [`serde_json::Value`] for cross-boundary transport.
    pub fn to_value(&self) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::to_value(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn loc(s: &str) -> LocationId {
        LocationId::new(s).unwrap()
    }

    fn sample_transfer() -> Transfer {
        Transfer::new("file-1".into(), loc("local"), loc("cloud")).expect("valid test data")
    }

    fn failed_transient(attempt: u32) -> Transfer {
        Transfer::reconstitute(
            uuid::Uuid::new_v4().to_string(),
            "file-1".into(),
            loc("local"),
            loc("cloud"),
            TransferKind::Sync,
            TransferState::Failed,
            Some("timeout".into()),
            Some(TransferErrorKind::Transient),
            attempt,
            Utc::now(),
            Some(Utc::now()),
            Some(Utc::now()),
        )
    }

    fn failed_permanent() -> Transfer {
        Transfer::reconstitute(
            uuid::Uuid::new_v4().to_string(),
            "file-1".into(),
            loc("local"),
            loc("cloud"),
            TransferKind::Sync,
            TransferState::Failed,
            Some("file not found".into()),
            Some(TransferErrorKind::Permanent),
            1,
            Utc::now(),
            Some(Utc::now()),
            Some(Utc::now()),
        )
    }

    // --- Factory ---

    #[test]
    fn new_creates_queued_transfer() {
        let t = sample_transfer();
        assert_eq!(t.state(), TransferState::Queued);
        assert_eq!(t.attempt(), 1);
        assert_eq!(t.file_id(), "file-1");
        assert_eq!(t.src(), &loc("local"));
        assert_eq!(t.dest(), &loc("cloud"));
        assert!(t.error().is_none());
        assert!(t.error_kind().is_none());
        assert!(t.started_at().is_none());
        assert!(t.finished_at().is_none());
    }

    // --- Happy path: Queued → InFlight → Completed ---

    #[test]
    fn start_transitions_to_in_flight() {
        let mut t = sample_transfer();
        t.start().unwrap();
        assert_eq!(t.state(), TransferState::InFlight);
        assert!(t.started_at().is_some());
    }

    #[test]
    fn complete_transitions_to_completed() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.complete().unwrap();
        assert_eq!(t.state(), TransferState::Completed);
        assert!(t.finished_at().is_some());
    }

    // --- Failure path: Queued → InFlight → Failed ---

    #[test]
    fn fail_transient_transitions_to_failed() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.fail("B2 timeout".into(), TransferErrorKind::Transient)
            .unwrap();
        assert_eq!(t.state(), TransferState::Failed);
        assert_eq!(t.error(), Some("B2 timeout"));
        assert_eq!(t.error_kind(), Some(TransferErrorKind::Transient));
        assert!(t.finished_at().is_some());
    }

    #[test]
    fn fail_permanent_transitions_to_failed() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.fail("file not found".into(), TransferErrorKind::Permanent)
            .unwrap();
        assert_eq!(t.state(), TransferState::Failed);
        assert_eq!(t.error_kind(), Some(TransferErrorKind::Permanent));
    }

    // --- Retry domain logic ---

    #[test]
    fn transient_within_limit_is_retryable() {
        let policy = RetryPolicy::new(3);
        let t = failed_transient(1); // attempt 1 < max 3
        assert!(t.is_retryable(&policy));
        assert!(!t.is_exhausted(&policy));
    }

    #[test]
    fn transient_at_limit_is_exhausted() {
        let policy = RetryPolicy::new(3);
        let t = failed_transient(3); // attempt 3 >= max 3
        assert!(!t.is_retryable(&policy));
        assert!(t.is_exhausted(&policy));
    }

    #[test]
    fn permanent_is_never_retryable() {
        let policy = RetryPolicy::new(10);
        let t = failed_permanent(); // attempt 1, but Permanent
        assert!(!t.is_retryable(&policy));
        assert!(t.is_exhausted(&policy));
    }

    #[test]
    fn queued_is_not_retryable() {
        let policy = RetryPolicy::default();
        let t = sample_transfer();
        assert!(!t.is_retryable(&policy));
        assert!(!t.is_exhausted(&policy));
    }

    // --- Retry factory ---

    #[test]
    fn retry_creates_new_queued_transfer() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.fail("error".into(), TransferErrorKind::Transient)
            .unwrap();

        let t2 = t.retry().unwrap();
        assert_eq!(t2.state(), TransferState::Queued);
        assert_eq!(t2.attempt(), 2);
        assert_eq!(t2.file_id(), "file-1");
        assert_eq!(t2.src(), &loc("local"));
        assert_eq!(t2.dest(), &loc("cloud"));
        assert!(t2.error().is_none());
        assert!(t2.error_kind().is_none());
        assert_ne!(t2.id(), t.id(), "retry must generate new id");
    }

    #[test]
    fn retry_preserves_original() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.fail("error".into(), TransferErrorKind::Transient)
            .unwrap();
        let original_id = t.id().to_string();

        let _ = t.retry().unwrap();

        // Original is unchanged
        assert_eq!(t.id(), original_id);
        assert_eq!(t.state(), TransferState::Failed);
        assert_eq!(t.error(), Some("error"));
        assert_eq!(t.error_kind(), Some(TransferErrorKind::Transient));
    }

    // --- Invalid transitions ---

    #[test]
    fn start_from_non_queued_fails() {
        let mut t = sample_transfer();
        t.start().unwrap();
        assert!(t.start().is_err(), "InFlight → InFlight is invalid");
    }

    #[test]
    fn complete_from_queued_fails() {
        let mut t = sample_transfer();
        assert!(t.complete().is_err(), "Queued → Completed is invalid");
    }

    #[test]
    fn fail_from_queued_fails() {
        let mut t = sample_transfer();
        assert!(
            t.fail("err".into(), TransferErrorKind::Transient).is_err(),
            "Queued → Failed is invalid"
        );
    }

    #[test]
    fn retry_from_non_failed_fails() {
        let t = sample_transfer();
        assert!(t.retry().is_err(), "Queued → retry is invalid");
    }

    #[test]
    fn retry_from_completed_fails() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.complete().unwrap();
        assert!(t.retry().is_err(), "Completed → retry is invalid");
    }

    // --- TransferState ---

    #[test]
    fn state_roundtrip() {
        for state in [
            TransferState::Queued,
            TransferState::InFlight,
            TransferState::Completed,
            TransferState::Failed,
        ] {
            let s = state.as_str();
            let parsed: TransferState = s.parse().unwrap();
            assert_eq!(parsed, state);
        }
    }

    #[test]
    fn is_actionable() {
        assert!(TransferState::Queued.is_actionable());
        assert!(!TransferState::InFlight.is_actionable());
        assert!(!TransferState::Completed.is_actionable());
        assert!(!TransferState::Failed.is_actionable());
    }

    // --- Serde ---

    #[test]
    fn serde_roundtrip() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.complete().unwrap();
        let json = serde_json::to_value(&t).unwrap();
        let restored: Transfer = serde_json::from_value(json).unwrap();
        assert_eq!(restored.state(), TransferState::Completed);
        assert_eq!(restored.file_id(), "file-1");
    }

    #[test]
    fn serde_roundtrip_failed_with_error_kind() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.fail("net err".into(), TransferErrorKind::Transient)
            .unwrap();
        let json = serde_json::to_value(&t).unwrap();
        let restored: Transfer = serde_json::from_value(json).unwrap();
        assert_eq!(restored.state(), TransferState::Failed);
        assert_eq!(restored.error_kind(), Some(TransferErrorKind::Transient));
    }

    // --- Validation ---

    #[test]
    fn new_rejects_empty_file_id() {
        let result = Transfer::new("".into(), loc("local"), loc("cloud"));
        assert!(result.is_err());
    }

    #[test]
    fn new_rejects_self_transfer() {
        let result = Transfer::new("file-1".into(), loc("local"), loc("local"));
        assert!(result.is_err());
    }

    // --- Resolve (Failed → Completed) ---

    #[test]
    fn resolve_transitions_failed_to_completed() {
        let mut t = failed_transient(3);
        assert_eq!(t.state(), TransferState::Failed);
        t.resolve().unwrap();
        assert_eq!(t.state(), TransferState::Completed);
        assert!(t.finished_at().is_some());
    }

    #[test]
    fn resolve_from_queued_fails() {
        let mut t = sample_transfer();
        assert!(
            t.resolve().is_err(),
            "Queued → Completed (resolve) is invalid"
        );
    }

    #[test]
    fn resolve_from_inflight_fails() {
        let mut t = sample_transfer();
        t.start().unwrap();
        assert!(
            t.resolve().is_err(),
            "InFlight → Completed (resolve) is invalid"
        );
    }

    #[test]
    fn resolve_from_completed_fails() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.complete().unwrap();
        assert!(
            t.resolve().is_err(),
            "Completed → Completed (resolve) is invalid"
        );
    }

    // --- Cancel (InFlight → Cancelled) ---

    #[test]
    fn cancel_transitions_inflight_to_cancelled() {
        let mut t = sample_transfer();
        t.start().unwrap();
        assert_eq!(t.state(), TransferState::InFlight);
        t.cancel().unwrap();
        assert_eq!(t.state(), TransferState::Cancelled);
        assert!(t.finished_at().is_some());
    }

    #[test]
    fn cancel_from_queued_fails() {
        let mut t = sample_transfer();
        assert!(t.cancel().is_err(), "Queued → Cancelled is invalid");
    }

    #[test]
    fn cancel_from_completed_fails() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.complete().unwrap();
        assert!(t.cancel().is_err(), "Completed → Cancelled is invalid");
    }

    #[test]
    fn cancel_from_failed_fails() {
        let t = failed_transient(1);
        let mut t = t;
        assert!(t.cancel().is_err(), "Failed → Cancelled is invalid");
    }

    #[test]
    fn cancelled_is_terminal() {
        assert!(TransferState::Cancelled.is_terminal());
        assert!(TransferState::Completed.is_terminal());
        assert!(TransferState::Failed.is_terminal());
        assert!(!TransferState::Queued.is_terminal());
        assert!(!TransferState::InFlight.is_terminal());
        assert!(!TransferState::Blocked.is_terminal());
    }

    #[test]
    fn cancelled_is_not_actionable() {
        assert!(!TransferState::Cancelled.is_actionable());
    }

    #[test]
    fn cancelled_roundtrip_serde() {
        let mut t = sample_transfer();
        t.start().unwrap();
        t.cancel().unwrap();
        let json = serde_json::to_value(&t).unwrap();
        let restored: Transfer = serde_json::from_value(json).unwrap();
        assert_eq!(restored.state(), TransferState::Cancelled);
    }

    #[test]
    fn cancelled_state_str_roundtrip() {
        let s = TransferState::Cancelled.as_str();
        assert_eq!(s, "cancelled");
        let parsed: TransferState = s.parse().unwrap();
        assert_eq!(parsed, TransferState::Cancelled);
    }
}