ostrya 0.18.0

Pure-Rust async reimplementation of the ostree repository library
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
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
//! The push of commits from a repository to a bucket repository.
//!
//! The push writes the bucket repository with no session. It reads the
//! objects through the archive view of the local repository, so each local
//! mode gives the bytes of an `archive` repository. The view builds each
//! `.filez` at the `[archive] zlib-level` of the bucket. The `config` of the
//! bucket takes the role of the server of a session push: its collection id
//! and each `DST` select the namespace of each ref, `refs/heads/` or
//! `refs/mirrors/ID/`.
//!
//! The writes go in this order: the tree objects and the detached metadata,
//! then the commit objects and the ref files. The push writes no `summary`
//! and no `summary.sig`. A commit object goes up only after each object of
//! its tree, so a commit object in the bucket has its whole tree in the
//! bucket at each point of a run, also of a run that failed, or a
//! partial-commit marker that the fsck wrote. A run again lists the objects
//! and uploads only the rest, and it walks no tree of a commit that the
//! bucket holds with no marker.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::pin::Pin;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Instant;

use futures_io::AsyncRead;
use futures_lite::AsyncReadExt;
use futures_lite::future::zip;
use futures_lite::io::Cursor;
use ostrya_core::{Checksum, DeflateReader, ObjectName, ObjectType, Ref};
use sha2::{Digest, Sha256};

use super::invalid;
use super::negotiate::{
    Commits, Local, Plan, RepoPushOptions, binding, check_collection_binding, check_written_shape,
    offered_history,
};
use super::refspec::is_delete;
use super::source::RepoSource;
use crate::access::ReadAccess;
use crate::archive::{ArchiveAnswer, ArchiveView};
use crate::bucket::{
    BucketPushOutcome, BucketRepo, LockOperation, ObjectListing, WriterLock, check_prefixes,
    marker_key, object_key, release_on_error,
};
use crate::config::{archive, ex_ostrya};
use crate::error::{Error, Result};
use crate::hashing::VerifyingReader;
use crate::pull::drive::Slots;
use crate::related::RelatedRule;
use crate::remote::s3::{Bucket, S3Endpoint, part_size};
use crate::remote::tree::TreeModel;
use crate::remote::{
    Compression, Encoding, ObjectData, ObjectSource, PushOutcome, PushPhase, PushProgress,
    PushStats, RefOutcome,
};
use crate::repo::Repo;
use crate::write::archive_level;

/// The namespace of a ref that a push writes.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Namespace {
    /// `refs/heads/`.
    Local,
    /// `refs/mirrors/ID/`.
    Mirror { id: String },
}

impl Namespace {
    /// Returns the namespace of the ref `r` in a bucket repository with the
    /// collection id `bucket_id`.
    ///
    /// A local ref, and a ref of the collection id of the bucket, give the
    /// local refs. A ref of each other collection gives its mirror refs, also
    /// in a bucket with no collection id. A push writes no remote ref, so a
    /// remote ref is no case here.
    pub(super) fn of(r: &Ref, bucket_id: Option<&str>) -> Namespace {
        match r {
            Ref::Collection { id, .. } if Some(id.as_str()) != bucket_id => {
                Namespace::Mirror { id: id.clone() }
            }
            Ref::Remote { .. } => unreachable!("a push writes no remote ref"),
            _ => Namespace::Local,
        }
    }

    /// Returns the ref directory of the namespace, `refs/heads/` or
    /// `refs/mirrors/ID/`.
    pub(super) fn dir(&self) -> String {
        match self {
            Namespace::Local => "refs/heads/".to_owned(),
            Namespace::Mirror { id } => format!("refs/mirrors/{id}/"),
        }
    }

    /// Returns the bucket key of the ref `name` of the namespace.
    pub(super) fn key(&self, name: &str) -> String {
        format!("{}{name}", self.dir())
    }
}

/// The state of a bucket repository that a push reads under the writer
/// lock.
pub(super) struct BucketState {
    /// The DEFLATE level of each `.filez` that the push builds: the
    /// `[archive] zlib-level` of the `config`, 6 if it has none, clamped to 1
    /// to 9.
    pub(super) level: u8,
    /// The `[ex-ostrya] keep-detached-related` of the `config`, `true` if it
    /// has none.
    pub(super) keep_related: bool,
    /// The `[core] collection-id` of the `config`.
    pub(super) collection_id: Option<String>,
    /// The refs of the ref directory of each namespace of the push, by name.
    pub(super) dirs: BTreeMap<Namespace, BTreeMap<String, Checksum>>,
    /// The objects of the bucket.
    pub(super) listing: ObjectListing,
}

/// Reads the state of `bucket` for a push that writes the refs `refs`.
///
/// The call reads the `config`, which gives the namespace of each ref. Then
/// it lists the objects and reads the ref files of the ref directory of
/// each namespace. The listing and the reads of all the directories run at
/// the same time. The ref file reads of all the directories share one bound
/// of `max_outstanding`, and the listing of the objects has its own bound.
/// The call reads no ref file of another namespace. The namespace of the
/// collection id of the bucket is `refs/heads/`, so the call does not list
/// or read `refs/mirrors/` of that id.
///
/// If more than one read fails, the call returns the error of one of them.
///
/// # Errors
///
/// - [`Error::Remote`] with
///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the bucket
///   repository has no `config`.
/// - The errors of [`BucketRepo::read_config`], of
///   [`BucketRepo::read_ref_dirs`], and of [`BucketRepo::list_objects`].
pub(super) async fn read_state(bucket: &BucketRepo, refs: &[&Ref]) -> Result<BucketState> {
    let Some(config) = bucket.read_config().await? else {
        return Err(invalid(format!(
            "the bucket repository {} has no config; init it first",
            bucket.address()
        )));
    };
    let level = archive_level(config.get::<archive::ZlibLevel>()?);
    let keep_related = config.get::<ex_ostrya::KeepDetachedRelated>()?;
    let collection_id = config.collection_id().map(str::to_owned);
    let namespaces: BTreeSet<Namespace> = refs
        .iter()
        .map(|r| Namespace::of(r, collection_id.as_deref()))
        .collect();
    // The push reads the ref directories of its namespaces alone.
    let dirs: Vec<String> = namespaces.iter().map(Namespace::dir).collect();
    let (refs, listing) = zip(bucket.read_ref_dirs(&dirs), bucket.list_objects()).await;
    Ok(BucketState {
        level,
        keep_related,
        collection_id,
        dirs: namespaces.into_iter().zip(refs?).collect(),
        listing: listing?,
    })
}

/// Refuses the options that a push to a bucket repository cannot carry:
/// tags, a compression, and a delete refspec `:DST`, `:@ID:NAME` included.
pub(super) fn refuse_options(opts: &RepoPushOptions) -> Result<()> {
    if !opts.tags.is_empty() {
        return Err(invalid(
            "a push to an s3:// address creates no tag, and the push names tags",
        ));
    }
    if opts.compression != Compression::None {
        return Err(invalid(
            "a push to an s3:// address uploads each object in archive form, and the push \
             names a compression",
        ));
    }
    if let Some(spec) = opts.refspecs.iter().find(|spec| is_delete(spec)) {
        return Err(invalid(format!(
            "a push to an s3:// address deletes no ref, and the refspec '{spec}' is a delete"
        )));
    }
    Ok(())
}

/// Refuses two refs of `names` that name one ref of a bucket repository
/// whose collection id is `own`: `NAME` and `@OWN:NAME`.
///
/// # Errors
///
/// [`Error::Remote`] with
/// [`InvalidInput`](crate::remote::Error::InvalidInput) for the first ref
/// that names the ref of an earlier ref.
fn check_distinct<'a>(own: Option<&str>, names: impl IntoIterator<Item = &'a Ref>) -> Result<()> {
    let mut seen: HashMap<Ref, &Ref> = HashMap::new();
    for name in names {
        if let Some(first) = seen.insert(name.clone().canonical(own), name) {
            return Err(invalid(format!(
                "the refs '{first}' and '{name}' name one ref of the server"
            )));
        }
    }
    Ok(())
}

/// One ref update of a push, after the checks against the bucket.
pub(super) struct Update {
    /// The `DST` of the refspec, or the branch of a tree push.
    pub(super) dst: Ref,
    /// The bucket key of the ref.
    pub(super) key: String,
    /// The commit of the ref in the bucket before the push.
    pub(super) old: Option<Checksum>,
    /// The commit that the ref takes.
    pub(super) new: Checksum,
}

/// The work of a push before the ref writes, and its counts.
struct Uploaded {
    /// The updates, in the order of the refspecs.
    updates: Vec<Update>,
    /// The commits whose partial-commit marker the push deletes before the
    /// ref writes: each offered commit with a marker, whose tree the push
    /// walked.
    cleared: Vec<Checksum>,
    stats: PushStats,
}

/// The counts of the uploads of one push.
#[derive(Default)]
pub(super) struct Counts {
    /// The bytes of each object body and detached metadata that the push
    /// read and uploaded.
    pub(super) bytes: AtomicU64,
    /// The objects that the push uploaded.
    pub(super) objects: AtomicU64,
}

/// Methods that push commits to a bucket repository.
impl Repo {
    /// Pushes the commits of `opts.refspecs` to the bucket repository of
    /// `endpoint`.
    ///
    /// [`Repo::push`] with an `Endpoint::S3` calls this method, and drops
    /// [`BucketPushOutcome::broken_lock`]. The push needs the features
    /// `push` and `s3`.
    ///
    /// The bucket repository needs a `config`, which
    /// [`BucketRepo::init`] writes. Each object goes up in archive form: the
    /// stored file of an `archive` repository, and for each other mode a
    /// `.filez` that the push builds at the `[archive] zlib-level` of the
    /// `config` of the bucket, 6 if the `config` has none, clamped to 1 to 9.
    /// The push trusts the listing of the objects of the bucket alone: it
    /// uploads each object of its walk that the listing does not hold.
    ///
    /// The push writes no `summary` and no `summary.sig`. A `summary` and a
    /// `summary.sig` that the bucket holds stay as they are, so they do not
    /// show the refs that the push writes. A pull of a named ref reads the
    /// ref file of the bucket when the summary does not list the ref.
    ///
    /// # Steps
    ///
    /// 1. The push refuses the options that it cannot carry, and runs the
    ///    checks and the commit walk of [`Repo::push_over_stream`] with no
    ///    request: the depth, the collection, the refspecs, the source
    ///    commits, the bindings, and the attachments. It holds the repository
    ///    lock shared until it returns.
    /// 2. It takes the writer lock of the bucket repository for
    ///    [`LockOperation::Push`], with
    ///    [`break_lock`](RepoPushOptions::break_lock).
    /// 3. It reads the `config`, which gives the namespace of each `DST`.
    ///    Then it lists the objects, and at the same time reads the ref files
    ///    of the ref directory of each namespace of the push. It reads no ref
    ///    file of another namespace, and it skips `refs/mirrors/` of the
    ///    collection id of the bucket, whose refs are in `refs/heads/`. It
    ///    refuses a `DST` `@OWN:NAME`, where `OWN` is the collection id of
    ///    the bucket, if `NAME` is 64 lowercase hex characters, as step 1
    ///    refuses a local `DST` of that form. It checks the collection
    ///    binding of each ref in its namespace. For
    ///    each ref, the tip of the ref in the bucket must be an ancestor of
    ///    the new commit in the local repository, unless
    ///    [`force`](RepoPushOptions::force) is set. A tip that the local
    ///    repository does not hold, or marks partial, is no ancestor.
    /// 4. It walks the commits to offer: each source commit, its history, and
    ///    the full set of attachments of the offered commits, as
    ///    [`Repo::push_over_stream`] offers them, with the tip of the ref in
    ///    the bucket in the role of the server tip. With no depth, it checks
    ///    the full set of attachments of the offered history here, as
    ///    "Attachments" of [`Repo::push_over_stream`] states. It walks the
    ///    tree of each offered commit that the listing lacks, and of each
    ///    offered commit with a partial-commit marker
    ///    `state/<checksum>.commitpartial`.
    ///    It walks no tree of another commit that the listing holds: each
    ///    writer uploads a commit object after its tree, so a commit object in
    ///    the bucket has its whole tree in the bucket, or a marker that
    ///    [`BucketRepo::fsck`] wrote.
    /// 5. It uploads each tree object that the listing lacks, and the
    ///    detached metadata of each commit that the bucket lacks and of each
    ///    source commit, at most `max_outstanding` uploads at a time. If
    ///    `[ex-ostrya] keep-detached-related` of the `config` of the bucket is
    ///    `false`, it drops `ostrya.related` from each dict that it uploads.
    ///    It skips a `.commitmeta` that the bucket holds with the same bytes,
    ///    and a commit with no detached metadata after the rule, which leaves
    ///    the bucket copy.
    /// 6. It uploads each commit object that the bucket lacks.
    /// 7. It checks the writer lock, deletes the marker of each walked commit
    ///    with a marker, then writes each ref file that changes, in the order
    ///    of the refspecs. A marker of a commit that the push does not offer
    ///    stays.
    /// 8. It releases the writer lock.
    ///
    /// # Namespace
    ///
    /// Each `DST` names its own namespace, as for
    /// [`Repo::push_over_stream`], with the `config` of the bucket in the
    /// role of the server. A plain `DST` `NAME`, and `@ID:NAME` where `ID` is
    /// the `[core] collection-id` of the bucket, writes `refs/heads/NAME`.
    /// Each other `@ID:NAME` writes `refs/mirrors/ID/NAME`, also in a bucket
    /// with no collection id. One push can write the refs of more than one
    /// namespace. The binding of a commit selects no namespace. A bound
    /// commit must name the id of the namespace of its ref, and for
    /// `refs/heads/` the collection id of the bucket. A commit with no
    /// binding goes to `refs/heads/` alone. The fast-forward rule and `force`
    /// apply to each ref in its own namespace.
    ///
    /// A bucket has no server check of `ostree.ref-binding`, so
    /// [`disable_verify_bindings`](RepoPushOptions::disable_verify_bindings)
    /// alone skips that check of the push.
    ///
    /// # Progress
    ///
    /// After step 1, the push sets the phase `Scanning` with
    /// [`start_phase`](crate::remote::PushProgress::start_phase), so the hook
    /// gets one call with `Scanning`, also on a new handle. The phase stays
    /// for the lock, the reads, the checks, and the walk of steps 2 to 4. It
    /// also stays for the check after the walk: each ref of the new ref set
    /// of each namespace of the push must name a commit that the bucket holds
    /// or that the push uploads. With a progress handle, a pass over the files to upload
    /// then gives the total of the content, also in `Scanning`. A failure of
    /// that pass gives no total, and the push goes on. The push sets
    /// `Uploading` before the uploads of steps 5 and 6, and `Committing`
    /// before step 7, which writes the refs. The objects that it uploads
    /// count as needed and as sent. The content of an `archive` repository
    /// counts with the stored bytes of each `.filez` as the push reads them.
    /// In each other mode, the payload size of a file counts after the upload
    /// of its `.filez`.
    ///
    /// # Failure states
    ///
    /// - A failure before the ref writes changes no ref. The objects that
    ///   went up stay, and a run again uploads only the rest. The push releases the lock, and returns the first error. An
    ///   error of the release is dropped: the lock then stays, and the next
    ///   writer names it. When one upload fails, the push starts no new
    ///   upload and waits for the uploads in flight. A failed upload aborts
    ///   its own multipart upload.
    /// - A failure of a ref write leaves some refs moved. A run again finds
    ///   the moved refs at their new commits, and writes the other refs.
    /// - A check of the lock that finds another lock, or no lock, stops the
    ///   push before its next write with
    ///   [`Error::BucketLockLost`], and the push releases no lock.
    /// - A failure of the release, or a crash, leaves the lock. The refs are
    ///   written at that point. The next writer gets
    ///   [`Error::BucketLocked`], and a push with `break_lock` removes the
    ///   lock and names its holder in [`BucketPushOutcome::broken_lock`].
    ///   The holder is reported on success alone: a push that breaks the
    ///   lock and then fails returns its error with no holder.
    /// - A crash during a multipart upload leaves the upload open, and it
    ///   holds storage until a lifecycle rule of the bucket aborts it.
    ///
    /// # Result
    ///
    /// The outcome holds one ref outcome for each refspec, in order, also
    /// for a ref that did not move. The statistics count the commits that
    /// the push offered and the tree objects of its walk, the objects that
    /// it uploaded, and the bytes of each object and detached metadata that
    /// it uploaded.
    ///
    /// # Errors
    ///
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if `opts` names
    ///   tags, a compression, or a delete refspec, `:@ID:NAME` included. The
    ///   push then sends no request.
    /// - The errors of the checks and of the commit walk of
    ///   [`Repo::push_over_stream`], before a request.
    /// - With no depth, [`Error::InvalidRelations`] for an attachment in the
    ///   full set of attachments of a history commit after the cut at the tip
    ///   of the ref in the bucket, as "Attachments" of
    ///   [`Repo::push_over_stream`] states. The push then uploads nothing and
    ///   releases the lock.
    /// - The errors of [`BucketRepo::lock`].
    /// - [`Error::Remote`] with
    ///   [`InvalidInput`](crate::remote::Error::InvalidInput) if the bucket
    ///   repository has no `config`, if two `DST` refs name one ref of the
    ///   bucket, `NAME` and `@OWN:NAME` for the collection id `OWN` of the
    ///   bucket, or if the ref directory of a namespace of the push holds a
    ///   name that is a directory of another name after the push. The push
    ///   then uploads nothing.
    /// - [`Error::InvalidRefspec`] with the text of the `DST` if a `DST` is
    ///   `@OWN:NAME` for the collection id `OWN` of the bucket, and `NAME` is
    ///   64 lowercase hex characters. The push then uploads nothing.
    /// - [`Error::InvalidFormat`] if the `config` of the bucket is malformed,
    ///   states a mode other than `archive-z2` and `archive`, holds a
    ///   `tombstone-commits`, `indexed-deltas`, or `keep-detached-related`
    ///   that is no boolean, or holds a `zlib-level` that is no integer, if a
    ///   key under the ref directory of a namespace of the push is no ref
    ///   name, if a ref file of such a namespace is malformed, or if a ref of
    ///   such a namespace names a commit that the bucket does not hold. The
    ///   push then uploads nothing. The push does not check the keys and the
    ///   ref files of the other namespaces, also `refs/mirrors/ID/` of the
    ///   collection id of the bucket.
    /// - [`Error::Remote`] with
    ///   [`BindingMismatch`](crate::remote::Error::BindingMismatch) if the
    ///   binding of a source commit does not agree with the namespace of its
    ///   `DST`.
    /// - [`Error::Remote`] with
    ///   [`NonFastForward`](crate::remote::Error::NonFastForward) if a ref
    ///   update is not a fast-forward and `force` is not set.
    /// - [`Error::ObjectNotFound`] if the local repository lacks an object of
    ///   the walk.
    /// - [`Error::BucketLockLost`] if a check of the writer lock fails.
    /// - [`Error::Remote`] for an error of the bucket client, for example
    ///   [`S3`](crate::remote::Error::S3) for an error response.
    /// - [`Error::Io`] and [`Error::Core`] for a failed read of the local
    ///   repository.
    pub async fn push_to_bucket(
        &self,
        endpoint: S3Endpoint,
        opts: RepoPushOptions,
    ) -> Result<BucketPushOutcome> {
        refuse_options(&opts)?;
        let bucket = match opts.bucket_max_outstanding {
            Some(n) => BucketRepo::new(Bucket::new(&endpoint).await?, n),
            None => BucketRepo::open(&endpoint).await?,
        };
        let mut plan = self.plan_push(&opts).await?;
        let progress = opts.progress.as_ref();
        if let Some(progress) = progress {
            progress.start_phase(PushPhase::Scanning);
        }
        let start = Instant::now();
        let lock = bucket.lock(LockOperation::Push, opts.break_lock).await?;
        let broken_lock = lock.broken().cloned();
        let Uploaded {
            updates,
            cleared,
            mut stats,
        } = match self.upload_to_bucket(&bucket, &mut plan, &opts).await {
            Ok(uploaded) => uploaded,
            Err(e) => return Err(release_on_error(lock, e).await),
        };
        if let Some(progress) = progress {
            progress.set_phase(PushPhase::Committing);
        }
        if let Err(e) = write_bucket_refs(&bucket, &lock, &cleared, &updates).await {
            return Err(release_on_error(lock, e).await);
        }
        lock.release().await?;
        stats.elapsed = start.elapsed();
        let refs = updates
            .into_iter()
            .map(|update| RefOutcome {
                name: update.dst.to_string(),
                old: update.old,
                new: Some(update.new),
            })
            .collect();
        Ok(BucketPushOutcome {
            outcome: PushOutcome {
                commit: None,
                refs,
                stats,
            },
            broken_lock,
        })
    }

    /// Runs the steps of a push to `bucket` from the read of its state to
    /// the upload of the commit objects.
    async fn upload_to_bucket(
        &self,
        bucket: &BucketRepo,
        plan: &mut Plan,
        opts: &RepoPushOptions,
    ) -> Result<Uploaded> {
        let dsts: Vec<&Ref> = plan.targets.iter().map(|t| &t.dst).collect();
        let BucketState {
            level,
            keep_related,
            collection_id,
            dirs,
            listing,
        } = read_state(bucket, &dsts).await?;
        drop(dsts);
        let bucket_id = collection_id.as_deref();
        // `NAME` and `@OWN:NAME` name one ref of the bucket, and the push
        // writes each ref once.
        check_distinct(bucket_id, plan.targets.iter().map(|t| &t.dst))?;
        // `@OWN:NAME` is `refs/heads/NAME`, so the local checksum-shape rule
        // applies to its `NAME`.
        check_written_shape(bucket_id, plan.targets.iter().map(|t| &t.dst))?;

        // The bindings, each ref in its namespace.
        for target in &plan.targets {
            let commit = target.commit.expect("a push to a bucket refuses a delete");
            let bound = binding(&plan.sources, &commit);
            check_collection_binding(&commit, bound, &target.dst, bucket_id)?;
        }

        // The ref checks, in the directory of each namespace.
        let mut updated = dirs.clone();
        for target in &plan.targets {
            let commit = target.commit.expect("a push to a bucket refuses a delete");
            let ns = Namespace::of(&target.dst, bucket_id);
            let dir = updated.get_mut(&ns).expect("the push read each namespace");
            dir.insert(target.dst.name().to_owned(), commit);
        }
        for dir in updated.values() {
            check_prefixes(dir)?;
        }
        let mut updates = Vec::with_capacity(plan.targets.len());
        for target in &plan.targets {
            let new = target.commit.expect("a push to a bucket refuses a delete");
            let ns = Namespace::of(&target.dst, bucket_id);
            let name = target.dst.name();
            let old = dirs[&ns].get(name).copied();
            let key = ns.key(name);
            if let Some(tip) = old
                && tip != new
                && !opts.force
                && !self.fast_forward(new, tip, &mut plan.commits).await?
            {
                return Err(Error::Remote(crate::remote::Error::NonFastForward(
                    format!(
                        "ref '{key}' is at {tip}, which is not an ancestor of {new} in the \
                         local repository"
                    ),
                )));
            }
            updates.push(Update {
                dst: target.dst.clone(),
                key,
                old,
                new,
            });
        }
        drop(dirs);

        let walk = self
            .bucket_walk(bucket, plan, &updates, &listing, opts)
            .await?;
        // The walk is the last reader of the commits of the plan.
        drop(std::mem::take(&mut plan.commits));
        // Each ref of the new ref set of each namespace names a commit that
        // the bucket holds or that the push uploads, so a ref of a namespace
        // of the push that names an absent commit refuses the push before
        // its first upload.
        if let Some(absent) = updated.values().flat_map(BTreeMap::values).find(|commit| {
            !walk.missing.contains(commit)
                && !listing
                    .objects
                    .contains_key(&ObjectName::new(**commit, ObjectType::Commit))
        }) {
            return Err(bucket.malformed(format!(
                "a ref names the commit {absent}, which the bucket does not hold"
            )));
        }
        let counts = Counts::default();
        let progress = opts.progress.as_ref();
        let (sizes, content) = self.content_sizes(&walk.upload, opts).await;
        let needed = (walk.upload.len() + walk.missing_commits.len()) as u64;
        if let Some(progress) = progress {
            progress.add_upload(needed, content);
            progress.set_phase(PushPhase::Uploading);
        }

        let view = ArchiveView::with_zlib_level(self.clone(), level);
        let access = self.implicit_reads();
        let source = RepoSource::new(
            self.clone(),
            RelatedRule {
                drop_related: !keep_related,
            },
        );
        let uploads = Uploads {
            bucket,
            origin: Origin::Repo {
                repo: self,
                view: &view,
                access,
                source: &source,
                sizes: &sizes,
            },
            listing: &listing,
            part: opts.part_size,
            progress,
            counts: &counts,
        };
        // The tree objects and the detached metadata share one pool of
        // uploads. Each commit object goes up after the pool ends.
        uploads
            .all(
                walk.upload
                    .iter()
                    .copied()
                    .map(Job::Object)
                    .chain(walk.metadata.iter().copied().map(Job::Metadata)),
            )
            .await?;
        uploads
            .all(
                walk.missing_commits
                    .iter()
                    .map(|commit| Job::Object(ObjectName::new(*commit, ObjectType::Commit))),
            )
            .await?;

        let sent = counts.objects.load(Ordering::Relaxed);
        let bytes = counts.bytes.load(Ordering::Relaxed);
        Ok(Uploaded {
            updates,
            cleared: walk.marked,
            stats: PushStats {
                objects_total: walk.offered as u64 + walk.tree_objects as u64,
                objects_needed: needed,
                objects_sent: sent,
                bytes_sent: bytes,
                payload_bytes: bytes,
                elapsed: Default::default(),
            },
        })
    }

    /// Returns the payload size of each file of `upload` whose `.filez` the
    /// push builds, and the total of the content for the progress.
    ///
    /// A `.filez` that the push builds takes its part size from the size of
    /// its payload, so the pass reads the size of each file of a repository
    /// of a mode other than `archive`, unless the caller sets the part size.
    /// The total needs a progress handle. In an `archive` repository it is
    /// the sum of the stored sizes. A failure of the pass gives no sizes and
    /// a total of zero, and the push goes on: each upload reads the size of
    /// its own payload, and an upload of an absent object fails.
    async fn content_sizes(
        &self,
        upload: &[ObjectName],
        opts: &RepoPushOptions,
    ) -> (HashMap<Checksum, u64>, u64) {
        let archive = self.mode().is_archive();
        let builds = !archive && opts.part_size.is_none();
        if opts.progress.is_none() && !builds {
            return (HashMap::new(), 0);
        }
        let files: Vec<Checksum> = upload
            .iter()
            .filter(|name| name.ty == ObjectType::File)
            .map(|name| name.checksum)
            .collect();
        let repo = self.clone();
        if archive {
            let total = ostrya_rt::unblock(move || repo.content_size_blocking(&files, true)).await;
            return (HashMap::new(), total.unwrap_or(0));
        }
        let sizes = ostrya_rt::unblock(move || -> Result<HashMap<Checksum, u64>> {
            files
                .iter()
                .map(|file| Ok((*file, repo.object_content_size_blocking(file, false)?)))
                .collect()
        })
        .await
        .unwrap_or_default();
        let total = sizes
            .values()
            .fold(0u64, |sum, size| sum.saturating_add(*size));
        (sizes, total)
    }

    /// Returns the commits and the objects of a push to the bucket
    /// repository `bucket`, whose listing is `listing`.
    ///
    /// The walk reads the tree of each offered commit that the listing
    /// lacks, and of each offered commit with a partial-commit marker. A
    /// commit object in the bucket has its whole tree in the bucket, or a
    /// marker, so the walk reads no tree of another commit that the listing
    /// holds. The walk lists the markers under `state/` only if the listing
    /// holds an offered commit.
    async fn bucket_walk(
        &self,
        bucket: &BucketRepo,
        plan: &mut Plan,
        updates: &[Update],
        listing: &ObjectListing,
        opts: &RepoPushOptions,
    ) -> Result<Walk> {
        let holds = |checksum: &Checksum, ty: ObjectType| {
            listing
                .objects
                .contains_key(&ObjectName::new(*checksum, ty))
        };
        // The commits to offer: each source commit and its history, cut at
        // the tip of the ref in the bucket.
        let chains = std::mem::take(&mut plan.chains);
        let mut offered: Vec<Checksum> = Vec::new();
        let mut seen = HashSet::new();
        for ((target, chain), update) in plan.targets.iter().zip(&chains).zip(updates) {
            let source = target.commit.expect("a push to a bucket refuses a delete");
            let history = offered_history(opts.depth, update.old, chain);
            for commit in std::iter::once(&source).chain(history) {
                if seen.insert(*commit) {
                    offered.push(*commit);
                }
            }
        }
        drop(chains);
        // Then the full set of attachments of the offered commits, each
        // once. With no depth, the push resolves the attachments of the
        // offered history here, before the first upload.
        if opts.depth.is_none() {
            plan.commits.check_attachments(self, &offered).await?;
        }
        let attachments = plan.commits.full_set(&offered, &mut seen);
        offered.extend(attachments);
        let missing_commits: Vec<Checksum> = offered
            .iter()
            .filter(|commit| !holds(commit, ObjectType::Commit))
            .copied()
            .collect();
        let missing: HashSet<Checksum> = missing_commits.iter().copied().collect();
        // The offered commits that the bucket holds with a marker. The walk
        // reads their trees as the trees of the missing commits.
        let partial = if missing_commits.len() < offered.len() {
            bucket.partial_commits().await?
        } else {
            BTreeSet::new()
        };
        let marked: Vec<Checksum> = offered
            .iter()
            .filter(|commit| holds(commit, ObjectType::Commit) && partial.contains(*commit))
            .copied()
            .collect();
        let mut seen = HashSet::new();
        let mut tree_names = Vec::new();
        for commit in missing_commits.iter().chain(&marked) {
            let Local::Held(link) = plan.commits.local[commit] else {
                unreachable!("an offered commit is held");
            };
            self.collect_tree_strict(
                link.root_dirtree,
                link.root_dirmeta,
                &mut seen,
                &mut tree_names,
            )
            .await?;
        }
        drop(seen);
        let tree_objects = tree_names.len();
        let upload = tree_names
            .into_iter()
            .filter(|name| !listing.objects.contains_key(name))
            .collect();
        // The detached metadata of each commit that the push uploads, then of
        // each source commit, each once.
        let mut metadata = missing_commits.clone();
        metadata.extend(
            plan.sources
                .iter()
                .map(|(c, _)| *c)
                .filter(|c| !missing.contains(c)),
        );
        Ok(Walk {
            offered: offered.len(),
            missing_commits,
            missing,
            marked,
            tree_objects,
            upload,
            metadata,
        })
    }

    /// Returns `true` if the local repository holds `tip` on the parent
    /// chain of `new`.
    ///
    /// The walk reads the chain with no depth limit. It stops with `false`
    /// at a commit that the local repository does not hold or marks
    /// partial, and at the root.
    async fn fast_forward(
        &self,
        new: Checksum,
        tip: Checksum,
        commits: &mut Commits,
    ) -> Result<bool> {
        let mut next = new;
        loop {
            let Local::Held(link) = self.history_commit(&next, commits).await? else {
                return Ok(false);
            };
            if next == tip {
                return Ok(true);
            }
            match link.parent {
                Some(parent) => next = parent,
                None => return Ok(false),
            }
        }
    }
}

/// The commits and the objects of a push to a bucket repository.
struct Walk {
    /// The number of commits that the push offered.
    offered: usize,
    /// The offered commits that the listing lacks, in the order of the
    /// offer.
    missing_commits: Vec<Checksum>,
    /// The commits of `missing_commits`, for a lookup.
    missing: HashSet<Checksum>,
    /// The offered commits that the bucket holds with a partial-commit
    /// marker, in the order of the offer. The walk read their trees.
    marked: Vec<Checksum>,
    /// The number of tree objects of the walk.
    tree_objects: usize,
    /// The tree objects that the listing lacks.
    upload: Vec<ObjectName>,
    /// The commits whose detached metadata the push uploads: each missing
    /// commit, then each source commit, each once.
    metadata: Vec<Checksum>,
}

/// Checks the writer lock, deletes the partial-commit marker of each commit
/// of `cleared`, then writes the ref file of each update that changes a ref,
/// in order.
pub(super) async fn write_bucket_refs(
    bucket: &BucketRepo,
    lock: &WriterLock<'_>,
    cleared: &[Checksum],
    updates: &[Update],
) -> Result<()> {
    lock.check().await?;
    let mut deletes = Slots::new(bucket.max_outstanding());
    let mut pending = cleared.iter();
    loop {
        while deletes.has_room()
            && let Some(commit) = pending.next()
        {
            deletes.push(async move { bucket.bucket().delete(&marker_key(commit)).await });
        }
        let Some(deleted) = deletes.next_ready().await else {
            break;
        };
        deleted?;
    }
    for update in updates {
        if update.old == Some(update.new) {
            continue;
        }
        bucket
            .bucket()
            .put(
                &update.key,
                format!("{}\n", update.new.to_hex()).into_bytes(),
            )
            .await?;
    }
    Ok(())
}

/// One upload of a push.
#[derive(Clone, Copy)]
pub(super) enum Job {
    /// An object, as a stream.
    Object(ObjectName),
    /// The detached metadata of a commit.
    Metadata(Checksum),
}

/// The uploads of the objects of one push.
pub(super) struct Uploads<'a> {
    pub(super) bucket: &'a BucketRepo,
    /// The source of the objects.
    pub(super) origin: Origin<'a>,
    /// The listing of the objects of the bucket before the uploads.
    pub(super) listing: &'a ObjectListing,
    /// The part size of the caller, or `None` for the part size rule.
    pub(super) part: Option<u64>,
    pub(super) progress: Option<&'a PushProgress>,
    pub(super) counts: &'a Counts,
}

/// The source of the objects of a push to a bucket repository.
pub(super) enum Origin<'a> {
    /// A local repository, through its archive view.
    Repo {
        repo: &'a Repo,
        view: &'a ArchiveView,
        access: &'a ReadAccess,
        /// The source of the detached metadata, with the rule of `[ex-ostrya]
        /// keep-detached-related` of the bucket.
        source: &'a RepoSource,
        /// The payload size of each file whose `.filez` the push builds, if
        /// the pass over the files read it.
        sizes: &'a HashMap<Checksum, u64>,
    },
    /// The model of a local directory, whose `.filez` objects the push
    /// builds at `level` with the compressors of `compressors`.
    Tree {
        model: &'a TreeModel,
        level: u8,
        compressors: &'a CompressorPool,
    },
}

/// The body of one object upload.
struct Body<'a> {
    /// The number of bytes of the body, if it is known.
    len: Option<u64>,
    body: BodyData<'a>,
    /// The payload size of a file whose `.filez` the push builds, which
    /// counts as content after the upload, if it is known.
    payload: Option<u64>,
    /// `true` if the bytes of the body count as content as the push reads
    /// them: the stored `.filez` of an `archive` repository.
    stored_content: bool,
}

/// The bytes of one object upload.
enum BodyData<'a> {
    /// A stream.
    Stream(Box<dyn AsyncRead + Unpin + Send + 'a>),
    /// Bytes in memory: a dirtree or a dirmeta object of a tree push.
    Bytes(Vec<u8>),
}

/// The raw-DEFLATE compressor of the payload of one file of a tree push.
type FileDeflate = DeflateReader<Box<dyn AsyncRead + Unpin + Send>>;

/// The compressors of a tree push that no upload body holds.
///
/// A body leases one compressor, and gives it back when the body drops. At
/// most `max_outstanding` bodies exist at a time, so the pool holds at most
/// that many compressors.
#[derive(Default)]
pub(super) struct CompressorPool {
    idle: Mutex<Vec<FileDeflate>>,
}

impl CompressorPool {
    /// Leases a compressor over `source` at `level`.
    ///
    /// The lease reuses an idle compressor if one is there.
    fn lease(&self, source: Box<dyn AsyncRead + Unpin + Send>, level: u8) -> Leased<'_> {
        let idle = self.idle.lock().expect("tree push compressor mutex").pop();
        let reader = match idle {
            Some(mut reader) => {
                reader.reset(source, level);
                reader
            }
            None => DeflateReader::new(source, level),
        };
        Leased {
            reader: Some(reader),
            pool: self,
        }
    }
}

/// A compressor that one upload body holds.
struct Leased<'a> {
    reader: Option<FileDeflate>,
    pool: &'a CompressorPool,
}

impl AsyncRead for Leased<'_> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<std::io::Result<usize>> {
        let reader = self.reader.as_mut().expect("a lease holds its compressor");
        Pin::new(reader).poll_read(cx, buf)
    }
}

impl Drop for Leased<'_> {
    fn drop(&mut self) {
        if let Some(mut reader) = self.reader.take() {
            // The file closes now. The compressor and its buffers stay for
            // the next body.
            *reader.get_mut() = Box::new(futures_lite::io::empty());
            self.pool
                .idle
                .lock()
                .expect("tree push compressor mutex")
                .push(reader);
        }
    }
}

impl Uploads<'_> {
    /// Runs each upload of `jobs`, at most `max_outstanding` at a time.
    ///
    /// After the first failure, the call starts no new upload, waits for
    /// the uploads in flight, and returns the first error.
    pub(super) async fn all(&self, jobs: impl Iterator<Item = Job>) -> Result<()> {
        let mut slots = Slots::new(self.bucket.max_outstanding());
        let mut pending = jobs;
        let mut first = None;
        loop {
            while first.is_none()
                && slots.has_room()
                && let Some(job) = pending.next()
            {
                match job {
                    Job::Object(name) => slots.push(self.one(name)),
                    Job::Metadata(commit) => slots.push(self.metadata(commit)),
                }
            }
            match slots.next_ready().await {
                None => break,
                Some(Ok(())) => {}
                Some(Err(e)) => {
                    first.get_or_insert(e);
                }
            }
        }
        first.map_or(Ok(()), Err)
    }

    /// Uploads the object `name` as a stream.
    async fn one(&self, name: ObjectName) -> Result<()> {
        let key = object_key(&name);
        let file = name.ty == ObjectType::File;
        let Body {
            len,
            body,
            payload,
            stored_content,
        } = match self.origin {
            Origin::Repo {
                repo,
                view,
                access,
                sizes,
                ..
            } => {
                self.repo_body(repo, view, access, sizes, &key, &name)
                    .await?
            }
            Origin::Tree {
                model,
                level,
                compressors,
            } => tree_body(model, level, compressors, &name).await?,
        };
        let part = match self.part {
            Some(part) => part,
            None => part_size(len.or(payload).unwrap_or(0))?,
        };
        let read = AtomicU64::new(0);
        let body = match body {
            // Bytes of at most one part go in one `PUT`, with no copy.
            BodyData::Bytes(bytes) if bytes.len() as u64 <= part => {
                let len = bytes.len() as u64;
                self.bucket.bucket().put(&key, bytes).await?;
                read.store(len, Ordering::Relaxed);
                None
            }
            BodyData::Bytes(bytes) => Some(Box::new(Cursor::new(bytes)) as Box<_>),
            BodyData::Stream(body) => Some(body),
        };
        if let Some(body) = body {
            let counted = Counted {
                inner: body,
                read: &read,
                progress: self.progress.filter(|_| file && stored_content),
            };
            let put = self.bucket.bucket().put_stream(&key, counted, part).await;
            if let (Err(e), Origin::Tree { model, .. }) = (&put, &self.origin)
                && let Some(e) = changed_file(model, &name, e)
            {
                return Err(e);
            }
            put?;
        }
        self.counts
            .bytes
            .fetch_add(read.load(Ordering::Relaxed), Ordering::Relaxed);
        self.counts.objects.fetch_add(1, Ordering::Relaxed);
        if let Some(progress) = self.progress {
            if let Some(payload) = payload.filter(|_| file) {
                progress.add_content(payload);
            }
            progress.object_uploaded();
        }
        Ok(())
    }

    /// Returns the body of the object `name` of a local repository, at the
    /// key `key`, from the archive view.
    async fn repo_body(
        &self,
        repo: &Repo,
        view: &ArchiveView,
        access: &ReadAccess,
        sizes: &HashMap<Checksum, u64>,
        key: &str,
        name: &ObjectName,
    ) -> Result<Body<'static>> {
        let missing = || Error::ObjectNotFound {
            checksum: name.checksum,
            ty: name.ty,
        };
        let (len, body) = match view.get(key, access).await? {
            ArchiveAnswer::Stream { len, body } => (len, body),
            ArchiveAnswer::NotFound | ArchiveAnswer::Refused => return Err(missing()),
            other => {
                return Err(Error::InvalidFormat(format!(
                    "the archive view gave {other:?} for the object {key}"
                )));
            }
        };
        // The view builds a `.filez` with no length. The payload size of the
        // file bounds the size of the `.filez`, and counts as content after
        // the upload.
        let built = len.is_none();
        let payload = match sizes.get(&name.checksum) {
            _ if !built => None,
            Some(size) => Some(*size),
            None if self.part.is_some() && self.progress.is_none() => None,
            None => {
                let repo = repo.clone();
                let checksum = name.checksum;
                Some(
                    ostrya_rt::unblock(move || repo.object_content_size_blocking(&checksum, false))
                        .await?,
                )
            }
        };
        Ok(Body {
            len,
            body: BodyData::Stream(body),
            payload,
            stored_content: !built,
        })
    }

    /// Uploads the detached metadata of `commit` if the bucket does not hold
    /// it with the same bytes.
    ///
    /// The bytes are the stored `.commitmeta` after the rule of `[ex-ostrya]
    /// keep-detached-related` of the bucket. A commit with no detached
    /// metadata after the rule uploads nothing,
    /// and the bucket keeps its copy. The bytes go up when the listing does
    /// not hold the key, when the size in the listing differs, or when a
    /// read of the key gives other bytes.
    async fn metadata(&self, commit: Checksum) -> Result<()> {
        let Origin::Repo { source, .. } = self.origin else {
            unreachable!("a tree push uploads no detached metadata");
        };
        let Some(bytes) = source.detached_bytes(&commit).await? else {
            return Ok(());
        };
        let name = ObjectName::new(commit, ObjectType::CommitMeta);
        let key = object_key(&name);
        let len = bytes.len() as u64;
        let current = match self.listing.objects.get(&name) {
            Some(size) if *size == len => match self.bucket.bucket().get(&key, len).await {
                Ok(object) => object.map(|object| object.bytes),
                // A larger object holds other bytes.
                Err(crate::remote::Error::LimitExceeded(_)) => None,
                Err(e) => return Err(e.into()),
            },
            _ => None,
        };
        if current.as_deref() == Some(&bytes[..]) {
            return Ok(());
        }
        self.bucket.bucket().put(&key, bytes).await?;
        self.counts.bytes.fetch_add(len, Ordering::Relaxed);
        Ok(())
    }
}

/// Returns the body of the object `name` of the tree `model`.
///
/// A dirtree or a dirmeta object is its serialized bytes, in memory. A
/// symlink is the framed archive header alone. A regular file is the framed
/// archive header, then its payload in raw DEFLATE at `level`, through a
/// compressor of `compressors`. The payload goes through a reader that hashes
/// the header and the payload, and fails at the end of the payload if the
/// checksum is not that of `name`. So a file that changed after the hash pass
/// fails the upload before its last part goes up.
async fn tree_body<'a>(
    model: &TreeModel,
    level: u8,
    compressors: &'a CompressorPool,
    name: &ObjectName,
) -> Result<Body<'a>> {
    let data = model.open(name, Encoding::Raw).await?;
    let (header, size, payload) = match data {
        ObjectData::Content {
            header,
            size,
            payload,
        } => (header, size, payload),
        ObjectData::Encoded { mut reader, .. } => {
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes).await?;
            return Ok(Body {
                len: Some(bytes.len() as u64),
                body: BodyData::Bytes(bytes),
                payload: None,
                stored_content: false,
            });
        }
    };
    let mut framed = Vec::new();
    header.write_framed_archive(size, &mut framed)?;
    let body: Box<dyn AsyncRead + Unpin + Send + 'a> = match payload {
        // A symlink is the archive header alone.
        None => Box::new(Cursor::new(framed)),
        Some(payload) => {
            let mut prefix = Vec::new();
            header.write_framed(&mut prefix)?;
            let mut hasher = Sha256::new();
            hasher.update(&prefix);
            drop(prefix);
            let verified = VerifyingReader::new(name.checksum, hasher, payload);
            Box::new(Cursor::new(framed).chain(compressors.lease(Box::new(verified), level)))
        }
    };
    Ok(Body {
        len: None,
        body: BodyData::Stream(body),
        payload: Some(size),
        stored_content: false,
    })
}

/// Returns the error of a failed upload of the file `name` of the tree
/// `model` when the failure is a read of the file, or `None` for another
/// failure.
///
/// A read that finds other bytes than the hash pass gives
/// [`ChecksumMismatch`](crate::remote::Error::ChecksumMismatch), and each
/// other failed read gives [`Walk`](crate::remote::Error::Walk). Each names
/// the path of the file.
fn changed_file(model: &TreeModel, name: &ObjectName, e: &crate::remote::Error) -> Option<Error> {
    let crate::remote::Error::Io(io) = e else {
        return None;
    };
    if name.ty != ObjectType::File {
        return None;
    }
    let path = model.source_path(name)?;
    let error = if io.kind() == std::io::ErrorKind::InvalidData {
        crate::remote::Error::ChecksumMismatch(format!(
            "the file {} changed after the hash pass: {io}",
            path.display()
        ))
    } else {
        crate::remote::Error::Walk {
            path,
            source: std::io::Error::new(io.kind(), io.to_string()),
        }
    };
    Some(Error::Remote(error))
}

/// A body that counts the bytes that it gives, and gives them to a progress
/// handle as content bytes.
struct Counted<'a> {
    inner: Box<dyn AsyncRead + Unpin + Send + 'a>,
    read: &'a AtomicU64,
    progress: Option<&'a PushProgress>,
}

impl AsyncRead for Counted<'_> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<std::io::Result<usize>> {
        let polled = Pin::new(&mut self.inner).poll_read(cx, buf);
        if let Poll::Ready(Ok(n)) = polled {
            self.read.fetch_add(n as u64, Ordering::Relaxed);
            if let Some(progress) = self.progress {
                progress.add_content(n as u64);
            }
        }
        polled
    }
}

#[cfg(test)]
mod tests {
    use ostrya_core::RepoMode;

    use super::super::test_repo::{Scratch, commit_tree};
    use super::*;

    #[test]
    fn the_namespace_comes_from_the_ref_and_the_bucket_id() {
        let a = Some("org.example.A");
        let r = |text: &str| -> Ref { text.parse().unwrap() };
        let mirror = || Namespace::Mirror {
            id: "org.example.B".into(),
        };
        assert_eq!(Namespace::of(&r("main"), None), Namespace::Local);
        assert_eq!(Namespace::of(&r("main"), a), Namespace::Local);
        assert_eq!(
            Namespace::of(&r("@org.example.A:main"), a),
            Namespace::Local
        );
        assert_eq!(Namespace::of(&r("@org.example.B:main"), a), mirror());
        assert_eq!(Namespace::of(&r("@org.example.B:main"), None), mirror());
        assert_eq!(Namespace::Local.key("a/b"), "refs/heads/a/b");
        assert_eq!(mirror().key("main"), "refs/mirrors/org.example.B/main");
    }

    #[test]
    fn the_options_of_a_session_push_are_refused() {
        refuse_options(&RepoPushOptions {
            refspecs: vec![
                "main".into(),
                "origin:main:dst".into(),
                "a:b".into(),
                "main:@org.example.X:a".into(),
            ],
            ..RepoPushOptions::default()
        })
        .unwrap();
        for (opts, needle) in [
            (
                RepoPushOptions {
                    tags: vec![Ref::local("v1")],
                    ..RepoPushOptions::default()
                },
                "tags",
            ),
            (
                RepoPushOptions {
                    compression: Compression::Deflate { level: 6 },
                    ..RepoPushOptions::default()
                },
                "compression",
            ),
            (
                RepoPushOptions {
                    refspecs: vec!["main".into(), ":old".into()],
                    ..RepoPushOptions::default()
                },
                "':old' is a delete",
            ),
            (
                RepoPushOptions {
                    refspecs: vec!["main".into(), ":@org.example.X:a".into()],
                    ..RepoPushOptions::default()
                },
                "':@org.example.X:a' is a delete",
            ),
        ] {
            match refuse_options(&opts) {
                Err(Error::Remote(crate::remote::Error::InvalidInput(message))) => {
                    assert!(message.contains(needle), "{message}")
                }
                other => panic!("{needle}: {other:?}"),
            }
        }
    }

    /// The walk finds a tip on the parent chain, and stops at a partial
    /// commit, at an absent commit, and at the root.
    #[test]
    fn a_fast_forward_needs_the_tip_on_the_local_chain() {
        ostrya_rt::block_on(async {
            let scratch = Scratch::new("bucket-ff");
            let repo = scratch.create(RepoMode::Archive).await;
            let c1 = commit_tree(&repo, &scratch, "main", None, b"1").await;
            let c2 = commit_tree(&repo, &scratch, "main", Some(c1), b"2").await;
            let c3 = commit_tree(&repo, &scratch, "main", Some(c2), b"3").await;
            let other = commit_tree(&repo, &scratch, "other", None, b"x").await;
            let mut commits = Commits::default();
            assert!(repo.fast_forward(c3, c1, &mut commits).await.unwrap());
            assert!(repo.fast_forward(c3, c2, &mut commits).await.unwrap());
            assert!(!repo.fast_forward(c3, other, &mut commits).await.unwrap());
            assert!(!repo.fast_forward(c1, c3, &mut commits).await.unwrap());
            // A tip beyond a partial commit is no ancestor.
            std::fs::write(
                repo.path()
                    .join("state")
                    .join(format!("{}.commitpartial", c2.to_hex())),
                b"",
            )
            .unwrap();
            let mut commits = Commits::default();
            assert!(!repo.fast_forward(c3, c1, &mut commits).await.unwrap());
            // A tip that the repository does not hold is no ancestor.
            let mut commits = Commits::default();
            let absent = Checksum::from_bytes([9; 32]);
            assert!(!repo.fast_forward(c3, absent, &mut commits).await.unwrap());
        });
    }

    #[test]
    fn the_object_key_is_the_archive_path() {
        let name = ObjectName::new(Checksum::from_bytes([0xab; 32]), ObjectType::File);
        assert_eq!(
            object_key(&name),
            format!("objects/ab/{}.filez", "ab".repeat(31))
        );
    }
}