ostrya 0.19.1

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
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
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
//! The archive view of a repository.
//!
//! The `ostree` command pulls over HTTP from a repository whose `config`
//! states the archive mode. It requests the files of the archive layout. An
//! [`ArchiveView`] answers these requests over a repository of any mode. For
//! a request path, it gives the bytes or a stream to serve, a not-found, or a
//! refusal. A server maps the answers onto its protocol.
//!
//! - [`ArchiveView::get`] gives the [`ArchiveAnswer`] for a `GET`.
//! - [`ArchiveView::head`] gives the [`ArchiveHead`] for a `HEAD`.
//! - [`ArchiveView`] states the [routing](ArchiveView#routing) of a path, the
//!   [read access](ArchiveView#read-access), and the
//!   [file access](ArchiveView#file-access).

use std::fmt;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, ready};

use futures_io::AsyncRead;
use ostrya_core::{Checksum, DeflateReader, RepoMode};
use ostrya_fetch::Priority;
use ostrya_fetch::gate::{Acquire, Gate, Permit};
use ostrya_rt::FileReader;
use rustix::io::Errno;

use crate::access::{AuthItem, ReadAccess};
use crate::config::{RepoConfig, archive};
use crate::error::Result;
use crate::file::{Contained, ContentReader, FileKind};
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, Opened, Reason, RepoDir, RootFile, Stat};
use crate::summary::{ACCESS_SUFFIX, SIG_SUFFIX, access_file_bytes, open_summary_dir};
use crate::write::archive_level;

/// The maximum number of `.filez` objects that one view deflates at one time.
///
/// Each of these objects holds a compressor and two 64 KiB buffers.
pub const MAX_COMPRESSORS: usize = 16;

/// The archive view over one repository.
///
/// The view is `Send + Sync`, so one view serves every connection of a
/// server.
///
/// # Routing
///
/// - `config`: the view builds it for each request. It holds a `[core]`
///   group with `repo_version=1` and `mode=archive-z2`. Then comes
///   `collection-id`, and in an `archive` repository `indexed-deltas`, with
///   the values of the repository, if the repository sets them. The view
///   serves no other key.
/// - `summary` and `summary.sig`: the view serves the files of the summary
///   of the item of the client, as stored (see
///   [Read access](ArchiveView#read-access)). Such a summary states the mode
///   `archive-z2`. The view never serves `summary` and `summary.sig` at the
///   repository root.
/// - The files under `refs/` and `extensions/`, and the `.commit`,
///   `.dirtree`, `.dirmeta`, and `.commitmeta` objects: the view serves them
///   as stored, to a client that reads them. `extensions/ostrya` and each
///   path under it are not found.
/// - In an `archive` repository, the view also serves the `.filez` objects
///   and the files under `deltas/` and `delta-indexes/` as stored.
/// - In every other mode, the view builds a `.filez` object on request from
///   the stored content object. [`get`](ArchiveView::get) states the format
///   of the body. The files under `deltas/` and `delta-indexes/` are not
///   found in these modes, and the summary of an item names no delta.
/// - A `.file` path is not found. Every path outside these families is not
///   found.
/// - The view refuses a path with an empty component, or with a `.` at the
///   start of a component. It also refuses `tmp/` and `state/`.
///
/// The view refuses a path with a symlink on it, wherever the symlink leads.
/// One exception is a ref alias: a symlink at the last component of a path
/// under `refs/`. If the alias names a ref that is a regular file under
/// `refs/`, the view serves that ref. The view follows one link, so it
/// refuses an alias of an alias.
///
/// # Read access
///
/// Each request carries the [`ReadAccess`] of its client. The view checks
/// it before it opens a file, so it reads no ref that the client cannot
/// read:
///
/// - A path under `refs/` needs [`ReadAccess::can_read_path`]. So
///   `refs/heads/NAME` and `refs/mirrors/ID/NAME` need `r` on `NAME`. A
///   path under `refs/mirrors/` of the own collection id is refused. Each
///   other path under `refs/` is refused, `refs/remotes/` included.
/// - An alias also needs [`ReadAccess::can_read_path`] on its target.
/// - `config`, the objects, and the files under `extensions/`, `deltas/`,
///   and `delta-indexes/` need no right.
///
/// A path that the client cannot read is refused.
///
/// `summary` and `summary.sig` give the files of the summary of the item of
/// the client, which
/// [`Repo::regenerate_summaries`](crate::Repo::regenerate_summaries) writes
/// (section "Files"): `extensions/ostrya/summary/HEX` and
/// `extensions/ostrya/summary/HEX.sig`, for each item, `anonymous`
/// included. For each request, the view opens the file first, and then reads the
/// `.access` file of the item:
///
/// - An item with no summary ([`ReadAccess::summary_digest`] is `None`)
///   gets [`ArchiveAnswer::NotFound`].
/// - When the `.access` file holds another digest than the access digest of
///   the item, or does not exist while the file exists, the answer is
///   [`ArchiveAnswer::StaleSummary`].
/// - Else the view serves the file, or answers not found when the file does
///   not exist.
///
/// Before it serves the file, the view checks that the name of the file
/// still names the file that it opened. If a write replaced the file during
/// the request, the view starts again, at most three times, and then
/// answers not found.
///
/// The view opens these paths with no symlink followed, as for each stored
/// file. A symlink on the path of the `.access` file or of the file is
/// refused. The view opens `extensions/ostrya/summary` as a directory
/// handle, so the process needs read permission on that directory.
///
/// # File access
///
/// The view opens a stored file with one `openat2` with `RESOLVE_BENEATH`,
/// `RESOLVE_NO_SYMLINKS`, and `O_NONBLOCK`, relative to the handle of the
/// repository root or of `objects/`, and checks its type with one `statx`.
/// A symlink at any component gives refused, except a ref alias. An entry
/// that is not a regular file, such as a FIFO, a directory, or a socket, is
/// not found, and its open does not block. The repository handle opened the
/// root and `objects/`. The open of the handle refuses a symlink at
/// `objects`. The open has no fallback: on a kernel without `openat2`, each
/// read of a stored file fails.
///
/// The view reads the repository `config` again if its inode number, size,
/// modification time, or change time differs from the last parse. One
/// `statx` of `config` with no symlink followed reads these values. The next
/// answer then shows the change. One request reads a changed file, and the
/// requests that see the same change wait for its parse.
pub struct ArchiveView {
    repo: Repo,
    /// The `config` of the last parse and the `statx` fields it was read
    /// under.
    config: Mutex<Option<ConfigSnapshot>>,
    /// One permit, held by the request that reads a changed `config`.
    refresh: Arc<Gate>,
    compressors: Arc<Compressors>,
    /// The DEFLATE level of each built `.filez`, or `None` for the
    /// `[archive] zlib-level` of `config`.
    level: Option<u8>,
    /// How many times the view read `config`, for the tests of the reuse.
    #[cfg(test)]
    config_reads: std::sync::atomic::AtomicUsize,
}

/// The answer of the view for one request path.
pub enum ArchiveAnswer {
    /// The built `config`.
    Bytes(Vec<u8>),
    /// A stream to serve: a stored file, or a `.filez` built on request.
    ///
    /// For a stored file, `len` comes from its `fstat`. For a built `.filez`,
    /// `len` is `None`. If the caller drops the stream before its first read,
    /// the stream reads no byte, and a built `.filez` does no deflate work.
    Stream {
        /// The number of bytes that the stream gives, if it is known.
        len: Option<u64>,
        /// The bytes to serve.
        body: Box<dyn AsyncRead + Unpin + Send>,
    },
    /// The answer for a path with nothing to serve.
    ///
    /// The view gives this answer for:
    ///
    /// - a `.file` path
    /// - a path under `deltas/` or `delta-indexes/` in a mode other than
    ///   `archive`
    /// - a path outside the served families
    /// - a served path with nothing at it.
    NotFound,
    /// The answer for a path that the view refuses.
    ///
    /// The view gives this answer for:
    ///
    /// - a path with an empty component, or with a `.` at the start of a
    ///   component
    /// - `tmp/` and `state/`
    /// - a path with a symlink on it that is no ref alias
    /// - a path that the [`ReadAccess`] of the request does not read.
    Refused,
    /// The answer for `summary` or `summary.sig` when the `.access` file of
    /// the item of the client holds another digest than the access digest of
    /// the item, or does not exist while the file exists.
    ///
    /// The summary of the item does not match the client groups. A server
    /// answers as for [`NotFound`](ArchiveAnswer::NotFound), and tells the
    /// operator to write the summaries again.
    StaleSummary {
        /// The auth item of the client.
        item: AuthItem,
    },
}

/// The answer of the view for one `HEAD` request path.
///
/// Each variant matches the [`ArchiveAnswer`] variant for the same path.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ArchiveHead {
    /// The answer for a path that the view serves.
    ///
    /// `len` is the length that a `GET` gives. It is `None` for a `.filez`
    /// built on request.
    Found {
        /// The number of bytes that a `GET` gives, if it is known.
        len: Option<u64>,
    },
    /// The same answer as [`ArchiveAnswer::NotFound`].
    NotFound,
    /// The same answer as [`ArchiveAnswer::Refused`].
    Refused,
    /// The same answer as [`ArchiveAnswer::StaleSummary`]. The item is the
    /// item of the [`ReadAccess`] of the request.
    StaleSummary,
}

impl fmt::Debug for ArchiveAnswer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArchiveAnswer::Bytes(bytes) => f.debug_tuple("Bytes").field(&bytes.len()).finish(),
            ArchiveAnswer::Stream { len, .. } => f
                .debug_struct("Stream")
                .field("len", len)
                .finish_non_exhaustive(),
            ArchiveAnswer::NotFound => f.write_str("NotFound"),
            ArchiveAnswer::Refused => f.write_str("Refused"),
            ArchiveAnswer::StaleSummary { item } => {
                f.debug_struct("StaleSummary").field("item", item).finish()
            }
        }
    }
}

impl ArchiveView {
    /// Creates the view over `repo`.
    ///
    /// The view reads nothing until a request needs it.
    pub fn new(repo: Repo) -> ArchiveView {
        ArchiveView {
            repo,
            config: Mutex::new(None),
            refresh: Arc::new(Gate::new(1)),
            level: None,
            #[cfg(test)]
            config_reads: std::sync::atomic::AtomicUsize::new(0),
            compressors: Arc::new(Compressors {
                gate: Arc::new(Gate::new(MAX_COMPRESSORS)),
                idle: Mutex::new(Vec::new()),
                #[cfg(test)]
                leases: std::sync::atomic::AtomicUsize::new(0),
            }),
        }
    }

    /// Creates the view over `repo` that builds each `.filez` at the DEFLATE
    /// level `level`, 1 to 9, in place of the `[archive] zlib-level` of the
    /// repository.
    #[cfg(all(feature = "push", feature = "s3"))]
    pub(crate) fn with_zlib_level(repo: Repo, level: u8) -> ArchiveView {
        ArchiveView {
            level: Some(level),
            ..ArchiveView::new(repo)
        }
    }

    /// Returns the answer for one `GET` request path of a client with the
    /// read rights `access`.
    ///
    /// The path is relative to the repository root and has no leading `/`.
    /// [`ArchiveView`](ArchiveView#routing) states the routing and the
    /// [read access](ArchiveView#read-access).
    ///
    /// # Built `.filez` objects
    ///
    /// In a mode other than `archive`, the view builds a `.filez` object on
    /// request from the stored content object. The body is the archive file
    /// header, then the payload in raw DEFLATE at `[archive] zlib-level`. The
    /// length of the stream is unknown.
    ///
    /// The body takes a compressor from a pool of at most [`MAX_COMPRESSORS`]
    /// when it first reads past the header. It gives the compressor back when
    /// it ends or when the caller drops it. While the body waits for a
    /// compressor, its read is pending. A body dropped before that read does
    /// no deflate work.
    ///
    /// The payload must hold the size that the header states. If the stored
    /// file ends sooner, the body fails with `io::ErrorKind::UnexpectedEof`.
    /// If it holds more, the body fails with `io::ErrorKind::InvalidData`. An
    /// error of the body is sticky, so a read after it fails too.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] if the `statx` or the read of `config` fails, for the
    ///   path `config` or a built `.filez`.
    /// - [`Error::InvalidFormat`] or [`Error::Core`] if `config` is not a
    ///   valid repository config, for the path `config` or a built `.filez`.
    /// - [`Error::Io`] if the walk to a stored file fails with an error that
    ///   gives no not-found and no refusal. A directory that the process
    ///   cannot search gives this error.
    /// - [`Error::Core`] if `[archive] zlib-level` is not an integer, for a
    ///   built `.filez`.
    /// - [`Error::Io`] if the load of the content object for a built `.filez`
    ///   fails with an error other than a missing object or a symlink.
    /// - [`Error::InvalidFormat`] or [`Error::Core`] if the content object
    ///   for a built `.filez` is not a valid object, or its archive header
    ///   cannot be written.
    ///
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn get(&self, path: &str, access: &ReadAccess) -> Result<ArchiveAnswer> {
        match classify(path, self.repo.mode()) {
            Route::Config => Ok(ArchiveAnswer::Bytes(built_config(
                &*self.current_config().await?,
                self.repo.mode(),
            ))),
            Route::Stored {
                anchor,
                path,
                alias_ok,
            } => Ok(match self.stored(anchor, path, alias_ok, access).await? {
                Walked::File(file, len) => ArchiveAnswer::Stream {
                    len: Some(len),
                    body: Box::new(FileReader::with_len_hint(file.file, len)),
                },
                Walked::NotFound => ArchiveAnswer::NotFound,
                Walked::Refused | Walked::Alias(_) => ArchiveAnswer::Refused,
            }),
            Route::Summary { sig } => Ok(match self.summary(sig, access).await? {
                Summarized::Walked(Walked::File(file, len)) => ArchiveAnswer::Stream {
                    len: Some(len),
                    body: Box::new(FileReader::with_len_hint(file.file, len)),
                },
                Summarized::Walked(Walked::NotFound) => ArchiveAnswer::NotFound,
                Summarized::Walked(Walked::Refused | Walked::Alias(_)) => ArchiveAnswer::Refused,
                Summarized::Stale => ArchiveAnswer::StaleSummary {
                    item: access.item().clone(),
                },
            }),
            Route::BuiltFilez(checksum) => self.built_filez(&checksum).await,
            Route::NotFound => Ok(ArchiveAnswer::NotFound),
            Route::Refused => Ok(ArchiveAnswer::Refused),
        }
    }

    /// Returns the answer for one `HEAD` request path of a client with the
    /// read rights `access`.
    ///
    /// The answer matches the answer of [`get`](ArchiveView::get) for a `GET`
    /// of the same path and the same rights. The view uses the same routing
    /// and the same walk. It opens a stored file and does not read it.
    ///
    /// For a `.filez` built on request, the view checks that the object is
    /// there. It reads no xattr and no byte of the object. Because of this, a
    /// `bare-split-xattrs` object is found even if a `GET` cannot read its
    /// xattrs.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] if the `statx` or the read of `config` fails, for the
    ///   path `config`.
    /// - [`Error::InvalidFormat`] or [`Error::Core`] if `config` is not a
    ///   valid repository config, for the path `config`.
    /// - [`Error::Io`] if the walk to a stored file fails with an error that
    ///   gives no not-found and no refusal.
    /// - [`Error::Io`] if the check of the content object for a built `.filez`
    ///   fails with an error other than a missing object or a symlink.
    /// - [`Error::InvalidFormat`] if the content object for a built `.filez`
    ///   is neither a regular file nor a symlink.
    /// - [`Error::InvalidFormat`] if the repository mode is `bare-split-xattrs`
    ///   and the object has no `.file-xattrs-link` entry next to it. The view
    ///   checks the object before this entry, so an absent object gives
    ///   [`ArchiveHead::NotFound`], as [`get`](ArchiveView::get) gives
    ///   [`ArchiveAnswer::NotFound`].
    ///
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn head(&self, path: &str, access: &ReadAccess) -> Result<ArchiveHead> {
        match classify(path, self.repo.mode()) {
            Route::Config => Ok(ArchiveHead::Found {
                len: Some(
                    built_config(&*self.current_config().await?, self.repo.mode()).len() as u64,
                ),
            }),
            Route::Stored {
                anchor,
                path,
                alias_ok,
            } => Ok(match self.stored(anchor, path, alias_ok, access).await? {
                Walked::File(_, len) => ArchiveHead::Found { len: Some(len) },
                Walked::NotFound => ArchiveHead::NotFound,
                Walked::Refused | Walked::Alias(_) => ArchiveHead::Refused,
            }),
            Route::Summary { sig } => Ok(match self.summary(sig, access).await? {
                Summarized::Walked(Walked::File(_, len)) => ArchiveHead::Found { len: Some(len) },
                Summarized::Walked(Walked::NotFound) => ArchiveHead::NotFound,
                Summarized::Walked(Walked::Refused | Walked::Alias(_)) => ArchiveHead::Refused,
                Summarized::Stale => ArchiveHead::StaleSummary,
            }),
            Route::BuiltFilez(checksum) => {
                let repo = self.repo.clone();
                let probed =
                    ostrya_rt::unblock(move || repo.probe_contained_blocking(&checksum)).await;
                Ok(match probed? {
                    Contained::Found(()) => ArchiveHead::Found { len: None },
                    Contained::NotFound => ArchiveHead::NotFound,
                    Contained::Refused => ArchiveHead::Refused,
                })
            }
            Route::NotFound => Ok(ArchiveHead::NotFound),
            Route::Refused => Ok(ArchiveHead::Refused),
        }
    }

    /// Returns the parsed repository `config`.
    ///
    /// One `statx` shows if the file changed since the last parse. An
    /// unchanged file reuses that parse.
    async fn current_config(&self) -> Result<Arc<RepoConfig>> {
        let repo = self.repo.clone();
        let stat =
            ostrya_rt::unblock(move || repo.root_dir().lstat(RootFile::Config.name())).await?;
        self.config_for(&stat).await
    }

    /// Returns the parsed repository `config` for its `statx` fields `stat`.
    ///
    /// One request reads a change of the file. The requests that wait at the
    /// same time take its parse if they saw the same change.
    async fn config_for(&self, stat: &Stat) -> Result<Arc<RepoConfig>> {
        let key = ConfigKey::of(stat);
        if let Some(config) = self.cached_config(key) {
            return Ok(config);
        }
        let _refresh = self.refresh.acquire(Priority::Normal).await;
        if let Some(config) = self.cached_config(key) {
            return Ok(config);
        }
        #[cfg(test)]
        self.config_reads
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        // The view reads the file after the `statx`, so the parse is at least
        // as new as its key. A later change gives another key.
        let config = Arc::new(self.repo.read_config_file().await?);
        *self.config.lock().expect("archive view config mutex") = Some(ConfigSnapshot {
            key,
            config: config.clone(),
        });
        Ok(config)
    }

    /// Returns the parse stored under `key`, if the last parse has that key.
    fn cached_config(&self, key: ConfigKey) -> Option<Arc<RepoConfig>> {
        let snapshot = self.config.lock().expect("archive view config mutex");
        snapshot
            .as_ref()
            .filter(|snapshot| snapshot.key == key)
            .map(|snapshot| snapshot.config.clone())
    }

    /// Opens a stored file through the safe walk.
    ///
    /// A path under the repository root that `access` does not read is
    /// refused before the walk. The target of an alias must also be a path
    /// that `access` reads.
    async fn stored(
        &self,
        anchor: Anchor,
        path: String,
        alias_ok: bool,
        access: &ReadAccess,
    ) -> Result<Walked> {
        if anchor == Anchor::Repo && !readable(&path, access) {
            return Ok(Walked::Refused);
        }
        let repo = self.repo.clone();
        let access = access.clone();
        let walked = ostrya_rt::unblock(move || {
            let root = match anchor {
                Anchor::Repo => repo.root_dir(),
                Anchor::Objects => repo.objects(),
            };
            match walk(root, &path, alias_ok)? {
                Walked::Alias(body) => {
                    let link_dir = path.rsplit_once('/').map_or("", |(dir, _)| dir);
                    match resolve_alias(link_dir, &body) {
                        Some(target) if access.can_read_path(&target) => walk(root, &target, false),
                        _ => Ok(Walked::Refused),
                    }
                }
                walked => Ok(walked),
            }
        })
        .await?;
        Ok(walked)
    }

    /// Opens the file of the summary of the item of `access`: the summary,
    /// or its signature file with `sig`.
    ///
    /// An item with no summary gives not found. The call opens the file
    /// first, and then reads the `.access` file of the item, which must hold
    /// the access digest of the item, else the result is
    /// [`Summarized::Stale`]. With no `.access` file, the result is
    /// [`Summarized::Stale`] when the file exists, and not found when it
    /// does not. The walk to each file follows no symlink.
    ///
    /// A matching `.access` file covers the file that its directory holds
    /// at the read. So after the read, the call checks that the name of the
    /// file still names the open file. If not, a write replaced the file
    /// during the request, and the call starts again, at most
    /// [`SUMMARY_TRIES`] times. Then the result is not found.
    async fn summary(&self, sig: bool, access: &ReadAccess) -> Result<Summarized> {
        let Some(files) = access.summary_files() else {
            return Ok(Summarized::Walked(Walked::NotFound));
        };
        let name = if sig {
            format!("{}{SIG_SUFFIX}", files.stem)
        } else {
            files.stem.clone()
        };
        let access_name = format!("{}{ACCESS_SUFFIX}", files.stem);
        let want = access_file_bytes(&files.digest);
        let repo = self.repo.clone();
        let summarized = ostrya_rt::unblock(move || -> io::Result<Summarized> {
            // The one open of the directory of the summary.
            let dir = match open_summary_dir(repo.root_dir()) {
                Ok(Some(dir)) => dir,
                Ok(None) => return Ok(Summarized::Walked(Walked::NotFound)),
                Err(e) => return walk_error(e).map(Summarized::Walked),
            };
            for _ in 0..SUMMARY_TRIES {
                let at = &dir;
                // The file first, so a write between the two opens cannot
                // pair a matching `.access` file with a later file.
                let file = walk(at, &name, false)?;
                let current = walk(at, &access_name, false)?;
                let file = match (current, file) {
                    (Walked::File(current, _), file) => {
                        if !holds(&current.file, &want)? {
                            return Ok(Summarized::Stale);
                        }
                        file
                    }
                    (Walked::NotFound, Walked::File(..)) => return Ok(Summarized::Stale),
                    // With no `.access` file and no file, no summary was
                    // written for the item, and the answer is not found.
                    (Walked::NotFound, file) => file,
                    (current, _) => return Ok(Summarized::Walked(current)),
                };
                let Walked::File(file, len) = file else {
                    return Ok(Summarized::Walked(file));
                };
                if names_file(at, &name, &file)? {
                    return Ok(Summarized::Walked(Walked::File(file, len)));
                }
            }
            Ok(Summarized::Walked(Walked::NotFound))
        })
        .await?;
        Ok(summarized)
    }

    /// Builds a `.filez` from the stored content object `checksum`.
    ///
    /// The `statx` of `config` and the load of the object share one call on
    /// the blocking pool. A view with a fixed level reads no `config`.
    async fn built_filez(&self, checksum: &Checksum) -> Result<ArchiveAnswer> {
        let repo = self.repo.clone();
        let key = *checksum;
        let fixed = self.level;
        let (stat, loaded) = ostrya_rt::unblock(move || {
            (
                fixed
                    .is_none()
                    .then(|| repo.root_dir().lstat(RootFile::Config.name())),
                repo.load_contained_blocking(&key),
            )
        })
        .await;
        let level = match (fixed, stat) {
            (Some(level), _) => level,
            (None, Some(stat)) => {
                archive_level(self.config_for(&stat?).await?.get::<archive::ZlibLevel>()?)
            }
            (None, None) => unreachable!("a view with no fixed level reads the statx of config"),
        };
        let contained = match loaded? {
            Contained::Found(contained) => contained,
            Contained::NotFound => return Ok(ArchiveAnswer::NotFound),
            Contained::Refused => return Ok(ArchiveAnswer::Refused),
        };
        let (file, reader) = self.repo.contained_file(checksum, contained);
        let (size, payload) = match file.kind {
            FileKind::Regular { size } => (size, Some(reader)),
            // A symlink is the archive header alone.
            FileKind::Symlink { .. } => (0, None),
        };
        let mut header = Vec::new();
        file.header().write_framed_archive(size, &mut header)?;
        Ok(ArchiveAnswer::Stream {
            len: None,
            body: Box::new(BuiltFilez {
                header,
                pos: 0,
                payload: match payload {
                    Some(source) => Payload::Waiting {
                        source: Exact {
                            source,
                            remaining: size,
                        },
                        level,
                        acquire: None,
                    },
                    None => Payload::Done,
                },
                compressors: self.compressors.clone(),
            }),
        })
    }
}

/// Returns `true` if `access` reads the stored file at `path` under the
/// repository root.
///
/// A path under `refs/` needs [`ReadAccess::can_read_path`]. Each other path
/// needs no right. The function reads no file.
fn readable(path: &str, access: &ReadAccess) -> bool {
    !path.starts_with("refs/") || access.can_read_path(path)
}

/// The outcome of the walk to a file of a summary.
enum Summarized {
    /// The walk to the file.
    Walked(Walked),
    /// The `.access` file holds another digest than the access digest of the
    /// item, or does not exist while the file exists.
    Stale,
}

/// The number of times that a request for a file of a summary opens the
/// file while a write replaces it, before the answer is not found.
const SUMMARY_TRIES: usize = 3;

/// Returns `true` if `file` holds exactly `want`. The read stops one byte
/// past the length of `want`.
pub(crate) fn holds(file: &std::fs::File, want: &[u8]) -> io::Result<bool> {
    use std::io::Read;

    let mut buf = Vec::with_capacity(want.len() + 1);
    file.take(want.len() as u64 + 1).read_to_end(&mut buf)?;
    Ok(buf == want)
}

/// Returns `true` if `name` in `dir` is the open file `file`, with no
/// symlink followed.
///
/// The call compares the device and the inode of [`RepoDir::lstat`] of
/// `name` with those of `file`. An absent `name` gives `false`.
fn names_file(dir: &RepoDir, name: &str, file: &Opened) -> io::Result<bool> {
    let named = dir.lstat(name).optional().map_err(io_error)?;
    Ok(named.is_some_and(|n| n.dev == file.stat.dev && n.ino == file.stat.ino))
}

/// The parsed `config` and the key it was parsed under.
struct ConfigSnapshot {
    key: ConfigKey,
    config: Arc<RepoConfig>,
}

/// The `statx` fields that show if `config` changed: the inode number,
/// the size, and the modification and change times in nanoseconds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ConfigKey {
    ino: u64,
    size: u64,
    mtime: (i64, u32),
    ctime: (i64, u32),
}

impl ConfigKey {
    fn of(stat: &Stat) -> ConfigKey {
        ConfigKey {
            ino: stat.ino,
            size: stat.size,
            mtime: (stat.mtime_sec, stat.mtime_nsec),
            ctime: (stat.ctime_sec, stat.ctime_nsec),
        }
    }
}

/// Returns the `config` of an archive repository with the values of `config`.
///
/// `indexed-deltas` is copied in an `archive` repository alone, because the
/// view serves `delta-indexes/` in that mode alone.
fn built_config(config: &RepoConfig, mode: RepoMode) -> Vec<u8> {
    let mut out = String::from("[core]\nrepo_version=1\nmode=archive-z2\n");
    let keys: &[&str] = if mode.is_archive() {
        &["collection-id", "indexed-deltas"]
    } else {
        &["collection-id"]
    };
    for key in keys {
        if let Some(value) = config.keyfile().get_value("core", key) {
            out.push_str(key);
            out.push('=');
            out.push_str(value);
            out.push('\n');
        }
    }
    out.into_bytes()
}

/// The directory a stored path walks from.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Anchor {
    /// The repository root.
    Repo,
    /// `objects/`.
    Objects,
}

/// What a request path names.
#[derive(Debug, Eq, PartialEq)]
enum Route {
    Config,
    /// `summary`, or `summary.sig` with `sig`: a file of the summary of the
    /// item of the client.
    Summary {
        sig: bool,
    },
    /// A stored file at `path` under `anchor`. `alias_ok` allows a ref alias
    /// at the last component.
    Stored {
        anchor: Anchor,
        path: String,
        alias_ok: bool,
    },
    /// A `.filez` built from the content object of this checksum.
    BuiltFilez(Checksum),
    NotFound,
    Refused,
}

/// Returns `true` if the router refuses a path component by its name alone.
///
/// The router refuses an empty component and a component that starts with
/// `.`. This covers `.`, `..`, `.lock`, and `.update.lock`.
fn refused_component(part: &str) -> bool {
    part.is_empty() || part.starts_with('.')
}

/// Classifies a request path. The function reads no file.
fn classify(path: &str, mode: RepoMode) -> Route {
    if path.is_empty() {
        return Route::NotFound;
    }
    if path.split('/').any(refused_component) {
        return Route::Refused;
    }
    let archive = mode.is_archive();
    let stored = |alias_ok| Route::Stored {
        anchor: Anchor::Repo,
        path: path.to_owned(),
        alias_ok,
    };
    // No component is empty here, so a `rest` holds one component or more.
    let (first, rest) = match path.split_once('/') {
        Some((first, rest)) => (first, Some(rest)),
        None => (path, None),
    };
    match (first, rest) {
        ("tmp" | "state", _) => Route::Refused,
        ("config", None) => Route::Config,
        ("summary", None) => Route::Summary { sig: false },
        ("summary.sig", None) => Route::Summary { sig: true },
        ("refs", Some(_)) => stored(true),
        ("extensions", Some(rest)) if rest == "ostrya" || rest.starts_with("ostrya/") => {
            Route::NotFound
        }
        ("extensions", Some(_)) => stored(false),
        ("deltas" | "delta-indexes", Some(_)) if archive => stored(false),
        ("objects", Some(rest)) => match rest.split_once('/') {
            Some((fanout, name)) if !name.contains('/') => object_route(fanout, name, archive),
            _ => Route::NotFound,
        },
        _ => Route::NotFound,
    }
}

/// Classifies `objects/<fanout>/<name>`.
fn object_route(fanout: &str, name: &str, archive: bool) -> Route {
    let Some((rest, ext)) = name.split_once('.') else {
        return Route::NotFound;
    };
    if fanout.len() != 2 || rest.len() != 62 {
        return Route::NotFound;
    }
    let Ok(checksum) = Checksum::from_hex_lower(&format!("{fanout}{rest}")) else {
        return Route::NotFound;
    };
    let stored = || Route::Stored {
        anchor: Anchor::Objects,
        path: format!("{fanout}/{name}"),
        alias_ok: false,
    };
    match ext {
        "commit" | "dirtree" | "dirmeta" | "commitmeta" => stored(),
        "filez" if archive => stored(),
        "filez" => Route::BuiltFilez(checksum),
        _ => Route::NotFound,
    }
}

/// The result of the safe walk.
pub(crate) enum Walked {
    /// A regular file, open, and its size.
    File(Opened, u64),
    NotFound,
    Refused,
    /// A symlink at the last component of a walk that allows a ref alias,
    /// with the bytes of its body.
    Alias(Vec<u8>),
}

/// The cap of the body of a ref alias, in bytes. A symlink body on Linux has
/// 4095 bytes at most.
const ALIAS_CAP: u64 = 4096;

/// Opens the regular file at `path` below `dir` and follows no symlink.
///
/// The open is [`RepoDir::open_regular`]: one `openat2` with
/// `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`, then one `statx` of the open
/// file. `O_NONBLOCK` keeps the open of a FIFO from a wait for a writer.
///
/// A symlink at a component gives refused. With `alias_ok`, a symlink at the
/// last component gives its body, which [`RepoDir::read_link`] reads. An
/// entry that is not a regular file, a component that is not a directory,
/// a name longer than the kernel accepts, and a path with nothing at it are
/// not found. A directory that the process cannot search fails the walk
/// with its error.
pub(crate) fn walk(dir: &RepoDir, path: &str, alias_ok: bool) -> io::Result<Walked> {
    match dir.open_regular(path) {
        Ok(opened) => {
            let len = opened.stat.size;
            Ok(Walked::File(opened, len))
        }
        Err(FsError::Invalid {
            reason: Reason::Symlink,
            ..
        }) if alias_ok => match dir.read_link(path, ALIAS_CAP) {
            Ok(body) => Ok(Walked::Alias(body)),
            Err(e) => walk_error(e),
        },
        Err(e) => walk_error(e),
    }
}

/// Returns the answer of the walk for the error `err` of an open.
///
/// A symlink, a path that leaves the repository, and an alias body over its
/// cap give refused. An absent entry, an entry that is not a regular file, a
/// component that is not a directory, and a name longer than the kernel
/// accepts give not found. Each other error fails the walk.
fn walk_error(err: FsError) -> io::Result<Walked> {
    match err {
        FsError::Absent { .. }
        | FsError::Invalid {
            reason: Reason::NotDirectory | Reason::NotRegular(_),
            ..
        } => Ok(Walked::NotFound),
        FsError::Invalid { .. } => Ok(Walked::Refused),
        FsError::Io(e) if e.raw_os_error() == Some(Errno::NAMETOOLONG.raw_os_error()) => {
            Ok(Walked::NotFound)
        }
        e => Err(io_error(e)),
    }
}

/// Returns the [`io::Error`] of `err`, through `From<FsError> for Error`
/// and then `From<Error> for io::Error`.
fn io_error(err: FsError) -> io::Error {
    crate::Error::from(err).into()
}

/// Resolves the body of a ref alias in the directory `link_dir`, which
/// starts with `refs`.
///
/// The function resolves `.` and `..` by name. The result is `None` for:
///
/// - an absolute body
/// - a body that is not UTF-8
/// - an empty component, which a trailing `/` gives
/// - a `..` that leaves `refs/`
/// - a component that the router refuses by name
/// - a result with no component under `refs/`.
pub(crate) fn resolve_alias(link_dir: &str, body: &[u8]) -> Option<String> {
    let body = std::str::from_utf8(body).ok()?;
    if body.starts_with('/') {
        return None;
    }
    // No component of `link_dir` or of the result is empty, so each `/`
    // separates two components.
    let mut target = link_dir.to_owned();
    for part in body.split('/') {
        match part {
            "" => return None,
            "." => {}
            ".." => {
                let (dir, _) = target.rsplit_once('/')?;
                target.truncate(dir.len());
            }
            part if refused_component(part) => return None,
            part => {
                if !target.is_empty() {
                    target.push('/');
                }
                target.push_str(part);
            }
        }
    }
    let under_refs = target
        .split_once('/')
        .is_some_and(|(first, _)| first == "refs");
    under_refs.then_some(target)
}

/// The compressors of one view: a gate of [`MAX_COMPRESSORS`] permits, and the
/// compressors that no body holds.
struct Compressors {
    gate: Arc<Gate>,
    idle: Mutex<Vec<DeflateReader<Exact>>>,
    /// The number of leases that the view gave. The tests use it to prove
    /// that a body dropped unread takes no lease.
    #[cfg(test)]
    leases: std::sync::atomic::AtomicUsize,
}

impl Compressors {
    /// Leases a compressor over `source` at `level`.
    ///
    /// The lease reuses an idle compressor if one is there.
    fn lease(self: &Arc<Self>, source: Exact, level: u8, permit: Permit) -> Lease {
        #[cfg(test)]
        self.leases
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let idle = self
            .idle
            .lock()
            .expect("archive view compressor mutex")
            .pop();
        let reader = match idle {
            Some(mut reader) => {
                reader.reset(source, level);
                reader
            }
            None => DeflateReader::new(source, level),
        };
        Lease {
            reader: Some(reader),
            compressors: self.clone(),
            _permit: permit,
        }
    }
}

/// A compressor held by one body.
///
/// When the lease drops, the compressor goes back to the idle ones before the
/// lease releases the permit.
struct Lease {
    reader: Option<DeflateReader<Exact>>,
    compressors: Arc<Compressors>,
    _permit: Permit,
}

impl Drop for Lease {
    fn drop(&mut self) {
        if let Some(mut reader) = self.reader.take() {
            // The descriptor of the object closes now. The compressor and its
            // buffers stay for the next body.
            drop(std::mem::replace(reader.get_mut(), Exact::empty()));
            self.compressors
                .idle
                .lock()
                .expect("archive view compressor mutex")
                .push(reader);
        }
    }
}

/// The body of a `.filez` built on request: the framed archive header, then
/// the deflated payload.
struct BuiltFilez {
    header: Vec<u8>,
    /// The bytes of `header` already read.
    pos: usize,
    payload: Payload,
    compressors: Arc<Compressors>,
}

/// The payload half of a built `.filez`.
enum Payload {
    /// The payload source, which waits for a compressor. The wait starts on
    /// the first read past the header.
    Waiting {
        source: Exact,
        level: u8,
        acquire: Option<Acquire>,
    },
    Deflating(Lease),
    /// The payload is at its end, or a symlink has no payload.
    Done,
    /// A read failed with an error of this kind. Each later read fails too,
    /// so a reader that reads again does not see the end of the stream.
    Failed(io::ErrorKind),
}

/// The payload source of a built `.filez`: the content reader, held to the
/// size the header states. A source that ends sooner, or holds more, fails
/// the read, so the body never ends with a payload of another length.
struct Exact {
    source: ContentReader,
    /// The bytes the source still has to give.
    remaining: u64,
}

impl Exact {
    /// Returns a source of no bytes that holds no descriptor.
    fn empty() -> Exact {
        Exact {
            source: ContentReader::empty(),
            remaining: 0,
        }
    }
}

impl AsyncRead for Exact {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let me = self.get_mut();
        if buf.is_empty() {
            return Poll::Ready(Ok(0));
        }
        // The read asks for one byte past the size, so a longer source shows.
        let want =
            usize::try_from(me.remaining.saturating_add(1)).map_or(buf.len(), |n| n.min(buf.len()));
        let n = ready!(Pin::new(&mut me.source).poll_read(cx, &mut buf[..want]))?;
        if n as u64 > me.remaining {
            return Poll::Ready(Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "the object holds more bytes than its size",
            )));
        }
        if n == 0 && me.remaining > 0 {
            return Poll::Ready(Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "the object ended before its size",
            )));
        }
        me.remaining -= n as u64;
        Poll::Ready(Ok(n))
    }
}

impl AsyncRead for BuiltFilez {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let BuiltFilez {
            header,
            pos,
            payload,
            compressors,
        } = self.get_mut();
        if buf.is_empty() {
            return Poll::Ready(Ok(0));
        }
        if *pos < header.len() {
            let n = buf.len().min(header.len() - *pos);
            buf[..n].copy_from_slice(&header[*pos..*pos + n]);
            *pos += n;
            return Poll::Ready(Ok(n));
        }
        loop {
            match payload {
                Payload::Done => return Poll::Ready(Ok(0)),
                Payload::Failed(kind) => {
                    return Poll::Ready(Err(io::Error::new(
                        *kind,
                        "the payload failed at an earlier read",
                    )));
                }
                Payload::Waiting { acquire, .. } => {
                    let acquire =
                        acquire.get_or_insert_with(|| compressors.gate.acquire(Priority::Normal));
                    let permit = ready!(Pin::new(acquire).poll(cx));
                    let Payload::Waiting { source, level, .. } =
                        std::mem::replace(payload, Payload::Done)
                    else {
                        unreachable!("the payload is waiting");
                    };
                    *payload = Payload::Deflating(compressors.lease(source, level, permit));
                }
                Payload::Deflating(lease) => {
                    let reader = lease
                        .reader
                        .as_mut()
                        .expect("a lease holds its compressor until it drops");
                    let read = ready!(Pin::new(reader).poll_read(cx, buf));
                    // The end of the stream and an error both give the
                    // compressor back.
                    match &read {
                        Ok(0) => *payload = Payload::Done,
                        Ok(_) => {}
                        Err(e) => *payload = Payload::Failed(e.kind()),
                    }
                    return Poll::Ready(read);
                }
            }
        }
    }
}

/// The view moves freely across tasks and threads, and so does the future of
/// a request.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    fn assert_send<T: Send>(_: &T) {}
    assert_send_sync::<ArchiveView>();
    let _ = |view: &ArchiveView, access: &ReadAccess| assert_send(&view.get("", access));
    let _ = |view: &ArchiveView, access: &ReadAccess| assert_send(&view.head("", access));
};

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::sync::atomic::Ordering;

    use futures_lite::AsyncReadExt;
    use ostrya_core::ObjectType;
    use rustix::fs::{FileType, Mode};

    use super::*;
    use crate::repo::CreateOptions;
    use crate::write::FileMeta;

    fn route(path: &str, mode: RepoMode) -> Route {
        classify(path, mode)
    }

    fn stored(anchor: Anchor, path: &str, alias_ok: bool) -> Route {
        Route::Stored {
            anchor,
            path: path.to_owned(),
            alias_ok,
        }
    }

    /// The rights of an anonymous client under the implicit group.
    fn anyone() -> ReadAccess {
        let config = config_of("[core]\nrepo_version=1\nmode=archive-z2\n");
        let access = crate::access::ClientAccess::from_config(&config).unwrap();
        ReadAccess::new(Arc::new(access), crate::access::AuthItem::Anonymous, None)
    }

    const HEX: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    #[test]
    fn the_router_names_each_family() {
        let (fanout, rest) = HEX.split_at(2);
        let object = |ext: &str| format!("objects/{fanout}/{rest}.{ext}");
        for mode in [RepoMode::Archive, RepoMode::BareUser] {
            assert_eq!(route("config", mode), Route::Config);
            assert_eq!(route("summary", mode), Route::Summary { sig: false });
            assert_eq!(route("summary.sig", mode), Route::Summary { sig: true });
            assert_eq!(
                route("refs/heads/a/b", mode),
                stored(Anchor::Repo, "refs/heads/a/b", true)
            );
            assert_eq!(
                route("extensions/x", mode),
                stored(Anchor::Repo, "extensions/x", false)
            );
            assert_eq!(
                route("extensions/ostrya-x/y", mode),
                stored(Anchor::Repo, "extensions/ostrya-x/y", false)
            );
            for path in [
                "extensions/ostrya",
                "extensions/ostrya/x",
                "extensions/ostrya/a/b",
            ] {
                assert_eq!(route(path, mode), Route::NotFound, "{path}");
            }
            for ext in ["commit", "dirtree", "dirmeta", "commitmeta"] {
                assert_eq!(
                    route(&object(ext), mode),
                    stored(Anchor::Objects, &format!("{fanout}/{rest}.{ext}"), false)
                );
            }
            assert_eq!(route(&object("file"), mode), Route::NotFound);
            assert_eq!(route(&object("tombstone-commit"), mode), Route::NotFound);
            assert_eq!(route(&object("file-xattrs-link"), mode), Route::NotFound);
            assert_eq!(
                route(&format!("objects/{fanout}/{}.commit", &rest[1..]), mode),
                Route::NotFound
            );
            assert_eq!(
                route(&format!("objects/AB/{rest}.commit"), mode),
                Route::NotFound
            );
            for path in ["", "refs", "objects", "extensions", "deltas", "other"] {
                assert_eq!(route(path, mode), Route::NotFound, "{path}");
            }
            for path in [
                ".lock",
                ".update.lock",
                "tmp",
                "tmp/x",
                "state",
                "state/x",
                "a/../config",
                "./config",
                "refs//heads",
                "refs/heads/",
                "/config",
                "refs/heads/.hidden",
            ] {
                assert_eq!(route(path, mode), Route::Refused, "{path}");
            }
        }
        assert_eq!(
            route(&object("filez"), RepoMode::Archive),
            stored(Anchor::Objects, &format!("{fanout}/{rest}.filez"), false)
        );
        assert_eq!(
            route(&object("filez"), RepoMode::Bare),
            Route::BuiltFilez(Checksum::from_hex(HEX).unwrap())
        );
        for path in ["deltas/ab/cd/superblock", "delta-indexes/ab/cd.index"] {
            assert_eq!(
                route(path, RepoMode::Archive),
                stored(Anchor::Repo, path, false)
            );
            assert_eq!(route(path, RepoMode::BareUserOnly), Route::NotFound);
        }
    }

    /// A deep path routes by its first components and keeps the whole path.
    /// A refused component anywhere in it refuses the path, and so does an
    /// empty one.
    #[test]
    fn the_router_takes_a_deep_path_whole() {
        let deep = format!("refs/heads/{}b", "a/".repeat(100_000));
        for mode in [RepoMode::Archive, RepoMode::BareUser] {
            assert_eq!(route(&deep, mode), stored(Anchor::Repo, &deep, true));
            for tail in ["/..", "/.", "/", "//c", "/.lock"] {
                let path = format!("{deep}{tail}");
                assert_eq!(route(&path, mode), Route::Refused, "{tail}");
            }
            let path = format!("{}refs/heads/x", "a/".repeat(100_000));
            assert_eq!(route(&path, mode), Route::NotFound);
            let path = format!("objects/{}x", "a/".repeat(100_000));
            assert_eq!(route(&path, mode), Route::NotFound);
            assert_eq!(route("objects/ab/cd/ef.commit", mode), Route::NotFound);
            assert_eq!(route("config/x", mode), Route::NotFound);
            assert_eq!(route("summary/x", mode), Route::NotFound);
            assert_eq!(route("tmp/a/b", mode), Route::Refused);
        }
    }

    #[test]
    fn an_alias_resolves_inside_refs_alone() {
        let resolve = |dir: &str, body: &str| resolve_alias(dir, body.as_bytes());
        let target = |t: &str| Some(t.to_owned());
        assert_eq!(resolve("refs/heads", "main"), target("refs/heads/main"));
        assert_eq!(
            resolve("refs/heads/a", "../b/./c"),
            target("refs/heads/b/c")
        );
        assert_eq!(
            resolve("refs/heads", "../remotes/o/main"),
            target("refs/remotes/o/main")
        );
        assert_eq!(resolve("refs/heads", "./main"), target("refs/heads/main"));
        assert_eq!(resolve("refs/heads", "../x"), target("refs/x"));
        assert_eq!(resolve("refs/heads", "../.."), None);
        assert_eq!(resolve("refs/heads", "../../summary"), None);
        assert_eq!(resolve("refs/heads", "../../refs/heads/x"), None);
        assert_eq!(resolve("refs/heads", "/etc/passwd"), None);
        assert_eq!(resolve("refs/heads", ".."), None);
        assert_eq!(resolve("refs/heads", ".lock"), None);
        assert_eq!(resolve("refs/heads", "main/"), None);
        assert_eq!(resolve("refs/heads", "a//main"), None);
        assert_eq!(resolve_alias("refs/heads", b"\xff"), None);
    }

    fn config_of(text: &str) -> RepoConfig {
        RepoConfig::parse(text).unwrap()
    }

    #[test]
    fn the_built_config_copies_two_keys() {
        assert_eq!(
            built_config(
                &config_of("[core]\nrepo_version=1\nmode=bare-user\n[remote \"o\"]\nurl=x\n"),
                RepoMode::BareUser
            ),
            b"[core]\nrepo_version=1\nmode=archive-z2\n"
        );
        assert_eq!(
            built_config(
                &config_of(
                    "[core]\nindexed-deltas=true\nmode=bare\nrepo_version=1\n\
                     collection-id=org.example.Repo\n[ex-ostrya]\nk=v\n"
                ),
                RepoMode::Bare
            ),
            b"[core]\nrepo_version=1\nmode=archive-z2\ncollection-id=org.example.Repo\n"
        );
        assert_eq!(
            built_config(
                &config_of(
                    "[core]\nindexed-deltas=true\nmode=archive-z2\nrepo_version=1\n\
                     collection-id=org.example.Repo\n[ex-ostrya]\nk=v\n"
                ),
                RepoMode::Archive
            ),
            b"[core]\nrepo_version=1\nmode=archive-z2\ncollection-id=org.example.Repo\n\
              indexed-deltas=true\n"
        );
    }

    fn scratch(tag: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("ostrya-archive-view-{}-{tag}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// `names_file` is `true` while the name names the open file, and
    /// `false` after a rename replaces the file and after a removal.
    #[test]
    fn a_replaced_file_no_more_has_its_name() {
        let dir = scratch("names-file");
        std::fs::write(dir.join("summary"), b"old").unwrap();
        let root = RepoDir::open_root(rustix::fs::CWD, &dir).unwrap();
        let Walked::File(file, _) = walk(&root, "summary", false).unwrap() else {
            panic!("the file exists");
        };
        assert!(names_file(&root, "summary", &file).unwrap());
        std::fs::write(dir.join("new"), b"new").unwrap();
        std::fs::rename(dir.join("new"), dir.join("summary")).unwrap();
        assert!(!names_file(&root, "summary", &file).unwrap());
        std::fs::remove_file(dir.join("summary")).unwrap();
        assert!(!names_file(&root, "summary", &file).unwrap());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A `bare-user` repository with one regular content object.
    async fn repo_with_object(dir: &Path) -> (Repo, Checksum) {
        let repo = Repo::create(&dir.join("repo"), CreateOptions::new(RepoMode::BareUser))
            .await
            .unwrap();
        let txn = repo.transaction().await.unwrap();
        let meta = FileMeta {
            uid: 0,
            gid: 0,
            mode: 0o100644,
            xattrs: ostrya_core::Xattrs::empty(),
        };
        let checksum = txn
            .write_regfile_inline(None, &meta, &vec![7u8; 100_000])
            .await
            .unwrap();
        txn.commit().await.unwrap();
        (repo, checksum)
    }

    fn filez_path(checksum: &Checksum) -> String {
        format!(
            "objects/{}",
            ostrya_core::loose_path(checksum, ObjectType::File, RepoMode::Archive)
        )
    }

    /// A built `.filez` takes a compressor on its first read past the
    /// header, and one dropped unread takes none. A body that ends gives its
    /// compressor back, and the next body reuses it.
    #[test]
    fn a_compressor_is_taken_on_the_first_payload_read() {
        let dir = scratch("lazy");
        ostrya_rt::block_on(async {
            let (repo, checksum) = repo_with_object(&dir).await;
            let view = ArchiveView::new(repo);
            let leases = || view.compressors.leases.load(Ordering::Relaxed);
            let idle = || view.compressors.idle.lock().unwrap().len();

            let answer = view.get(&filez_path(&checksum), &anyone()).await.unwrap();
            assert!(matches!(answer, ArchiveAnswer::Stream { len: None, .. }));
            drop(answer);
            assert_eq!(leases(), 0);

            let ArchiveAnswer::Stream { mut body, .. } =
                view.get(&filez_path(&checksum), &anyone()).await.unwrap()
            else {
                panic!("a stream");
            };
            // A read inside the header takes no compressor.
            let mut byte = [0u8; 1];
            body.read_exact(&mut byte).await.unwrap();
            assert_eq!(leases(), 0);
            let mut rest = Vec::new();
            body.read_to_end(&mut rest).await.unwrap();
            assert_eq!(leases(), 1);
            assert_eq!(idle(), 1);

            let ArchiveAnswer::Stream { mut body, .. } =
                view.get(&filez_path(&checksum), &anyone()).await.unwrap()
            else {
                panic!("a stream");
            };
            let mut again = Vec::new();
            body.read_to_end(&mut again).await.unwrap();
            assert_eq!([&byte[..], &rest[..]].concat(), again);
            assert_eq!((leases(), idle()), (2, 1));
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The path of the `bare-user` object of `checksum` under `dir`.
    fn bare_user_path(dir: &Path, checksum: &Checksum) -> PathBuf {
        dir.join("repo/objects").join(ostrya_core::loose_path(
            checksum,
            ObjectType::File,
            RepoMode::BareUser,
        ))
    }

    /// The body of a built `.filez` of `checksum` after its header.
    async fn past_header(
        view: &ArchiveView,
        checksum: &Checksum,
    ) -> Box<dyn AsyncRead + Unpin + Send> {
        let ArchiveAnswer::Stream { mut body, .. } =
            view.get(&filez_path(checksum), &anyone()).await.unwrap()
        else {
            panic!("a stream");
        };
        let mut header = Vec::new();
        view.repo
            .load_file(checksum)
            .await
            .unwrap()
            .header()
            .write_framed_archive(100_000, &mut header)
            .unwrap();
        let mut head = vec![0u8; header.len()];
        body.read_exact(&mut head).await.unwrap();
        body
    }

    /// A stored file that ends before the size of the header fails the body,
    /// and so does one that holds more. The error is sticky: a read after it
    /// fails too and does not see the end of the stream.
    #[test]
    fn a_payload_of_another_size_fails_the_body() {
        let dir = scratch("size");
        ostrya_rt::block_on(async {
            let (repo, checksum) = repo_with_object(&dir).await;
            let view = ArchiveView::new(repo);
            let object = bare_user_path(&dir, &checksum);
            for (len, kind) in [
                (50_000, io::ErrorKind::UnexpectedEof),
                (150_000, io::ErrorKind::InvalidData),
            ] {
                let mut body = past_header(&view, &checksum).await;
                std::fs::OpenOptions::new()
                    .write(true)
                    .open(&object)
                    .unwrap()
                    .set_len(len)
                    .unwrap();
                let mut out = Vec::new();
                let err = body.read_to_end(&mut out).await.unwrap_err();
                assert_eq!(err.kind(), kind, "{len}");
                let mut more = [0u8; 16];
                let err = body.read(&mut more).await.unwrap_err();
                assert_eq!(err.kind(), kind, "{len}");
                std::fs::OpenOptions::new()
                    .write(true)
                    .open(&object)
                    .unwrap()
                    .set_len(100_000)
                    .unwrap();
            }
            // A body of the right size still ends cleanly, with the
            // compressor of the failed bodies back in the pool.
            let mut out = Vec::new();
            past_header(&view, &checksum)
                .await
                .read_to_end(&mut out)
                .await
                .unwrap();
            assert_eq!(view.compressors.idle.lock().unwrap().len(), 1);
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A FIFO at the path of a `bare-user` object fails the `GET` and the
    /// `HEAD` at once: neither open waits for a writer.
    #[test]
    fn a_fifo_at_an_object_path_answers_at_once() {
        let dir = scratch("fifo");
        let (repo, checksum) = ostrya_rt::block_on(repo_with_object(&dir));
        let object = bare_user_path(&dir, &checksum);
        std::fs::remove_file(&object).unwrap();
        rustix::fs::mknodat(
            rustix::fs::CWD,
            &object,
            FileType::Fifo,
            Mode::from_raw_mode(0o644),
            0,
        )
        .unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            ostrya_rt::block_on(async {
                let view = ArchiveView::new(repo);
                let get = view.get(&filez_path(&checksum), &anyone()).await;
                let head = view.head(&filez_path(&checksum), &anyone()).await;
                tx.send((get.is_err(), head.is_err())).unwrap();
            });
        });
        let answered = rx.recv_timeout(std::time::Duration::from_secs(10));
        assert_eq!(answered, Ok((true, true)));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// After a change of `config`, requests that see the change at the same
    /// time read the file once.
    #[test]
    fn one_request_reads_a_changed_config() {
        let dir = scratch("single-flight");
        ostrya_rt::block_on(async {
            let (repo, checksum) = repo_with_object(&dir).await;
            let view = ArchiveView::new(repo);
            let reads = || view.config_reads.load(Ordering::Relaxed);
            view.get("config", &anyone()).await.unwrap();
            assert_eq!(reads(), 1);
            view.get("config", &anyone()).await.unwrap();
            assert_eq!(reads(), 1);

            let config = dir.join("repo/config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str("indexed-deltas=true\n");
            std::fs::write(&config, text).unwrap();
            let path = filez_path(&checksum);
            let mut requests: Vec<Pin<Box<dyn Future<Output = ()> + '_>>> = Vec::new();
            for i in 0..8 {
                let view = &view;
                let path = path.as_str();
                requests.push(Box::pin(async move {
                    if i % 2 == 0 {
                        view.get("config", &anyone()).await.unwrap();
                    } else {
                        view.get(path, &anyone()).await.unwrap();
                    }
                }));
            }
            std::future::poll_fn(|cx| {
                requests.retain_mut(|request| request.as_mut().poll(cx).is_pending());
                if requests.is_empty() {
                    Poll::Ready(())
                } else {
                    Poll::Pending
                }
            })
            .await;
            assert_eq!(reads(), 2);
        });
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// No more than the pool size of bodies deflate at once: one more waits
    /// for a compressor, and gets one when a body is dropped mid-stream.
    #[test]
    fn a_body_past_the_pool_size_waits_for_a_compressor() {
        let dir = scratch("gate");
        ostrya_rt::block_on(async {
            let (repo, checksum) = repo_with_object(&dir).await;
            let view = ArchiveView::new(repo);
            let mut header_len = Vec::new();
            {
                let file = view.repo.load_file(&checksum).await.unwrap();
                file.header()
                    .write_framed_archive(100_000, &mut header_len)
                    .unwrap();
            }
            let open = || async {
                let ArchiveAnswer::Stream { body, .. } =
                    view.get(&filez_path(&checksum), &anyone()).await.unwrap()
                else {
                    panic!("a stream");
                };
                body
            };
            let mut held = Vec::new();
            for _ in 0..MAX_COMPRESSORS {
                let mut body = open().await;
                let mut head = vec![0u8; header_len.len() + 1];
                body.read_exact(&mut head).await.unwrap();
                held.push(body);
            }
            let mut waiting = open().await;
            let mut head = vec![0u8; header_len.len()];
            waiting.read_exact(&mut head).await.unwrap();
            let mut one = [0u8; 1];
            let mut read = Box::pin(waiting.read(&mut one));
            assert!(futures_lite::future::poll_once(&mut read).await.is_none());
            drop(held.pop());
            assert_eq!(read.await.unwrap(), 1);
        });
        let _ = std::fs::remove_dir_all(&dir);
    }
}