vstorage 0.7.0

Common API for various icalendar/vcard storages.
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
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
// Copyright 2023-2025 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

mod common;

use futures_util::stream::TryStreamExt;
use std::path::Path;
use std::sync::Arc;
use tempfile::tempdir;
use vstorage::ItemKind;
use vstorage::base::{CreateItemOptions, Storage};
use vstorage::sync::plan::Plan;
use vstorage::sync::{
    conflict::{KeepSideResolver, resolve_conflicts},
    declare::{OnDelete, OnEmpty, StoragePair, SyncedCollection},
    execute::Executor,
    operation::{ItemOp, Operation},
    status::{Side, StatusDatabase},
};
use vstorage::vdir::VdirStorage;

use common::{minimal_icalendar, minimal_icalendar_with_uid};

/// Create a storage with three calendars each one with a single event.
async fn create_populated_storage(path: &Path) -> Arc<dyn Storage> {
    let storage = VdirStorage::builder(path.to_path_buf().try_into().unwrap())
        .unwrap()
        .build(ItemKind::Calendar);

    let first = storage.create_collection("first-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    let opts = CreateItemOptions::default();
    storage
        .create_item(first.href(), item, opts.clone())
        .await
        .unwrap();

    let item = &minimal_icalendar("First calendar event two")
        .unwrap()
        .into();
    storage
        .create_item(first.href(), item, opts.clone())
        .await
        .unwrap();
    drop(first);

    let second = storage.create_collection("second-calendar").await.unwrap();
    let item = &minimal_icalendar("Second calendar event one")
        .unwrap()
        .into();
    storage
        .create_item(second.href(), item, opts.clone())
        .await
        .unwrap();

    let item = &minimal_icalendar("Second calendar event two")
        .unwrap()
        .into();
    storage
        .create_item(second.href(), item, opts.clone())
        .await
        .unwrap();
    drop(second);

    let third = storage.create_collection("third-calendar").await.unwrap();
    let item = &minimal_icalendar("Third calendar event one")
        .unwrap()
        .into();
    storage.create_item(third.href(), item, opts).await.unwrap();
    drop(third);

    Arc::new(storage)
}

fn create_empty_storage(path: &Path) -> Arc<dyn Storage> {
    let storage = VdirStorage::builder(path.to_path_buf().try_into().unwrap())
        .unwrap()
        .build(ItemKind::Calendar);
    Arc::new(storage)
}

// TODO: maybe "second calendar" should exist in side B for these to make more sense.

#[tokio::test]
async fn sync_only_declared_mappings() {
    let populated_path = tempdir().unwrap();
    let empty_path = tempdir().unwrap();
    let populated = create_populated_storage(populated_path.path()).await;
    let empty = create_empty_storage(empty_path.path());

    let first_mapping = SyncedCollection::direct("first-calendar".parse().unwrap());
    let second_mapping = SyncedCollection::direct("second-calendar".parse().unwrap());
    // third-calendar is not synced.

    let pair = StoragePair::new(populated.clone(), empty.clone())
        .with_mapping(first_mapping)
        .with_mapping(second_mapping);

    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(populated, empty, operations, &status)
        .await
        .unwrap()
        .unwrap();

    let first = std::fs::read_dir(empty_path.path().join("first-calendar"))
        .unwrap()
        .map(|r| r.unwrap())
        .collect::<Vec<_>>();
    assert_eq!(first.len(), 2);
    for item in first {
        let data = std::fs::read_to_string(item.path()).unwrap();
        let found = data.find("First calendar event");
        assert!(found.is_some());
    }

    let second = std::fs::read_dir(empty_path.path().join("second-calendar"))
        .unwrap()
        .map(|r| r.unwrap())
        .collect::<Vec<_>>();
    assert_eq!(second.len(), 2);
    for item in second {
        let data = std::fs::read_to_string(item.path()).unwrap();
        let found = data.find("Second calendar event");
        assert!(found.is_some());
    }

    let _third = std::fs::read_dir(empty_path.path().join("third-calendar")).unwrap_err();

    std::fs::remove_dir_all(populated_path).unwrap();
    std::fs::remove_dir_all(empty_path).unwrap();
}

#[tokio::test]
async fn sync_from_a() {
    let populated_path = tempdir().unwrap();
    let empty_path = tempdir().unwrap();
    let populated = create_populated_storage(populated_path.path()).await;
    let empty = create_empty_storage(empty_path.path());

    let pair = StoragePair::new(populated.clone(), empty.clone()).with_all_from_a();
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(populated, empty, operations, &status)
        .await
        .unwrap()
        .unwrap();

    let first = std::fs::read_dir(empty_path.path().join("first-calendar"))
        .unwrap()
        .map(|r| r.unwrap())
        .collect::<Vec<_>>();

    // Note that "third-calendar" is not present in the "empty" one.
    assert_eq!(first.len(), 2);

    for item in first {
        let data = std::fs::read_to_string(item.path()).unwrap();
        let found = data.find("First calendar event");
        assert!(found.is_some());
    }

    let second = std::fs::read_dir(empty_path.path().join("second-calendar"))
        .unwrap()
        .map(|r| r.unwrap())
        .collect::<Vec<_>>();
    assert_eq!(second.len(), 2);
    for item in second {
        let data = std::fs::read_to_string(item.path()).unwrap();
        let found = data.find("Second calendar event");
        assert!(found.is_some());
    }

    let third = std::fs::read_dir(empty_path.path().join("third-calendar"))
        .unwrap()
        .map(|r| r.unwrap())
        .collect::<Vec<_>>();
    assert_eq!(third.len(), 1);
    for item in third {
        let data = std::fs::read_to_string(item.path()).unwrap();
        let found = data.find("Third calendar event");
        assert!(found.is_some());
    }

    std::fs::remove_dir_all(populated_path).unwrap();
    std::fs::remove_dir_all(empty_path).unwrap();
}

#[tokio::test]
async fn sync_from_b() {
    let populated_path = tempdir().unwrap();
    let empty_path = tempdir().unwrap();
    let populated = create_populated_storage(populated_path.path()).await;
    let empty = create_empty_storage(empty_path.path());

    let pair = StoragePair::new(populated.clone(), empty.clone()).with_all_from_b();
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(populated, empty, operations, &status)
        .await
        .unwrap()
        .unwrap();

    let _first = std::fs::read_dir(empty_path.path().join("first-calendar")).unwrap_err();
    let _second = std::fs::read_dir(empty_path.path().join("second-calendar")).unwrap_err();
    let _third = std::fs::read_dir(empty_path.path().join("third-calendar")).unwrap_err();

    std::fs::remove_dir_all(populated_path).unwrap();
    std::fs::remove_dir_all(empty_path).unwrap();
}

#[tokio::test]
async fn sync_none() {
    let populated_path = tempdir().unwrap();
    let empty_path = tempdir().unwrap();
    let populated = create_populated_storage(populated_path.path()).await;
    let empty = create_empty_storage(empty_path.path());

    let pair = StoragePair::new(populated.clone(), empty.clone());
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(populated, empty, operations, &status)
        .await
        .unwrap()
        .unwrap();

    let _first = std::fs::read_dir(empty_path.path().join("first-calendar")).unwrap_err();
    let _second = std::fs::read_dir(empty_path.path().join("second-calendar")).unwrap_err();
    let _third = std::fs::read_dir(empty_path.path().join("third-calendar")).unwrap_err();

    std::fs::remove_dir_all(populated_path).unwrap();
    std::fs::remove_dir_all(empty_path).unwrap();
}

#[tokio::test]
async fn sync_deletion_from_a() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_a.create_collection("my-calendar").await.unwrap();
    storage_b.create_collection("my-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    let opts = CreateItemOptions {
        resource_name: Some("hello.ics".to_string()),
    };
    let item_a = storage_a
        .create_item("my-calendar", item, opts.clone())
        .await
        .unwrap();
    storage_b
        .create_item("my-calendar", item, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_b()
        .on_empty(OnEmpty::Sync);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // Both storages in sync with an updated status database.

    storage_a
        .delete_item(&item_a.href, &item_a.etag)
        .await
        .unwrap();

    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_delete_b = ops
        .iter()
        .any(|op| matches!(op, Operation::Item(ItemOp::Delete(d)) if d.side == Side::B));
    assert!(has_delete_b, "Should generate Delete(side: B) operation");

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();
    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    let count = storage_b.get_all_items("my-calendar").await.unwrap().len();
    assert_eq!(count, 0);
}

#[tokio::test]
async fn sync_deletion_from_b() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_a.create_collection("my-calendar").await.unwrap();
    storage_b.create_collection("my-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    let opts = CreateItemOptions {
        resource_name: Some("hello.ics".to_string()),
    };
    storage_a
        .create_item("my-calendar", item, opts.clone())
        .await
        .unwrap();
    let item_b = storage_b
        .create_item("my-calendar", item, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_b()
        .on_empty(OnEmpty::Sync);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // Both storages in sync with an updated status database.

    storage_b
        .delete_item(&item_b.href, &item_b.etag)
        .await
        .unwrap();

    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_delete_a = ops
        .iter()
        .any(|op| matches!(op, Operation::Item(ItemOp::Delete(d)) if d.side == Side::A));
    assert!(has_delete_a, "Should generate Delete(side: A) operation");

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();
    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    let count = storage_a.get_all_items("my-calendar").await.unwrap().len();
    assert_eq!(count, 0);
}

#[tokio::test]
async fn sync_creation_from_a() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_a.create_collection("my-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    storage_a
        .create_item("my-calendar", item, CreateItemOptions::default())
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone()).with_all_from_a();
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_write_in_b = ops
        .iter()
        .any(|op| matches!(op, Operation::Item(ItemOp::Write(w)) if w.target_side == Side::B));
    assert!(
        has_write_in_b,
        "Should generate Write(target_side: B) operation"
    );

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone()).with_all_from_a();
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();
    Executor::new(drop)
        .execute_stream(storage_a, storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    let fetched = &storage_b.get_all_items("my-calendar").await.unwrap()[0];
    assert_eq!(fetched.item.as_str(), item.as_str());
}

#[tokio::test]
async fn sync_creation_from_b() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_b.create_collection("my-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    storage_b
        .create_item("my-calendar", item, CreateItemOptions::default())
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone()).with_all_from_b();
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_write_in_a = ops
        .iter()
        .any(|op| matches!(op, Operation::Item(ItemOp::Write(w)) if w.target_side == Side::A));
    assert!(
        has_write_in_a,
        "Should generate Write(target_side: A) operation"
    );

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone()).with_all_from_b();
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();
    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b, operations, &status)
        .await
        .unwrap()
        .unwrap();

    let fetched = &storage_a.get_all_items("my-calendar").await.unwrap()[0];
    assert_eq!(fetched.item.as_str(), item.as_str());
}

#[tokio::test]
async fn empty_on_empty_skip() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    let first = storage_a.create_collection("first-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    let opts = CreateItemOptions::default();
    let item_ver = storage_a
        .create_item(first.href(), item, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_a()
        .on_empty(OnEmpty::Skip);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // At this point both storages and the status DB are all in sync.

    storage_a
        .delete_item(&item_ver.href, &item_ver.etag)
        .await
        .unwrap();

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    assert!(
        ops.is_empty(),
        "Should generate no operations due to OnEmpty::Skip"
    );
}

#[tokio::test]
async fn empty_on_empty_sync() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    let first = storage_a.create_collection("first-calendar").await.unwrap();
    let item = &minimal_icalendar("First calendar event one")
        .unwrap()
        .into();
    let opts = CreateItemOptions::default();
    let item_ver = storage_a
        .create_item(first.href(), item, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_a()
        .on_empty(OnEmpty::Sync);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // At this point both storages and the status DB are all in sync.

    storage_a
        .delete_item(&item_ver.href, &item_ver.etag)
        .await
        .unwrap();

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_delete_b = ops
        .iter()
        .any(|op| matches!(op, Operation::Item(ItemOp::Delete(d)) if d.side == Side::B));
    assert!(has_delete_b, "Should generate Delete(side: B) operation");
}

#[tokio::test]
async fn empty_on_delete_skip() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    let first = storage_a.create_collection("first-calendar").await.unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_a()
        .with_all_from_b()
        .on_delete(OnDelete::Skip);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // At this point both storages and the status DB are all in sync.

    storage_a.delete_collection(first.href()).await.unwrap();

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    assert!(
        ops.is_empty(),
        "Should generate no operations due to OnDelete::Skip"
    );
}

#[tokio::test]
async fn empty_on_delete_sync() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    let first = storage_a.create_collection("first-calendar").await.unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_all_from_a()
        .with_all_from_b()
        .on_delete(OnDelete::Sync);
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // At this point both storages and the status DB are all in sync.

    storage_a.delete_collection(first.href()).await.unwrap();

    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    let ops: Vec<Operation> = operations.try_collect().await.unwrap();
    let has_collection_delete = ops.iter().any(|op| {
        matches!(op, Operation::Collection(vstorage::sync::operation::CollectionOp::Delete { side, .. }) if *side == Side::B)
    });
    assert!(
        has_collection_delete,
        "Should generate collection Delete operation for side B"
    );
}

/// Test conflict resolution when there's no prior sync (old: None).
#[tokio::test]
async fn conflict_resolution_first_sync() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();

    // Create storage A with an item.
    let storage_a = VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
        .unwrap()
        .build(ItemKind::Calendar);
    let storage_a = Arc::new(storage_a);

    let collection_a = storage_a.create_collection("calendar").await.unwrap();
    let item_a = minimal_icalendar_with_uid("conflict-test-uid", "Event from A")
        .unwrap()
        .into();
    storage_a
        .create_item(collection_a.href(), &item_a, CreateItemOptions::default())
        .await
        .unwrap();

    // Create storage B with an item. Same UID but conflicting content.
    let storage_b = VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
        .unwrap()
        .build(ItemKind::Calendar);
    let storage_b = Arc::new(storage_b);

    let collection_b = storage_b.create_collection("calendar").await.unwrap();
    let item_b = minimal_icalendar_with_uid("conflict-test-uid", "Event from B")
        .unwrap()
        .into();
    storage_b
        .create_item(collection_b.href(), &item_b, CreateItemOptions::default())
        .await
        .unwrap();

    // Setup sync with conflict resolution

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_mapping(SyncedCollection::direct("calendar".parse().unwrap()));

    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();
    let resolved = resolve_conflicts(operations, KeepSideResolver(Side::A));

    // Execute the sync
    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), resolved, &status)
        .await
        .unwrap()
        .unwrap();

    // Side B should now have content from side A.

    let items_b = storage_b.get_all_items(collection_b.href()).await.unwrap();
    assert_eq!(items_b.len(), 1);
    let content_b = items_b[0].item.as_str();
    assert!(content_b.contains("Event from A"),);
    assert!(!content_b.contains("Event from B"),);

    // Side A should still have its original content.

    let items_a = storage_a.get_all_items(collection_a.href()).await.unwrap();
    assert_eq!(items_a.len(), 1);
    let content_a = items_a[0].item.as_str();
    assert!(content_a.contains("Event from A"),);
}

/// Test that sync properly iterates iterating through all items.
#[tokio::test]
async fn sync_continues_after_unchanged_items() {
    let dir_a = tempdir().unwrap();
    let dir_b = tempdir().unwrap();

    let storage_a = Arc::new(
        VdirStorage::builder(dir_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(dir_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    let collection_a = storage_a.create_collection("calendar").await.unwrap();
    let collection_b = storage_b.create_collection("calendar").await.unwrap();

    // Create the same three items on both sides.
    let uid1 = "item-one-uid";
    let uid2 = "item-two-uid";
    let uid3 = "item-three-uid";

    let opts = CreateItemOptions::default();

    let item1_a = minimal_icalendar_with_uid(uid1, "Event One")
        .unwrap()
        .into();
    let item2_a = minimal_icalendar_with_uid(uid2, "Event Two")
        .unwrap()
        .into();
    let item3_a = minimal_icalendar_with_uid(uid3, "Event Three")
        .unwrap()
        .into();

    storage_a
        .create_item(collection_a.href(), &item1_a, opts.clone())
        .await
        .unwrap();
    storage_a
        .create_item(collection_a.href(), &item2_a, opts.clone())
        .await
        .unwrap();
    storage_a
        .create_item(collection_a.href(), &item3_a, opts.clone())
        .await
        .unwrap();

    storage_b
        .create_item(collection_b.href(), &item1_a, opts.clone())
        .await
        .unwrap();
    storage_b
        .create_item(collection_b.href(), &item2_a, opts.clone())
        .await
        .unwrap();
    storage_b
        .create_item(collection_b.href(), &item3_a, opts.clone())
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_mapping(SyncedCollection::direct("calendar".parse().unwrap()));

    // Establish baseline in status database.
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let plan = Plan::new(pair.clone(), Some(status.clone())).await.unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), plan, &status)
        .await
        .unwrap()
        .unwrap();

    // Modify item3 on side A.
    let items_a = storage_a.get_all_items(collection_a.href()).await.unwrap();
    let item3_ver = items_a
        .iter()
        .find(|i| i.item.ident() == uid3)
        .expect("item3 should exist");

    let item3_modified = minimal_icalendar_with_uid(uid3, "Event Three MODIFIED")
        .unwrap()
        .into();
    storage_a
        .update_item(&item3_ver.href, &item3_ver.etag, &item3_modified)
        .await
        .unwrap();

    // Items 1 and 2 are unchanged (no operation), item 3 is modified
    let plan = Plan::new(pair, Some(status.clone())).await.unwrap();

    // Collect all operations to verify the correct ones are generated.
    let operations: Vec<_> = plan.try_collect().await.unwrap();

    // Should have exactly one item operation: Write(target_side: B) for item3.
    assert_eq!(operations.len(), 1);
    match &operations[0] {
        Operation::Item(ItemOp::Write(write)) => {
            assert_eq!(write.target_side, Side::B);
            assert!(
                write
                    .source
                    .data
                    .as_ref()
                    .expect("Write should have data")
                    .as_str()
                    .contains("Event Three MODIFIED"),
                "Write should contain the modified content"
            );
        }
        other => panic!("Expected Write operation, got {:?}", other),
    }

    let plan = Plan::new(
        StoragePair::new(storage_a.clone(), storage_b.clone())
            .with_mapping(SyncedCollection::direct("calendar".parse().unwrap())),
        Some(status.clone()),
    )
    .await
    .unwrap();

    Executor::new(drop)
        .execute_stream(storage_a.clone(), storage_b.clone(), plan, &status)
        .await
        .unwrap()
        .unwrap();

    // Verify item3 is updated on side B.
    let items_b = storage_b.get_all_items(collection_b.href()).await.unwrap();
    let item3_b = items_b
        .iter()
        .find(|i| i.item.ident() == uid3)
        .expect("item3 should exist on side B");

    assert!(item3_b.item.as_str().contains("Event Three MODIFIED"),);
}

/// Syncing an item from A to B retains the original filename.
#[tokio::test]
async fn sync_retains_filename() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_a.create_collection("my-calendar").await.unwrap();

    // Item filename ("custom-name.ics") differs from its UID ("my-uid-123").
    let item = &minimal_icalendar_with_uid("my-uid-123", "Test Event")
        .unwrap()
        .into();
    let opts = CreateItemOptions {
        resource_name: Some("custom-name".to_string()),
    };
    storage_a
        .create_item("my-calendar", item, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone()).with_all_from_a();
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(|err| panic!("Sync error: {err:?}"))
        .execute_stream(storage_a, storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    let items_b = storage_b.get_all_items("my-calendar").await.unwrap();
    assert_eq!(items_b.len(), 1);
    assert!(
        items_b[0].href.ends_with("custom-name.ics"),
        "Expected href ending with 'custom-name.ics', got: {}",
        items_b[0].href
    );
}

/// Syncing items with the same filename but different UIDs falls back to a
/// default name for the colliding item, so both items end up on both sides.
#[tokio::test]
async fn sync_with_filename_collision() {
    let path_a = tempdir().unwrap();
    let path_b = tempdir().unwrap();
    let storage_a = Arc::new(
        VdirStorage::builder(path_a.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );
    let storage_b = Arc::new(
        VdirStorage::builder(path_b.path().to_path_buf().try_into().unwrap())
            .unwrap()
            .build(ItemKind::Calendar),
    );

    storage_a.create_collection("my-calendar").await.unwrap();
    storage_b.create_collection("my-calendar").await.unwrap();

    // Both sides have "custom-name.ics", but with different UIDs.
    let item_a = &minimal_icalendar_with_uid("uid-aaa", "Event A")
        .unwrap()
        .into();
    let item_b = &minimal_icalendar_with_uid("uid-bbb", "Event B")
        .unwrap()
        .into();
    let opts = CreateItemOptions {
        resource_name: Some("custom-name".to_string()),
    };
    storage_a
        .create_item("my-calendar", item_a, opts.clone())
        .await
        .unwrap();
    storage_b
        .create_item("my-calendar", item_b, opts)
        .await
        .unwrap();

    let pair = StoragePair::new(storage_a.clone(), storage_b.clone())
        .with_mapping(SyncedCollection::direct("my-calendar".parse().unwrap()));
    let status = Arc::new(StatusDatabase::open_or_create(":memory:").unwrap());
    let operations = Plan::new(pair, Some(status.clone())).await.unwrap();

    Executor::new(|err| panic!("Sync error: {err:?}"))
        .execute_stream(storage_a.clone(), storage_b.clone(), operations, &status)
        .await
        .unwrap()
        .unwrap();

    // Preferred filename collided; fallback name (based on UID) used.
    let items_a = storage_a.get_all_items("my-calendar").await.unwrap();
    assert_eq!(items_a.len(), 2);
    assert!(items_a.iter().any(|i| i.item.as_str().contains("Event A")));
    assert!(items_a.iter().any(|i| i.item.as_str().contains("Event B")));

    let items_b = storage_b.get_all_items("my-calendar").await.unwrap();
    assert_eq!(items_b.len(), 2);
    assert!(items_b.iter().any(|i| i.item.as_str().contains("Event A")));
    assert!(items_b.iter().any(|i| i.item.as_str().contains("Event B")));
}