ostrya 0.6.0

Pure-Rust async reimplementation of the ostree repository library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
#![forbid(unsafe_code)]

//! Tests of the transfer of the composefs image object,
//! `objects/<xx>/<commit>.cfs`.
//!
//! The tests check these facts:
//!
//! - A local pull, an HTTP pull, a pull through a stream session, a push, and
//!   a one-way stream each copy the image byte for byte, and the copy passes
//!   [`Repo::check_composefs_image`]. A local pull never shares the inode of
//!   the source image.
//! - Each write path refuses an image whose digest is not the key of its
//!   commit, and publishes no ref.
//! - A pull from a source with no image of a commit with the key succeeds.
//!   A pull of a commit with no key, or with a malformed key, a commit-only
//!   pull, and a pull with a subpath request no `.cfs`.
//! - A pull and a push add the image of a commit that the destination holds
//!   with no image. An image that the destination holds is not sent again.
//! - An HTTP pull and a pull through a stream session request each image
//!   after each other object of the pull, also with several fetches in
//!   flight and through a chain of static deltas.
//! - After the first image that the remote does not serve, a pull requests
//!   no image of a held commit. A new commit gets its request all the same.
//! - The receiver refuses an image for a commit with no key, a second image
//!   for one commit, an image for a commit that it neither staged nor holds,
//!   and an image in a session with a server commit. It accepts an image for
//!   a commit that the repository holds. No object count holds an image.
//! - A static delta carries the image of its target in its last part, or as
//!   a fallback entry when the image is large or the delta is inline. An
//!   offline application and a pull store the image from the part, and the
//!   pull requests no `.cfs`. A pull requests a fallback image after the last
//!   part, and an offline application does not need it. Each path refuses an
//!   image whose digest is not the key.
//!
//! The tests of the seal skip if the file system has no fs-verity.

mod common;
#[path = "common/pull.rs"]
mod pull;

use std::io;
use std::os::fd::AsFd;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use common::composefs::{
    DIGEST_KEY, build_owned_source, commit_tree, dict, new_repo, verity_supported,
};
use common::pipe::pipe;
use common::{TmpDir, anyone, is_sealed};
use futures_io::AsyncRead;
use futures_lite::future;
use ostrya::remote::{PullSession, StreamSessionOptions};
use ostrya::verify::PullTrust;
use ostrya::{
    AdvertisedDelta, Checksum, CommitOptions, ComposefsImageState, DeltaOptions, DeltaSuperblock,
    Error, MutableTree, ObjectType, PullFlags, PullOptions, PullStats, Repo, RepoMode,
    SummaryOptions, Value, static_delta_relative_dir,
};
use ostrya_rt::block_on;
use pull::{RepoServer, build_dest, meta_path};

/// The capacity of each pipe of a stream session.
const PIPE_CAP: usize = 64 * 1024;

/// Creates a repository of `mode` under `dir/name` and commits the owned tree
/// of `dir/tree` onto `main`, with the key. If `image` is set, the repository
/// stores the image of the commit. A summary lists `main`.
async fn source(dir: &Path, name: &str, mode: RepoMode, image: bool) -> (Repo, Checksum) {
    let tree = dir.join("tree");
    if !tree.exists() {
        build_owned_source(&tree);
    }
    let repo = new_repo(&dir.join(name), mode, "").await;
    let (commit, _) = commit_tree(&repo, &tree, 1, image, Some("main")).await;
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(1),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    (repo, commit)
}

/// Commits the owned tree of `dir/tree` onto `main` of `repo`, with
/// `metadata` and no image, and writes a summary.
async fn commit_with(repo: &Repo, dir: &Path, metadata: Option<Value>) -> Checksum {
    let tree = dir.join("tree");
    if !tree.exists() {
        build_owned_source(&tree);
    }
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let dfd = std::fs::File::open(&tree).unwrap();
    txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("src"), &mut mtree, None)
        .await
        .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let opts = CommitOptions {
        subject: Some("no image".to_owned()),
        timestamp: Some(2),
        metadata,
        ..CommitOptions::default()
    };
    let commit = txn.write_commit(opts, &root).await.unwrap();
    txn.set_ref("main", Some(&commit));
    txn.commit().await.unwrap();
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(2),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    commit
}

/// Returns the bytes of the stored image of `commit`, or `None`.
fn image_bytes(repo: &Repo, commit: &Checksum) -> Option<Vec<u8>> {
    std::fs::read(repo.composefs_image_path(commit)).ok()
}

/// Asserts that `dest` holds the image of `commit` that `src` holds, byte for
/// byte, and that the image passes the check against the key.
async fn assert_same_image(src: &Repo, dest: &Repo, commit: &Checksum) {
    let expected = image_bytes(src, commit).expect("the source holds the image");
    assert_eq!(image_bytes(dest, commit), Some(expected));
    assert_eq!(
        dest.check_composefs_image(commit).await.unwrap(),
        ComposefsImageState::Valid
    );
}

/// Returns the request path of the image of `commit`.
fn cfs_path(commit: &Checksum) -> String {
    meta_path(commit, "cfs")
}

/// Returns `bytes` with the byte in the middle flipped.
fn flipped(mut bytes: Vec<u8>) -> Vec<u8> {
    let middle = bytes.len() / 2;
    bytes[middle] ^= 0xff;
    bytes
}

/// Writes `bytes` over the stored image of `commit` in `repo`.
fn replace_image(repo: &Repo, commit: &Checksum, bytes: &[u8]) {
    let path = repo.composefs_image_path(commit);
    std::fs::remove_file(&path).unwrap();
    std::fs::write(&path, bytes).unwrap();
}

/// The options of a pull of `main`.
fn main_ref() -> PullOptions {
    PullOptions {
        refs: vec!["main".to_owned()],
        ..PullOptions::default()
    }
}

/// Pulls `opts` from `remote` into `dest` through a stream session, with
/// `Repo::send` as the server of `remote`. After a pull that succeeds, the
/// server must succeed too.
async fn stream_pull(dest: &Repo, remote: &Repo, opts: PullOptions) -> ostrya::Result<PullStats> {
    stream_pull_seen(dest, remote, opts).await.0
}

/// A reader that keeps a copy of each byte that it reads from `inner`.
struct Tap<R> {
    inner: R,
    seen: Arc<Mutex<Vec<u8>>>,
}

impl<R: AsyncRead + Unpin> AsyncRead for Tap<R> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let polled = Pin::new(&mut self.inner).poll_read(cx, buf);
        if let Poll::Ready(Ok(n)) = &polled {
            self.seen.lock().unwrap().extend_from_slice(&buf[..*n]);
        }
        polled
    }
}

/// Returns the paths under `objects/` that the client bytes `bytes` of a
/// stream session request, in order. A `Get` frame holds its path as a
/// string with a NUL at its end.
fn object_requests(bytes: &[u8]) -> Vec<String> {
    let needle = b"objects/";
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(start) = bytes[at..]
        .windows(needle.len())
        .position(|window| window == needle)
    {
        let start = at + start;
        let len = bytes[start..].iter().position(|&b| b == 0).unwrap();
        out.push(String::from_utf8(bytes[start..start + len].to_vec()).unwrap());
        at = start + len;
    }
    out
}

/// Pulls as [`stream_pull`] does, and returns the paths under `objects/`
/// that the pull requested, in order.
async fn stream_pull_seen(
    dest: &Repo,
    remote: &Repo,
    opts: PullOptions,
) -> (ostrya::Result<PullStats>, Vec<String>) {
    let (to_server, server_in) = pipe(PIPE_CAP);
    let (server_out, from_server) = pipe(PIPE_CAP);
    let seen = Arc::new(Mutex::new(Vec::new()));
    let server_in = Tap {
        inner: server_in,
        seen: seen.clone(),
    };
    let (pulled, served) = future::zip(
        async {
            let session =
                PullSession::over_stream(from_server, to_server, StreamSessionOptions::default())
                    .await?;
            dest.pull_with_session(session, PullTrust::unverified(), opts)
                .await
        },
        async move { remote.send(server_in, server_out, &anyone()).await },
    )
    .await;
    // A pull that fails closes the session, and the server can fail on the
    // closed stream.
    if pulled.is_ok() {
        served.unwrap();
    }
    let seen = object_requests(&seen.lock().unwrap());
    (pulled, seen)
}

/// Asserts that `seen`, the object requests of a pull in order, holds a
/// request of each image of `commits`, each after each request of a tree
/// object or a content object. At least `min` tree and content requests go
/// first.
fn assert_images_last(seen: &[String], commits: &[Checksum], min: usize) {
    let images: Vec<usize> = commits
        .iter()
        .map(|commit| {
            seen.iter()
                .position(|path| *path == cfs_path(commit))
                .unwrap_or_else(|| panic!("no request of the image of {commit}: {seen:?}"))
        })
        .collect();
    let tree: Vec<usize> = seen
        .iter()
        .enumerate()
        .filter(|(_, path)| {
            [".filez", ".dirtree", ".dirmeta"]
                .iter()
                .any(|ext| path.ends_with(ext))
        })
        .map(|(at, _)| at)
        .collect();
    assert!(tree.len() >= min, "{seen:?}");
    assert!(
        tree.iter().max() < images.iter().min(),
        "an image before a tree object: {seen:?}"
    );
}

/// Commits the tree of `dir/tree` onto `branch` of `remote` at `timestamp`,
/// with the key and no image, and writes a summary.
async fn commit_keyed(remote: &Repo, dir: &Path, timestamp: u64, branch: &str) -> Checksum {
    let tree = dir.join("tree");
    if !tree.exists() {
        build_owned_source(&tree);
    }
    let (commit, _) = commit_tree(remote, &tree, timestamp, false, Some(branch)).await;
    remote
        .regenerate_summary(&SummaryOptions {
            last_modified: Some(timestamp),
            ..SummaryOptions::default()
        })
        .await
        .unwrap();
    commit
}

/// The options of a pull of `refs`.
fn refs_opts(refs: &[&str]) -> PullOptions {
    PullOptions {
        refs: refs.iter().map(|name| (*name).to_owned()).collect(),
        ..PullOptions::default()
    }
}

// ---------------------------------------------------------------------------
// The local pull.
// ---------------------------------------------------------------------------

/// A local pull copies the image byte for byte between modes, and the copy
/// is an inode of its own. A second pull copies nothing.
#[test]
fn a_local_pull_copies_the_image() {
    let dir = TmpDir::new("cfs-transfer-local");
    block_on(async {
        for (at, (src_mode, dest_mode)) in [
            (RepoMode::BareUser, RepoMode::Archive),
            (RepoMode::Archive, RepoMode::BareUser),
            (RepoMode::BareUser, RepoMode::BareUser),
        ]
        .into_iter()
        .enumerate()
        {
            let (src, commit) = source(dir.path(), &format!("src-{at}"), src_mode, true).await;
            let dest = new_repo(&dir.path().join(format!("dest-{at}")), dest_mode, "").await;
            dest.pull_local(&src, main_ref()).await.unwrap();
            assert_same_image(&src, &dest, &commit).await;
            let ino = |repo: &Repo| {
                std::fs::metadata(repo.composefs_image_path(&commit))
                    .unwrap()
                    .ino()
            };
            assert_ne!(ino(&src), ino(&dest), "{src_mode:?} -> {dest_mode:?}");

            let flags = PullFlags::FORCE_COPY | PullFlags::UNTRUSTED;
            let opts = PullOptions {
                flags,
                ..main_ref()
            };
            let before = ino(&dest);
            dest.pull_local(&src, opts).await.unwrap();
            assert_eq!(ino(&dest), before, "a held image is not copied again");
        }
    });
}

/// A local pull into a repository that seals its objects seals the image.
/// Skips if the file system has no fs-verity.
#[test]
fn a_local_pull_seals_the_image() {
    let dir = TmpDir::new("cfs-transfer-seal");
    if !verity_supported(dir.path()) {
        eprintln!("skipping: the file system has no fs-verity");
        return;
    }
    block_on(async {
        let (src, commit) = source(dir.path(), "src", RepoMode::BareUser, true).await;
        let config = "[ex-integrity]\nfsverity=maybe\n";
        let dest = new_repo(&dir.path().join("dest"), RepoMode::BareUser, config).await;
        dest.pull_local(&src, main_ref()).await.unwrap();
        assert_same_image(&src, &dest, &commit).await;
        assert!(is_sealed(&dest.composefs_image_path(&commit)));
    });
}

/// A local pull refuses a source image whose digest is not the key. It
/// writes no ref and no image.
#[test]
fn a_local_pull_refuses_an_image_that_is_not_the_key() {
    let dir = TmpDir::new("cfs-transfer-local-bad");
    block_on(async {
        let (src, commit) = source(dir.path(), "src", RepoMode::BareUser, true).await;
        let bytes = image_bytes(&src, &commit).unwrap();
        replace_image(&src, &commit, &flipped(bytes));
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;
        let err = dest.pull_local(&src, main_ref()).await.unwrap_err();
        assert!(
            matches!(err, Error::ComposefsDigestMismatch { commit: c, .. } if c == commit),
            "{err:?}"
        );
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert_eq!(image_bytes(&dest, &commit), None);
    });
}

/// A local pull from a source with no image of a commit with the key
/// succeeds. A commit-only pull copies no image. A later pull adds the image
/// of a commit that the destination holds complete with no image.
#[test]
fn a_local_pull_adds_the_image_of_a_held_commit() {
    let dir = TmpDir::new("cfs-transfer-local-held");
    block_on(async {
        let (plain, commit) = source(dir.path(), "plain", RepoMode::BareUser, false).await;
        let (src, same) = source(dir.path(), "src", RepoMode::BareUser, true).await;
        assert_eq!(commit, same, "the image does not change the commit");
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;

        dest.pull_local(&plain, main_ref()).await.unwrap();
        assert_eq!(
            dest.check_composefs_image(&commit).await.unwrap(),
            ComposefsImageState::Absent
        );
        let commit_only = PullOptions {
            flags: PullFlags::COMMIT_ONLY,
            ..main_ref()
        };
        dest.pull_local(&src, commit_only).await.unwrap();
        assert_eq!(image_bytes(&dest, &commit), None);

        dest.pull_local(&src, main_ref()).await.unwrap();
        assert_same_image(&src, &dest, &commit).await;
    });
}

// ---------------------------------------------------------------------------
// The HTTP pull.
// ---------------------------------------------------------------------------

/// An HTTP pull requests the image after each other object, and copies it
/// byte for byte. A second pull requests no image. After the image is gone
/// from the destination, a pull of the held commit requests it again.
#[test]
fn an_http_pull_fetches_the_image_after_the_content() {
    let dir = TmpDir::new("cfs-transfer-http");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let server = RepoServer::start(&dir.path().join("remote"), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        let opts = || PullOptions {
            max_outstanding_fetches: Some(1),
            ..main_ref()
        };

        let stats = dest.pull("origin", opts()).await.unwrap();
        assert_same_image(&remote, &dest, &commit).await;
        let objects: Vec<String> = server
            .seen()
            .into_iter()
            .filter(|path| path.starts_with("objects/"))
            .collect();
        assert_eq!(objects.last(), Some(&cfs_path(&commit)), "{objects:?}");
        assert_eq!(server.requests_for(&cfs_path(&commit)), 1);
        // The image adds its bytes alone.
        let size = image_bytes(&remote, &commit).unwrap().len() as u64;
        assert!(stats.bytes_transferred > size);

        server.forget();
        dest.pull("origin", opts()).await.unwrap();
        assert_eq!(server.requests_for(&cfs_path(&commit)), 0);

        std::fs::remove_file(dest.composefs_image_path(&commit)).unwrap();
        server.forget();
        dest.pull("origin", opts()).await.unwrap();
        assert_eq!(server.statuses_for(&cfs_path(&commit)), [200]);
        assert_same_image(&remote, &dest, &commit).await;
    });
}

/// With the default number of fetches in flight, an HTTP pull requests the
/// image after each dirtree, dirmeta, and content object of a tree with a
/// nested directory and several files.
#[test]
fn an_http_pull_with_several_fetches_requests_the_image_last() {
    let dir = TmpDir::new("cfs-transfer-http-order");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let server = RepoServer::start(&dir.path().join("remote"), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        dest.pull("origin", main_ref()).await.unwrap();
        assert_same_image(&remote, &dest, &commit).await;
        // Two dirtrees, two dirmetas, and five content objects.
        assert_images_last(&server.seen(), &[commit], 9);
    });
}

/// A pull through a chain of static deltas requests the image of each
/// commit of the chain after each part of the last step and each object
/// of the tree walk.
#[test]
fn a_delta_chain_pull_requests_the_images_last() {
    let dir = TmpDir::new("cfs-transfer-http-chain");
    block_on(async {
        let remote = new_repo(&dir.path().join("remote"), RepoMode::Archive, "").await;
        let mut commits = Vec::new();
        for (at, marker) in [&b"a\n"[..], b"b\n", b"c\n"].into_iter().enumerate() {
            let base = dir.path().join(format!("tree-{at}"));
            build_owned_source(&base);
            std::fs::write(base.join("src/marker"), marker).unwrap();
            let (commit, _) = commit_tree(&remote, &base, at as u64 + 1, true, Some("main")).await;
            commits.push(commit);
        }
        // A delta carries the image of its target in a part, unless the image
        // is a fallback. At this threshold each image is a fallback, so the
        // pull requests each image.
        let smallest = commits
            .iter()
            .map(|commit| image_bytes(&remote, commit).unwrap().len() as u64)
            .min()
            .unwrap();
        let mut list = Vec::new();
        for pair in commits.windows(2) {
            let opts = DeltaOptions {
                timestamp: Some(1),
                min_fallback_size: smallest,
                ..DeltaOptions::default()
            };
            remote
                .generate_static_delta(Some(&pair[0]), &pair[1], &opts)
                .await
                .unwrap();
            let dir = static_delta_relative_dir(Some(&pair[0]), &pair[1]);
            let bytes = std::fs::read(remote.path().join(format!("{dir}/superblock"))).unwrap();
            list.push(AdvertisedDelta {
                from: Some(pair[0]),
                to: pair[1],
                superblock: Checksum::sha256(&bytes),
            });
        }
        let server = RepoServer::start(remote.path(), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        let first = PullOptions {
            refs: vec![commits[0].to_hex()],
            ..PullOptions::default()
        };
        dest.pull_local(&remote, first).await.unwrap();

        let opts = PullOptions {
            static_deltas: Some(list),
            ..main_ref()
        };
        dest.pull("origin", opts).await.unwrap();
        let seen = server.seen();
        let last_part = seen
            .iter()
            .rposition(|path| path.starts_with("deltas/"))
            .unwrap_or_else(|| panic!("no delta request: {seen:?}"));
        let first_image = seen
            .iter()
            .position(|path| path.ends_with(".cfs"))
            .unwrap_or_else(|| panic!("no image request: {seen:?}"));
        assert!(last_part < first_image, "{seen:?}");
        let objects: Vec<String> = seen
            .into_iter()
            .filter(|path| path.starts_with("objects/"))
            .collect();
        assert_images_last(&objects, &commits[1..], 0);
        for commit in &commits[1..] {
            assert_same_image(&remote, &dest, commit).await;
        }
    });
}

/// A remote that serves no image answers 404 to the first image of a held
/// commit, and the pull requests no other image of a held commit. A new
/// commit gets its own request, and after its 404 the held commits get
/// none.
#[test]
fn an_http_pull_stops_the_held_images_after_a_404() {
    let dir = TmpDir::new("cfs-transfer-http-held-absent");
    block_on(async {
        let remote = new_repo(&dir.path().join("remote"), RepoMode::Archive, "").await;
        let a = commit_keyed(&remote, dir.path(), 1, "a").await;
        let b = commit_keyed(&remote, dir.path(), 2, "b").await;
        let server = RepoServer::start(remote.path(), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        let held_requests = |server: &RepoServer| {
            server.requests_for(&cfs_path(&a)) + server.requests_for(&cfs_path(&b))
        };

        dest.pull("origin", refs_opts(&["a", "b"])).await.unwrap();
        assert_eq!(
            held_requests(&server),
            2,
            "new commits: {:?}",
            server.seen()
        );

        server.forget();
        dest.pull("origin", refs_opts(&["a", "b"])).await.unwrap();
        assert_eq!(held_requests(&server), 1, "{:?}", server.seen());

        let c = commit_keyed(&remote, dir.path(), 3, "c").await;
        server.forget();
        dest.pull("origin", refs_opts(&["a", "b", "c"]))
            .await
            .unwrap();
        assert_eq!(server.statuses_for(&cfs_path(&c)), [404]);
        assert_eq!(held_requests(&server), 0, "{:?}", server.seen());
        assert_eq!(dest.resolve_rev("origin:c", false).await.unwrap(), Some(c));
    });
}

/// An HTTP pull refuses an image whose digest is not the key, and fetches it
/// one time. It writes no ref and no image.
#[test]
fn an_http_pull_refuses_an_image_that_is_not_the_key() {
    let dir = TmpDir::new("cfs-transfer-http-bad");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let server = RepoServer::start(&dir.path().join("remote"), false).await;
        server.tamper(
            &cfs_path(&commit),
            flipped(image_bytes(&remote, &commit).unwrap()),
        );
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        let err = dest.pull("origin", main_ref()).await.unwrap_err();
        assert!(
            matches!(err, Error::ComposefsDigestMismatch { .. }),
            "{err:?}"
        );
        assert_eq!(server.requests_for(&cfs_path(&commit)), 1);
        pull::assert_nothing_published(&dest).await;
        assert_eq!(image_bytes(&dest, &commit), None);
    });
}

/// A remote that serves no image of a commit with the key answers 404, and
/// the pull succeeds with no image.
#[test]
fn an_http_pull_from_a_remote_with_no_image_succeeds() {
    let dir = TmpDir::new("cfs-transfer-http-absent");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, false).await;
        let server = RepoServer::start(&dir.path().join("remote"), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        dest.pull("origin", main_ref()).await.unwrap();
        assert_eq!(server.statuses_for(&cfs_path(&commit)), [404]);
        assert_eq!(
            dest.resolve_rev("origin:main", false).await.unwrap(),
            Some(commit)
        );
        assert_eq!(
            dest.check_composefs_image(&commit).await.unwrap(),
            ComposefsImageState::Absent
        );
        let _ = remote;
    });
}

/// A pull requests no `.cfs` for a commit with no key, for a commit with a
/// malformed key, in a commit-only pull, and in a pull with a subpath.
#[test]
fn an_http_pull_requests_no_image_without_a_key_or_a_whole_tree() {
    let dir = TmpDir::new("cfs-transfer-http-none");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let server = RepoServer::start(&dir.path().join("remote"), false).await;
        let any_cfs = |server: &RepoServer| server.seen().iter().any(|p| p.ends_with(".cfs"));

        for (at, opts) in [
            PullOptions {
                flags: PullFlags::COMMIT_ONLY,
                ..main_ref()
            },
            PullOptions {
                subpaths: vec!["/sub".to_owned()],
                ..main_ref()
            },
        ]
        .into_iter()
        .enumerate()
        {
            let base = dir.path().join(format!("partial-{at}"));
            std::fs::create_dir_all(&base).unwrap();
            let dest = build_dest(&base, RepoMode::BareUser, &server.url(), "").await;
            server.forget();
            dest.pull("origin", opts).await.unwrap();
            assert!(!any_cfs(&server), "{:?}", server.seen());
            assert_eq!(image_bytes(&dest, &commit), None);
        }

        for (at, metadata) in [None, Some(dict(DIGEST_KEY, "s", Value::Str("x".into())))]
            .into_iter()
            .enumerate()
        {
            let other = commit_with(&remote, dir.path(), metadata).await;
            let base = dir.path().join(format!("keyless-{at}"));
            std::fs::create_dir_all(&base).unwrap();
            let dest = build_dest(&base, RepoMode::BareUser, &server.url(), "").await;
            server.forget();
            dest.pull("origin", main_ref()).await.unwrap();
            assert_eq!(
                dest.resolve_rev("origin:main", false).await.unwrap(),
                Some(other)
            );
            assert!(!any_cfs(&server), "{:?}", server.seen());
        }
    });
}

// ---------------------------------------------------------------------------
// The pull through a stream session.
// ---------------------------------------------------------------------------

/// A pull through a stream session copies the image that the archive view of
/// a `bare-user` remote serves as stored. A remote with no image leaves the
/// commit with none, and the pull succeeds.
#[test]
fn a_stream_pull_copies_the_image() {
    let dir = TmpDir::new("cfs-transfer-stream");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::BareUser, true).await;
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;
        stream_pull(&dest, &remote, main_ref()).await.unwrap();
        assert_same_image(&remote, &dest, &commit).await;

        let (plain, same) = source(dir.path(), "plain", RepoMode::BareUser, false).await;
        assert_eq!(same, commit);
        let empty = new_repo(&dir.path().join("empty"), RepoMode::Archive, "").await;
        stream_pull(&empty, &plain, main_ref()).await.unwrap();
        assert_eq!(image_bytes(&empty, &commit), None);
    });
}

/// A pull through a stream session requests the image after each dirtree,
/// dirmeta, and content object.
#[test]
fn a_stream_pull_requests_the_image_last() {
    let dir = TmpDir::new("cfs-transfer-stream-order");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::BareUser, true).await;
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;
        let (pulled, seen) = stream_pull_seen(&dest, &remote, main_ref()).await;
        pulled.unwrap();
        assert_same_image(&remote, &dest, &commit).await;
        assert_images_last(&seen, &[commit], 9);
    });
}

/// A pull through a stream session from a remote with no image requests one
/// image for the held commits. A new commit gets its own request.
#[test]
fn a_stream_pull_stops_the_held_images_after_an_absent_image() {
    let dir = TmpDir::new("cfs-transfer-stream-held-absent");
    block_on(async {
        let remote = new_repo(&dir.path().join("remote"), RepoMode::BareUser, "").await;
        let a = commit_keyed(&remote, dir.path(), 1, "a").await;
        let b = commit_keyed(&remote, dir.path(), 2, "b").await;
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;
        let count = |seen: &[String], commits: &[Checksum]| {
            seen.iter()
                .filter(|path| commits.iter().any(|commit| **path == cfs_path(commit)))
                .count()
        };

        let (pulled, seen) = stream_pull_seen(&dest, &remote, refs_opts(&["a", "b"])).await;
        pulled.unwrap();
        assert_eq!(count(&seen, &[a, b]), 2, "{seen:?}");

        let (pulled, seen) = stream_pull_seen(&dest, &remote, refs_opts(&["a", "b"])).await;
        pulled.unwrap();
        assert_eq!(count(&seen, &[a, b]), 1, "{seen:?}");

        let c = commit_keyed(&remote, dir.path(), 3, "c").await;
        let (pulled, seen) = stream_pull_seen(&dest, &remote, refs_opts(&["a", "b", "c"])).await;
        pulled.unwrap();
        assert_eq!(count(&seen, &[c]), 1, "{seen:?}");
        assert_eq!(count(&seen, &[a, b]), 0, "{seen:?}");
    });
}

/// A pull through a stream session into a repository that seals its objects
/// seals the image that it streams. Skips if the file system has no
/// fs-verity.
#[test]
fn a_stream_pull_seals_the_image() {
    let dir = TmpDir::new("cfs-transfer-stream-seal");
    if !verity_supported(dir.path()) {
        eprintln!("skipping: the file system has no fs-verity");
        return;
    }
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::BareUser, true).await;
        let config = "[ex-integrity]\nfsverity=yes\n";
        let dest = new_repo(&dir.path().join("dest"), RepoMode::BareUser, config).await;
        stream_pull(&dest, &remote, main_ref()).await.unwrap();
        assert_same_image(&remote, &dest, &commit).await;
        assert!(is_sealed(&dest.composefs_image_path(&commit)));
    });
}

/// A pull through a stream session refuses an image whose digest is not the
/// key.
#[test]
fn a_stream_pull_refuses_an_image_that_is_not_the_key() {
    let dir = TmpDir::new("cfs-transfer-stream-bad");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::BareUser, true).await;
        let bytes = image_bytes(&remote, &commit).unwrap();
        replace_image(&remote, &commit, &flipped(bytes));
        let dest = new_repo(&dir.path().join("dest"), RepoMode::Archive, "").await;
        let err = stream_pull(&dest, &remote, main_ref()).await.unwrap_err();
        assert!(
            matches!(err, Error::ComposefsDigestMismatch { .. }),
            "{err:?}"
        );
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert_eq!(image_bytes(&dest, &commit), None);
    });
}

// ---------------------------------------------------------------------------
// The static delta.
// ---------------------------------------------------------------------------

/// Builds the owned tree under `dir/name` with `marker` in `src/marker`, and
/// returns the directory that holds `src`.
fn marked_tree(dir: &Path, name: &str, marker: &[u8]) -> PathBuf {
    let base = dir.join(name);
    build_owned_source(&base);
    std::fs::write(base.join("src/marker"), marker).unwrap();
    base
}

/// Generates the delta from `from` to `to` in `repo` under `deltas/` with
/// `opts` and a fixed timestamp, writes a summary, and returns the delta
/// directory.
async fn publish_delta(
    repo: &Repo,
    from: Option<&Checksum>,
    to: &Checksum,
    opts: DeltaOptions,
) -> PathBuf {
    let relative = repo
        .generate_static_delta(
            from,
            to,
            &DeltaOptions {
                timestamp: Some(1),
                ..opts
            },
        )
        .await
        .unwrap();
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(1),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    repo.path().join(relative)
}

/// Returns each image entry of the superblock in `dir`: the part that lists
/// the image, or `None` for a fallback entry, with the commit that the entry
/// names.
async fn image_entries(dir: &Path) -> Vec<(Option<usize>, Checksum)> {
    let sb = DeltaSuperblock::read(&dir.join("superblock"))
        .await
        .unwrap();
    let mut out = Vec::new();
    for (index, part) in sb.parts().iter().enumerate() {
        for (ty, checksum) in part.objects() {
            if *ty == ObjectType::ComposefsImage {
                out.push((Some(index), *checksum));
            }
        }
    }
    for fallback in sb.fallbacks() {
        if fallback.object_type() == ObjectType::ComposefsImage {
            out.push((None, *fallback.checksum()));
        }
    }
    out
}

/// The options of a pull of `main` that takes a static delta.
fn delta_ref() -> PullOptions {
    PullOptions {
        require_static_deltas: true,
        ..main_ref()
    }
}

/// A delta from scratch and a delta from one commit to the next each carry
/// the image of their target in the last part, as the last object. An
/// offline application into `bare-user` and into `archive` stores each image
/// byte for byte. The statistics of each part read. An image that the
/// destination holds is trusted by its presence, and an application leaves
/// it as it is.
#[test]
fn a_delta_carries_the_image_of_its_target() {
    let dir = TmpDir::new("cfs-delta-offline");
    block_on(async {
        let src = new_repo(&dir.path().join("src"), RepoMode::Archive, "").await;
        let tree_a = marked_tree(dir.path(), "tree-a", b"a\n");
        let (a, _) = commit_tree(&src, &tree_a, 1, true, Some("main")).await;
        let tree_b = marked_tree(dir.path(), "tree-b", b"b\n");
        let (b, _) = commit_tree(&src, &tree_b, 2, true, Some("main")).await;
        let scratch = publish_delta(&src, None, &a, DeltaOptions::default()).await;
        let next = publish_delta(&src, Some(&a), &b, DeltaOptions::default()).await;

        for (delta, to) in [(&scratch, a), (&next, b)] {
            let sb = DeltaSuperblock::read(&delta.join("superblock"))
                .await
                .unwrap();
            let last = sb.parts().len() - 1;
            assert_eq!(image_entries(delta).await, [(Some(last), to)]);
            assert_eq!(
                sb.parts()[last].objects().last(),
                Some(&(ObjectType::ComposefsImage, to))
            );
            for index in 0..sb.parts().len() {
                let stats = sb.part_stats(index, delta).await.unwrap();
                assert!(stats.ops.open_splice_close > 0);
            }
        }

        for mode in [RepoMode::BareUser, RepoMode::Archive] {
            let dest = new_repo(&dir.path().join(format!("{mode:?}")), mode, "").await;
            assert_eq!(dest.apply_static_delta_offline(&scratch).await.unwrap(), a);
            assert_same_image(&src, &dest, &a).await;
            assert_eq!(dest.apply_static_delta_offline(&next).await.unwrap(), b);
            assert_same_image(&src, &dest, &b).await;

            let wrong = flipped(image_bytes(&dest, &b).unwrap());
            replace_image(&dest, &b, &wrong);
            dest.apply_static_delta_offline(&next).await.unwrap();
            assert_eq!(image_bytes(&dest, &b), Some(wrong), "{mode:?}");
        }
    });
}

/// With fallbacks off and the default chunk size, the image is a packed
/// entry of the type 100 in the last part.
#[test]
fn an_image_is_packed_with_fallbacks_off() {
    let dir = TmpDir::new("cfs-delta-no-fallback");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let opts = DeltaOptions {
            min_fallback_size: 0,
            ..DeltaOptions::default()
        };
        let delta = publish_delta(&remote, None, &commit, opts).await;
        let sb = DeltaSuperblock::read(&delta.join("superblock"))
            .await
            .unwrap();
        let last = sb.parts().len() - 1;
        assert_eq!(image_entries(&delta).await, [(Some(last), commit)]);
        assert_eq!(
            sb.parts()[last].objects().last(),
            Some(&(ObjectType::ComposefsImage, commit))
        );
    });
}

/// An inline delta lists the image as a fallback entry of the type 100, and
/// no part lists the image.
#[test]
fn an_inline_delta_lists_the_image_as_a_fallback() {
    let dir = TmpDir::new("cfs-delta-inline");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let size = image_bytes(&remote, &commit).unwrap().len() as u64;
        let opts = DeltaOptions {
            inline: true,
            ..DeltaOptions::default()
        };
        let delta = publish_delta(&remote, None, &commit, opts).await;
        assert_eq!(image_entries(&delta).await, [(None, commit)]);
        let sb = DeltaSuperblock::read(&delta.join("superblock"))
            .await
            .unwrap();
        assert!(!sb.parts().is_empty());
        let fallback = sb.fallbacks().last().unwrap();
        assert_eq!(fallback.object_type(), ObjectType::ComposefsImage);
        assert_eq!(
            (fallback.size(), fallback.uncompressed_size()),
            (size, size)
        );
    });
}

/// An HTTP pull, a pull through a stream session, and a local pull that take
/// a delta store the image from its part. The remote holds no stored image
/// after the generation, so each pull can take the image from the part
/// alone. The HTTP pull and the stream pull request no `.cfs`.
#[test]
fn a_delta_pull_takes_the_image_from_the_part() {
    let dir = TmpDir::new("cfs-delta-pull");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        publish_delta(&remote, None, &commit, DeltaOptions::default()).await;
        let expected = image_bytes(&remote, &commit).unwrap();
        std::fs::remove_file(remote.composefs_image_path(&commit)).unwrap();
        let holds_image = async |dest: &Repo| {
            assert_eq!(image_bytes(dest, &commit).as_ref(), Some(&expected));
            assert_eq!(
                dest.check_composefs_image(&commit).await.unwrap(),
                ComposefsImageState::Valid
            );
        };
        let server = RepoServer::start(remote.path(), false).await;

        let http = dir.path().join("http");
        std::fs::create_dir(&http).unwrap();
        let dest = build_dest(&http, RepoMode::BareUser, &server.url(), "").await;
        dest.pull("origin", delta_ref()).await.unwrap();
        let seen = server.seen();
        assert!(seen.iter().any(|p| p.starts_with("deltas/")), "{seen:?}");
        assert!(!seen.iter().any(|p| p.ends_with(".cfs")), "{seen:?}");
        holds_image(&dest).await;

        let dest = new_repo(&dir.path().join("stream"), RepoMode::BareUser, "").await;
        let (pulled, seen) = stream_pull_seen(&dest, &remote, delta_ref()).await;
        pulled.unwrap();
        assert!(!seen.iter().any(|p| p.ends_with(".cfs")), "{seen:?}");
        holds_image(&dest).await;

        let dest = new_repo(&dir.path().join("local"), RepoMode::Archive, "").await;
        dest.pull_local(&remote, delta_ref()).await.unwrap();
        holds_image(&dest).await;
    });
}

/// An image of the fallback size or larger is a fallback entry. So is an
/// image larger than the chunk size, also when fallbacks are off. An offline
/// application does not need the image. An HTTP pull requests the image
/// after the last part.
#[test]
fn a_large_image_goes_as_a_fallback() {
    let dir = TmpDir::new("cfs-delta-fallback");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let size = image_bytes(&remote, &commit).unwrap().len() as u64;
        let server = RepoServer::start(remote.path(), false).await;
        for (at, opts) in [
            DeltaOptions {
                min_fallback_size: size,
                ..DeltaOptions::default()
            },
            DeltaOptions {
                min_fallback_size: 0,
                max_chunk_size: size - 1,
                ..DeltaOptions::default()
            },
        ]
        .into_iter()
        .enumerate()
        {
            let delta = publish_delta(&remote, None, &commit, opts).await;
            assert_eq!(image_entries(&delta).await, [(None, commit)], "{at}");
            let sb = DeltaSuperblock::read(&delta.join("superblock"))
                .await
                .unwrap();
            let fallback = sb.fallbacks().last().unwrap();
            assert_eq!(
                (fallback.size(), fallback.uncompressed_size()),
                (size, size)
            );

            let offline = new_repo(
                &dir.path().join(format!("offline-{at}")),
                RepoMode::Archive,
                "",
            )
            .await;
            offline.apply_static_delta_offline(&delta).await.unwrap();
            assert_eq!(
                offline.check_composefs_image(&commit).await.unwrap(),
                ComposefsImageState::Absent
            );

            let base = dir.path().join(format!("http-{at}"));
            std::fs::create_dir(&base).unwrap();
            let dest = build_dest(&base, RepoMode::BareUser, &server.url(), "").await;
            server.forget();
            dest.pull("origin", delta_ref()).await.unwrap();
            let seen = server.seen();
            let last_part = seen
                .iter()
                .rposition(|path| path.starts_with("deltas/"))
                .unwrap_or_else(|| panic!("no delta request: {seen:?}"));
            let image = seen
                .iter()
                .position(|path| *path == cfs_path(&commit))
                .unwrap_or_else(|| panic!("no image request: {seen:?}"));
            assert!(last_part < image, "{seen:?}");
            assert_same_image(&remote, &dest, &commit).await;
        }
    });
}

/// A delta that carries an image whose digest is not the key is refused.
/// The offline application stores no commit, and an HTTP pull and a stream
/// pull write no ref and no image.
#[test]
fn a_corrupt_image_in_a_delta_is_refused() {
    let dir = TmpDir::new("cfs-delta-corrupt");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let bytes = image_bytes(&remote, &commit).unwrap();
        replace_image(&remote, &commit, &flipped(bytes));
        let delta = publish_delta(&remote, None, &commit, DeltaOptions::default()).await;
        assert_eq!(image_entries(&delta).await, [(Some(0), commit)]);
        let mismatch = |err: Error| {
            assert!(
                matches!(err, Error::ComposefsDigestMismatch { commit: c, .. } if c == commit),
                "{err:?}"
            );
        };

        let offline = new_repo(&dir.path().join("offline"), RepoMode::BareUser, "").await;
        mismatch(
            offline
                .apply_static_delta_offline(&delta)
                .await
                .unwrap_err(),
        );
        assert!(
            !offline
                .has_object(ObjectType::Commit, &commit)
                .await
                .unwrap()
        );
        assert_eq!(image_bytes(&offline, &commit), None);

        let server = RepoServer::start(remote.path(), false).await;
        let dest = build_dest(dir.path(), RepoMode::BareUser, &server.url(), "").await;
        mismatch(dest.pull("origin", delta_ref()).await.unwrap_err());
        pull::assert_nothing_published(&dest).await;
        assert_eq!(image_bytes(&dest, &commit), None);

        let dest = new_repo(&dir.path().join("stream"), RepoMode::Archive, "").await;
        mismatch(stream_pull(&dest, &remote, delta_ref()).await.unwrap_err());
        assert!(dest.list_refs(None).await.unwrap().is_empty());
        assert_eq!(image_bytes(&dest, &commit), None);
    });
}

/// A pull with a subpath that takes a delta stores the image that a part
/// carries. It requests no image that a fallback entry names, and leaves the
/// commit with no image.
#[test]
fn a_subpath_delta_pull_keeps_a_part_image_and_skips_a_fallback_image() {
    let dir = TmpDir::new("cfs-delta-subpath");
    block_on(async {
        let (remote, commit) = source(dir.path(), "remote", RepoMode::Archive, true).await;
        let size = image_bytes(&remote, &commit).unwrap().len() as u64;
        let server = RepoServer::start(remote.path(), false).await;
        let opts = || PullOptions {
            subpaths: vec!["/sub".to_owned()],
            ..delta_ref()
        };

        publish_delta(&remote, None, &commit, DeltaOptions::default()).await;
        let base = dir.path().join("part");
        std::fs::create_dir(&base).unwrap();
        let dest = build_dest(&base, RepoMode::BareUser, &server.url(), "").await;
        dest.pull("origin", opts()).await.unwrap();
        assert_same_image(&remote, &dest, &commit).await;

        let fallback = DeltaOptions {
            min_fallback_size: size,
            ..DeltaOptions::default()
        };
        let delta = publish_delta(&remote, None, &commit, fallback).await;
        assert_eq!(image_entries(&delta).await, [(None, commit)]);
        let base = dir.path().join("fallback");
        std::fs::create_dir(&base).unwrap();
        let dest = build_dest(&base, RepoMode::BareUser, &server.url(), "").await;
        server.forget();
        dest.pull("origin", opts()).await.unwrap();
        let seen = server.seen();
        assert!(seen.iter().any(|p| p.starts_with("deltas/")), "{seen:?}");
        assert!(!seen.iter().any(|p| p.ends_with(".cfs")), "{seen:?}");
        assert_eq!(image_bytes(&dest, &commit), None);
    });
}

// ---------------------------------------------------------------------------
// The push, the one-way stream, and the receiver.
// ---------------------------------------------------------------------------

#[cfg(all(feature = "push", feature = "receive"))]
mod push {
    use futures_lite::future::zip;
    use ostrya::remote::proto::{Message, ServerCommit};
    use ostrya::remote::{Encoding, ErrorCode, Expected, PushOutcome, RefUpdate};
    use ostrya::{ExportStreamOptions, ObjectType, RepoPushOptions, StreamPolicy};

    use super::common::receive::{
        Obj, assert_nothing_published, commit_objects, policy_allowing, returned_code, session,
    };
    use super::common::{TmpDir, file_inventory};
    use super::*;

    /// Pushes `main` from `client` into `server` over two pipes, under a
    /// policy that allows each write.
    async fn push(client: &Repo, server: &Repo) -> PushOutcome {
        let (client_out, server_in) = pipe(PIPE_CAP);
        let (server_out, client_in) = pipe(PIPE_CAP);
        let policy = policy_allowing(&["w:**"]);
        let opts = RepoPushOptions {
            refspecs: vec!["main".to_owned()],
            ..RepoPushOptions::default()
        };
        let (received, pushed) = zip(
            server.receive(server_in, server_out, &policy),
            client.push_over_stream(client_in, client_out, opts),
        )
        .await;
        received.unwrap();
        pushed.unwrap()
    }

    fn update(name: &str, expected: Expected, new: Checksum) -> RefUpdate {
        RefUpdate {
            name: name.into(),
            expected,
            new: Some(new),
        }
    }

    /// A push sends the image with its commit, byte for byte. A second push
    /// sends no object. After the server loses the image, a push of the
    /// commit that the server holds sends the image alone, and no object
    /// count holds it.
    #[test]
    fn a_push_sends_the_image_once() {
        let dir = TmpDir::new("cfs-transfer-push");
        block_on(async {
            let (client, commit) = source(dir.path(), "client", RepoMode::BareUser, true).await;
            let server = new_repo(&dir.path().join("server"), RepoMode::Archive, "").await;
            let size = image_bytes(&client, &commit).unwrap().len() as u64;

            push(&client, &server).await;
            assert_same_image(&client, &server, &commit).await;

            let outcome = push(&client, &server).await;
            assert_eq!(outcome.stats.objects_needed, 0);
            assert_eq!(outcome.stats.objects_sent, 0);
            assert_eq!(outcome.stats.payload_bytes, 0);

            std::fs::remove_file(server.composefs_image_path(&commit)).unwrap();
            let outcome = push(&client, &server).await;
            assert_eq!(outcome.stats.objects_needed, 0);
            assert_eq!(outcome.stats.objects_sent, 0);
            assert_eq!(outcome.stats.payload_bytes, size);
            assert_same_image(&client, &server, &commit).await;
        });
    }

    /// A one-way stream carries the image of each new commit, and the
    /// receiver stores it byte for byte.
    #[test]
    fn a_one_way_stream_carries_the_image() {
        let dir = TmpDir::new("cfs-transfer-one-way");
        block_on(async {
            let (client, commit) = source(dir.path(), "client", RepoMode::BareUser, true).await;
            let server = new_repo(&dir.path().join("server"), RepoMode::Archive, "").await;
            let mut bytes = Vec::new();
            let opts = ExportStreamOptions {
                updates: vec![update("main", Expected::Absent, commit)],
                ..ExportStreamOptions::default()
            };
            let stats = client.export_stream(&mut bytes, opts).await.unwrap();
            let size = image_bytes(&client, &commit).unwrap().len() as u64;
            assert!(stats.payload_bytes > size);
            server
                .receive_stream(&bytes[..], &StreamPolicy::default())
                .await
                .unwrap();
            assert_same_image(&client, &server, &commit).await;
        });
    }

    /// The objects of `commit` in the archive repository `repo`, with the
    /// commit last, and the image of the commit after them if `image` is
    /// given.
    fn objects(repo: &Repo, commit: &Checksum, image: Option<Vec<u8>>) -> Vec<Obj> {
        let mut objects = commit_objects(repo.path(), commit, Encoding::Raw);
        if let Some(bytes) = image {
            objects.push(Obj {
                ty: ObjectType::ComposefsImage,
                checksum: *commit,
                encoding: Encoding::Raw,
                bytes,
            });
        }
        objects
    }

    /// Runs a push session that sends `objects` and a `Commit` of `main` to
    /// `new` into `server`, and returns the result of the server and the
    /// `ObjectsReply` counts.
    fn send_objects(
        server: &Repo,
        objects: &[Obj],
        expected: Expected,
        new: Checksum,
    ) -> (ostrya::Result<ostrya::ReceiveReport>, Option<(u32, u64)>) {
        session(
            server,
            &policy_allowing(&["w:**"]),
            |mut client| async move {
                client.hello_reply(&["main"]).await;
                for o in objects {
                    if client
                        .object(o.ty, o.checksum, o.encoding, &o.bytes)
                        .await
                        .is_err()
                    {
                        return None;
                    }
                }
                if client.send(&Message::ObjectsEnd).await.is_err() {
                    return None;
                }
                let reply = match client.recv().await {
                    Some(Message::ObjectsReply(reply)) => reply,
                    _ => return None,
                };
                let _ = client
                    .commit(vec![update("main", expected, new)], false)
                    .await;
                let _ = client.commit_reply().await;
                Some((reply.objects, reply.payload_bytes))
            },
        )
    }

    /// The receiver refuses an image whose digest is not the key with
    /// `checksum-mismatch`, and an image for a commit with no key with
    /// `protocol`. Each refusal publishes nothing.
    #[test]
    fn the_receiver_refuses_an_image_that_is_not_the_key() {
        let dir = TmpDir::new("cfs-transfer-receive-bad");
        let (src, commit) = block_on(source(dir.path(), "src", RepoMode::Archive, true));
        let image = image_bytes(&src, &commit).unwrap();
        let keyless = block_on(commit_with(&src, dir.path(), None));

        for (at, (target, bytes, code)) in [
            (commit, flipped(image.clone()), ErrorCode::ChecksumMismatch),
            (keyless, image, ErrorCode::Protocol),
        ]
        .into_iter()
        .enumerate()
        {
            let server = block_on(new_repo(
                &dir.path().join(format!("server-{at}")),
                RepoMode::Archive,
                "",
            ));
            let before = file_inventory(server.path(), "objects");
            let objects = objects(&src, &target, Some(bytes));
            let (result, _) = send_objects(&server, &objects, Expected::Absent, target);
            assert_eq!(returned_code(&result), Some(code), "{result:?}");
            assert_nothing_published(&server, &before);
        }
    }

    /// A second image for one commit is `protocol`, and the session
    /// publishes nothing.
    #[test]
    fn the_receiver_refuses_a_second_image() {
        let dir = TmpDir::new("cfs-transfer-receive-twice");
        let (src, commit) = block_on(source(dir.path(), "src", RepoMode::Archive, true));
        let image = image_bytes(&src, &commit).unwrap();
        let server = block_on(new_repo(&dir.path().join("server"), RepoMode::Archive, ""));
        let before = file_inventory(server.path(), "objects");
        let mut objects = objects(&src, &commit, Some(image));
        objects.push(objects.last().unwrap().clone());
        let (result, _) = send_objects(&server, &objects, Expected::Absent, commit);
        assert_eq!(
            returned_code(&result),
            Some(ErrorCode::Protocol),
            "{result:?}"
        );
        assert_nothing_published(&server, &before);
    }

    /// The receiver accepts an image for a commit that the repository holds
    /// with no image. The image adds its bytes to the `ObjectsReply`, and no
    /// object. An image for a commit that the session did not stage and the
    /// repository does not hold is `protocol`.
    #[test]
    fn the_receiver_takes_an_image_for_a_held_commit() {
        let dir = TmpDir::new("cfs-transfer-receive-held");
        let (src, commit) = block_on(source(dir.path(), "src", RepoMode::Archive, true));
        let image = image_bytes(&src, &commit).unwrap();
        let (plain, _) = block_on(source(dir.path(), "plain", RepoMode::Archive, false));
        let server = block_on(new_repo(&dir.path().join("server"), RepoMode::Archive, ""));
        block_on(push(&plain, &server));
        assert_eq!(image_bytes(&server, &commit), None);

        let stray = Obj {
            ty: ObjectType::ComposefsImage,
            checksum: Checksum::from_bytes([7; 32]),
            encoding: Encoding::Raw,
            bytes: image.clone(),
        };
        let (result, _) = send_objects(&server, &[stray], Expected::Commit(commit), commit);
        assert_eq!(
            returned_code(&result),
            Some(ErrorCode::Protocol),
            "{result:?}"
        );

        let all = objects(&src, &commit, Some(image.clone()));
        let only = &all[all.len() - 1..];
        let (result, counts) = send_objects(&server, only, Expected::Commit(commit), commit);
        result.unwrap();
        assert_eq!(counts, Some((0, image.len() as u64)));
        block_on(assert_same_image(&src, &server, &commit));
    }

    /// A session with a server commit refuses an image with `protocol`.
    #[test]
    fn a_server_commit_session_refuses_an_image() {
        let dir = TmpDir::new("cfs-transfer-receive-onto");
        let (src, commit) = block_on(source(dir.path(), "src", RepoMode::Archive, true));
        let image = image_bytes(&src, &commit).unwrap();
        let (plain, _) = block_on(source(dir.path(), "plain", RepoMode::Archive, false));
        let server = block_on(new_repo(&dir.path().join("server"), RepoMode::Archive, ""));
        block_on(push(&plain, &server));
        let (stored, _) = block_on(server.load_commit(&commit)).unwrap();
        let sc = ServerCommit {
            branch: "onto".into(),
            tags: Vec::new(),
            bind_refs: Vec::new(),
            root_dirtree: stored.root_dirtree,
            root_dirmeta: stored.root_dirmeta,
            subject: "onto".into(),
            body: String::new(),
            metadata: Vec::new(),
            timestamp: Some(1),
            orphan: true,
        };

        let policy = policy_allowing(&["c:**"]);
        let (result, ()) = session(&server, &policy, |mut client| async move {
            client.hello_reply(&["onto"]).await;
            let _ = client
                .object(ObjectType::ComposefsImage, commit, Encoding::Raw, &image)
                .await;
            let _ = client.objects_end().await;
            let _ = client.server_commit(sc).await;
            let _ = client.commit_reply().await;
        });
        assert_eq!(
            returned_code(&result),
            Some(ErrorCode::Protocol),
            "{result:?}"
        );
        assert_eq!(image_bytes(&server, &commit), None);
    }
}