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
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
//! The repository handle and the options of an open and of a new repository.
//!
//! [`Repo`] is the handle. [`Repo::open`] opens a repository, and
//! [`Repo::create`] creates one with [`CreateOptions`]. [`OpenOptions`] opens
//! a repository with options. [`RemotesDir`] names the remotes directory of a
//! handle.

use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use ostrya_core::{KeyFile, RepoMode};

use crate::access::{AuthItem, ClientAccess, ReadAccess};
use crate::config::{
    CollectionIdValue, EX_OSTRYA, Entry, Group, Key, MinFreeSpace, Overridable, Overrides,
    REMOTES_CONFIG_DIR, RemotesConfigPath, RepoConfig, Settable, SingleKey, Tristate, Value,
    ValueOf, find_entry, put_entry, put_settable, repo,
};
use crate::error::{Error, Result};
use crate::lock::{self, LockGuard, LockKind, RepoLock, UpdateLock, UpdateLockHeld, UpdateLocks};
use crate::remotes_dir;
use crate::repo_fs::{self, Publish, Published, RepoDir, RepoLayout, RootFile};
use crate::staging::StagingDir;
use crate::transaction::{Settings, Transaction};

/// The largest `config` file that a read accepts, in bytes. A read refuses a
/// larger file with [`Error::InvalidFormat`].
pub(crate) const MAX_CONFIG_SIZE: u64 = 1024 * 1024;

/// The directory kinds that the create of a repository makes, in the order
/// of the create. The create of each kind also makes its initial children.
const INIT_KINDS: [RepoLayout; 5] = [
    RepoLayout::Objects,
    RepoLayout::Tmp,
    RepoLayout::Refs,
    RepoLayout::State,
    RepoLayout::Extensions,
];

/// The remotes directory of a repository handle: a directory of `.conf` files
/// that hold remotes.
///
/// The open reads the directory into the snapshot of [`Repo::config`] and
/// keeps no descriptor of it. Each later access resolves the value again, so
/// a directory that does not exist at the open can come into existence later.
/// The remote calls of an [`UpdateGuard`](crate::UpdateGuard) write the
/// `.conf` files of the directory. An add into the directory creates the
/// directory of a [`Path`](RemotesDir::Path) or an
/// [`InRepo`](RemotesDir::InRepo) value if it is absent. In a
/// `bare-user-shared` repository, each directory that an add creates for an
/// [`InRepo`](RemotesDir::InRepo) value gets the mode `02770`. A directory
/// of a [`Path`](RemotesDir::Path) value gets the mode `0777` with the umask
/// applied.
///
/// Each access follows a symlink at each component of the path of the
/// directory, also to a directory outside the repository. A read follows a
/// symlink at each name in the directory. A write replaces a symlink at a
/// name with a regular file, and the target of the symlink keeps its
/// content. A remove unlinks a symlink at a name, and the target stays.
///
/// A clone of a [`Fd`](RemotesDir::Fd) value shares one descriptor.
#[derive(Debug, Clone)]
pub enum RemotesDir {
    /// An absolute path. An open and a create refuse a relative path. A
    /// caller with a relative path makes it absolute first, for example with
    /// [`std::path::absolute`].
    Path(PathBuf),
    /// A descriptor of the directory. Each access uses it with `openat`.
    ///
    /// The value owns the descriptor. A caller that keeps its descriptor
    /// gives a duplicate.
    Fd(Arc<OwnedFd>),
    /// A path relative to the repository directory, with no `..` component.
    /// Each access resolves it with `openat` on the descriptor of the
    /// repository directory.
    InRepo(PathBuf),
}

impl RemotesDir {
    /// Creates a [`Path`](RemotesDir::Path) value.
    pub fn path(path: impl Into<PathBuf>) -> RemotesDir {
        RemotesDir::Path(path.into())
    }

    /// Refuses a value that an open and a create do not take: an empty path,
    /// a path that holds a NUL byte, a relative [`Path`](RemotesDir::Path)
    /// path, and an [`InRepo`](RemotesDir::InRepo) path that is absolute or
    /// has a `..` component.
    fn check(&self) -> Result<()> {
        match self {
            RemotesDir::Path(path) | RemotesDir::InRepo(path)
                if path.as_os_str().as_bytes().contains(&0) =>
            {
                Err(Error::InvalidInput(format!(
                    "the remotes directory path {} holds a NUL byte",
                    path.display()
                )))
            }
            RemotesDir::Path(path) if path.as_os_str().is_empty() => Err(Error::InvalidInput(
                "the remotes directory path is empty".into(),
            )),
            RemotesDir::InRepo(path) if path.as_os_str().is_empty() => Err(Error::InvalidInput(
                "the in-repository remotes directory path is empty".into(),
            )),
            RemotesDir::Path(path) if path.is_relative() => Err(Error::InvalidInput(format!(
                "the remotes directory path {} is relative",
                path.display()
            ))),
            RemotesDir::InRepo(path) if path.is_absolute() => Err(Error::InvalidInput(format!(
                "the in-repository remotes directory path {} is absolute",
                path.display()
            ))),
            RemotesDir::InRepo(path) if path.components().any(|c| c == Component::ParentDir) => {
                Err(Error::InvalidInput(format!(
                    "the in-repository remotes directory path {} has a `..` component",
                    path.display()
                )))
            }
            _ => Ok(()),
        }
    }
}

impl From<PathBuf> for RemotesDir {
    /// Gives a [`Path`](RemotesDir::Path) value.
    fn from(path: PathBuf) -> RemotesDir {
        RemotesDir::Path(path)
    }
}

impl From<OwnedFd> for RemotesDir {
    /// Gives a [`Fd`](RemotesDir::Fd) value that owns `fd`.
    fn from(fd: OwnedFd) -> RemotesDir {
        RemotesDir::Fd(Arc::new(fd))
    }
}

/// The options of an open of a repository.
///
/// [`Repo::open`] and [`Repo::open_at`] open with the default options.
///
/// # Remotes directory
///
/// The open selects the remotes directory of the handle in this order:
///
/// 1. [`remotes_dir`](OpenOptions::remotes_dir);
/// 2. the key `[ex-ostrya] remotes-config-dir` of `config`;
/// 3. [`default_remotes_dir`](OpenOptions::default_remotes_dir);
/// 4. no remotes directory.
///
/// No option turns off the key. An absolute value of the key gives a
/// [`Path`](RemotesDir::Path) value. A relative value gives an
/// [`InRepo`](RemotesDir::InRepo) value, relative to the repository
/// directory. The open refuses an empty value and a relative value with a
/// `..` component, also when an option comes before the key.
///
/// [`Repo::remotes_dir`] gives the selected value.
///
/// The open detects no system repository, so it reads `/etc/ostree/remotes.d`
/// only when an option or the key names that directory. The `ostree` command
/// uses `/etc/ostree/remotes.d` as the remotes directory of the system
/// repository, the directory of `/ostree/repo`, and writes a new remote into
/// it. A program for an ostree host gives that repository
/// `default_remotes_dir(RemotesDir::path("/etc/ostree/remotes.d"))` and
/// `fallback::<repo::AddRemotesConfigDir>(true)`, as the example in
/// "Overrides" shows.
///
/// The open reads the `.conf` files of the selected directory into
/// [`Repo::config`]:
///
/// - It reads each entry whose name ends in `.conf`, in the byte order of the
///   names. The match is case-sensitive. A name that starts with `.` is read.
/// - It skips a subdirectory, a FIFO, a socket, and a device by the type of
///   the listing, and opens no such entry.
/// - It opens a regular file and a symlink with `O_NONBLOCK`, and follows the
///   symlink. It then checks the type of the open file, and skips each entry
///   that is not a regular file. A symlink to an absent file is skipped. Each
///   other failure of the symlink, such as a loop, fails the open.
/// - The open of a symlink to a device opens the device before the type
///   check, and the open of a device with a driver can have side effects.
///   The read skips the entry if the open succeeds or if the device has no
///   driver. Each other error of the open fails the open of the repository,
///   for example `EACCES` for a device that the user cannot open or for a
///   device on a `nodev` mount.
/// - It takes the `[remote "<name>"]` groups of each file and ignores each
///   other group.
/// - An absent directory, or an absent parent of it, gives no remotes.
///
/// [`UpdateGuard::add_remote`](crate::UpdateGuard::add_remote) writes a new
/// remote into the remotes directory only when `[core]
/// add-remotes-config-dir` is `true` in effect. The default of the key is
/// `false`, so with no key and no override an add writes into `config`.
///
/// # Overrides
///
/// [`force`](OpenOptions::force) and [`fallback`](OpenOptions::fallback) set
/// the value of a key of a single group on the handle, in memory:
///
/// - A forced value is in effect whether `config` sets the key or not.
/// - A fallback value is in effect when `config` does not set the key.
///
/// [`RepoConfig::get`] and [`RepoConfig::lookup`] of [`Repo::config`] read
/// the forced value, then the value of `config`, then the fallback value,
/// then the default of the key. [`Lookup`](crate::config::Lookup) names the
/// source. The config of
/// [`UpdateGuard::read_config`](crate::UpdateGuard::read_config) takes the
/// same overrides. [`RepoConfig::file_value`], [`RepoConfig::keyfile`], and
/// each write of `config` give the file alone, so an override never goes to
/// disk. A later open does not take the overrides of this handle.
///
/// A key takes an override if it implements [`Overridable`]. A key of a
/// remote takes no override.
///
/// # Examples
///
/// ```no_run
/// # async fn run() -> ostrya::Result<()> {
/// use ostrya::repo::{OpenOptions, RemotesDir};
///
/// let repo = OpenOptions::new()
///     .remotes_dir(RemotesDir::path("/etc/myapp/remotes.d"))
///     .open("/srv/repo".as_ref())
///     .await?;
/// assert!(repo.remotes_dir().is_some());
/// # Ok(()) }
/// ```
///
/// The system repository of an ostree host, with the remotes directory and
/// the add target of the `ostree` command, and with no sync of a write:
///
/// ```no_run
/// # async fn run() -> ostrya::Result<()> {
/// use ostrya::config::repo;
/// use ostrya::repo::{OpenOptions, RemotesDir};
///
/// let repo = OpenOptions::new()
///     .default_remotes_dir(RemotesDir::path("/etc/ostree/remotes.d"))
///     .fallback::<repo::AddRemotesConfigDir>(true)
///     .force::<repo::Fsync>(false)
///     .open("/ostree/repo".as_ref())
///     .await?;
/// assert!(!repo.config().get::<repo::Fsync>()?);
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, Default)]
pub struct OpenOptions {
    remotes_dir: Option<RemotesDir>,
    default_remotes_dir: Option<RemotesDir>,
    overrides: Overrides,
}

impl OpenOptions {
    /// Creates the options of an open with no remotes directory.
    pub fn new() -> Self {
        OpenOptions::default()
    }

    /// Sets the remotes directory of the handle. This value comes before
    /// [`default_remotes_dir`](OpenOptions::default_remotes_dir).
    pub fn remotes_dir(mut self, dir: RemotesDir) -> Self {
        self.remotes_dir = Some(dir);
        self
    }

    /// Sets the remotes directory of the handle when no other source gives
    /// one.
    pub fn default_remotes_dir(mut self, dir: RemotesDir) -> Self {
        self.default_remotes_dir = Some(dir);
        self
    }

    /// Sets a forced value of the key `K` on the handle.
    ///
    /// The value is in effect whether `config` sets the key or not. A read
    /// of the key does not parse the value of the file, so a bad value of the
    /// file does not fail the read. A later call for the same key replaces
    /// the value. [`OpenOptions`], "Overrides", states the rules.
    ///
    /// The `config` that an [`ArchiveView`](crate::ArchiveView) serves holds
    /// the text of `[core] indexed-deltas` of the file. A forced value of the
    /// key does not change the served text.
    ///
    /// The key implements [`Overridable`]. Each other key fails to compile:
    ///
    /// ```
    /// use ostrya::OpenOptions;
    /// use ostrya::config::repo;
    ///
    /// let _ = OpenOptions::new().force::<repo::Fsync>(false);
    /// ```
    ///
    /// ```compile_fail,E0277
    /// use ostrya::OpenOptions;
    /// use ostrya::config::repo;
    ///
    /// let _ = OpenOptions::new().force::<repo::Locking>(false);
    /// ```
    pub fn force<K>(mut self, value: ValueOf<K>) -> Self
    where
        K: Overridable + Key<<K as SingleKey>::Group>,
    {
        self.overrides.force::<K>(value);
        self
    }

    /// Sets a fallback value of the key `K` on the handle.
    ///
    /// The value is in effect when `config` does not set the key. A later
    /// call for the same key replaces the value. [`OpenOptions`],
    /// "Overrides", states the rules. The key implements [`Overridable`], as
    /// for [`force`](OpenOptions::force).
    pub fn fallback<K>(mut self, value: ValueOf<K>) -> Self
    where
        K: Overridable + Key<<K as SingleKey>::Group>,
    {
        self.overrides.fallback::<K>(value);
        self
    }

    /// Refuses a remotes directory value that the open does not take.
    fn check(&self) -> Result<()> {
        for dir in [&self.remotes_dir, &self.default_remotes_dir]
            .into_iter()
            .flatten()
        {
            dir.check()?;
        }
        Ok(())
    }

    /// Opens the repository at `path`, relative to the current working
    /// directory.
    ///
    /// [`Repo::open`] describes the handle.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if a remotes directory value is an empty
    ///   path, a path that holds a NUL byte, a relative
    ///   [`Path`](RemotesDir::Path) path, or an [`InRepo`](RemotesDir::InRepo)
    ///   path that is absolute or has a `..` component. The call checks the
    ///   values before it opens a file.
    /// - [`Error::Io`] of kind `NotFound` if a component of `path` does not
    ///   exist, if a symlink in `path` has no target, or if `objects` or
    ///   `config` does not exist. The message is `<path> does not exist`,
    ///   with `path` as given, and with `objects` and `config` relative to
    ///   the repository.
    /// - [`Error::InvalidFormat`] if `path`, a component of it, or `objects`
    ///   is not a directory, or if `config` is not a regular file. A FIFO at
    ///   `config` does not block the open.
    /// - [`Error::InvalidFormat`] if `objects` or `config` is a symlink. The
    ///   open follows a symlink in `path`, and no symlink at `objects` or
    ///   `config`.
    /// - [`Error::Io`] if a read fails, or if the kernel has no `openat2`
    ///   (Linux 5.6 or later).
    /// - [`Error::InvalidFormat`] if `config` is larger than 1 MiB (1048576
    ///   bytes) or is not valid UTF-8.
    /// - [`Error::InvalidFormat`] if the `[core]` group of `config` fails the
    ///   checks of [`RepoConfig::from_keyfile`].
    /// - [`Error::Core`] if `config` is not a valid key file, or if a `[core]`
    ///   value that [`RepoConfig::from_keyfile`] reads does not parse.
    /// - [`Error::InvalidFormat`] if `[ex-ostrya] remotes-config-dir` is
    ///   empty, holds a NUL byte, or is a relative path with a `..`
    ///   component, and [`Error::Core`] if it holds a malformed escape
    ///   sequence.
    /// - [`Error::InvalidFormat`] if the remotes directory or a component of
    ///   its path is not a directory. The message is
    ///   `<path> is not a directory`.
    /// - [`Error::Io`] if the remotes directory or one of its `.conf` files
    ///   cannot be read. The message starts with the path of the directory or
    ///   of the file. In the messages of the remotes directory, a
    ///   [`Path`](RemotesDir::Path) value gives the path as given, and an
    ///   [`InRepo`](RemotesDir::InRepo) value the path relative to the
    ///   repository. A [`Fd`](RemotesDir::Fd) value gives the name of a file,
    ///   and `.` for the directory.
    /// - [`Error::InvalidFormat`] if a `.conf` file is larger than 1 MiB, if
    ///   its name or its content is not valid UTF-8, or if it is not a valid
    ///   key file. The message names the file.
    /// - [`Error::InvalidFormat`] if `config` and a `.conf` file, or two
    ///   `.conf` files, define one remote name.
    pub async fn open(&self, path: &Path) -> Result<Repo> {
        self.check()?;
        let opts = self.clone();
        let path = path.to_owned();
        let stored = path.clone();
        let materials =
            ostrya_rt::unblock(move || open_materials(rustix::fs::CWD, &path, false, opts)).await?;
        Ok(Repo::assemble(materials, stored))
    }

    /// Opens the repository at `path`, relative to the directory `dir`.
    ///
    /// [`Repo::open_at`] describes the handle.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if a remotes directory value is an empty
    ///   path, a path that holds a NUL byte, a relative
    ///   [`Path`](RemotesDir::Path) path, or an [`InRepo`](RemotesDir::InRepo)
    ///   path that is absolute or has a `..` component. The call checks the
    ///   values before it opens a file.
    /// - [`Error::Io`] if the call cannot duplicate `dir`.
    /// - [`Error::Io`] of kind `NotFound` if a component of `path` does not
    ///   exist, if a symlink in `path` has no target, or if `objects` or
    ///   `config` does not exist. The message is `<path> does not exist`,
    ///   with `path` as given, and with `objects` and `config` relative to
    ///   the repository.
    /// - [`Error::InvalidFormat`] if `path`, a component of it, or `objects`
    ///   is not a directory, or if `config` is not a regular file. A FIFO at
    ///   `config` does not block the open.
    /// - [`Error::InvalidFormat`] if `objects` or `config` is a symlink. The
    ///   open follows a symlink in `path`, and no symlink at `objects` or
    ///   `config`.
    /// - [`Error::Io`] if a read fails, or if the kernel has no `openat2`
    ///   (Linux 5.6 or later).
    /// - [`Error::InvalidFormat`] if `config` is larger than 1 MiB (1048576
    ///   bytes) or is not valid UTF-8.
    /// - [`Error::InvalidFormat`] if the `[core]` group of `config` fails the
    ///   checks of [`RepoConfig::from_keyfile`].
    /// - [`Error::Core`] if `config` is not a valid key file, or if a `[core]`
    ///   value that [`RepoConfig::from_keyfile`] reads does not parse.
    /// - [`Error::InvalidFormat`] if `[ex-ostrya] remotes-config-dir` is
    ///   empty, holds a NUL byte, or is a relative path with a `..`
    ///   component, and [`Error::Core`] if it holds a malformed escape
    ///   sequence.
    /// - [`Error::InvalidFormat`] if the remotes directory or a component of
    ///   its path is not a directory. The message is
    ///   `<path> is not a directory`.
    /// - [`Error::Io`] if the remotes directory or one of its `.conf` files
    ///   cannot be read. The message starts with the path of the directory or
    ///   of the file. In the messages of the remotes directory, a
    ///   [`Path`](RemotesDir::Path) value gives the path as given, and an
    ///   [`InRepo`](RemotesDir::InRepo) value the path relative to the
    ///   repository. A [`Fd`](RemotesDir::Fd) value gives the name of a file,
    ///   and `.` for the directory.
    /// - [`Error::InvalidFormat`] if a `.conf` file is larger than 1 MiB, if
    ///   its name or its content is not valid UTF-8, or if it is not a valid
    ///   key file. The message names the file.
    /// - [`Error::InvalidFormat`] if `config` and a `.conf` file, or two
    ///   `.conf` files, define one remote name.
    pub async fn open_at(&self, dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
        self.check()?;
        let opts = self.clone();
        let dir = dir.try_clone_to_owned()?;
        let path = path.to_owned();
        let stored = path.clone();
        let materials =
            ostrya_rt::unblock(move || open_materials(&dir, &path, false, opts)).await?;
        Ok(Repo::assemble(materials, stored))
    }
}

/// The options of a new repository.
///
/// [`collection_id`](CreateOptions::collection_id),
/// [`remotes_dir`](CreateOptions::remotes_dir), and
/// [`set`](CreateOptions::set) give the keys of the new `config`.
/// [`fallback`](CreateOptions::fallback) gives a value in memory to the
/// handle that the create returns. A create writes no
/// `[core] add-remotes-config-dir` of its own, and the default of the key is
/// `false`.
///
/// # Examples
///
/// ```no_run
/// # async fn run() -> ostrya::Result<()> {
/// use ostrya::repo::{CreateOptions, RemotesDir};
/// use ostrya::RepoMode;
///
/// let repo = CreateOptions::new(RepoMode::Archive)
///     .collection_id("org.example.Os")
///     .remotes_dir(RemotesDir::path("/etc/myapp/remotes.d"))
///     .create("/srv/repo".as_ref())
///     .await?;
/// assert_eq!(repo.mode(), RepoMode::Archive);
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct CreateOptions {
    mode: RepoMode,
    /// The keys that the create writes into the new `config`, in the order
    /// of the first call for each key.
    values: Vec<Entry>,
    remotes_dir: Option<RemotesDir>,
    overrides: Overrides,
}

impl Default for CreateOptions {
    /// Gives the options of a [`Bare`](RepoMode::Bare) repository, with no
    /// collection id and no remotes directory.
    fn default() -> Self {
        CreateOptions::new(RepoMode::Bare)
    }
}

impl CreateOptions {
    /// Creates the options of a repository of `mode`, with no collection id
    /// and no remotes directory.
    ///
    /// The create writes `mode` to `[core] mode`.
    pub fn new(mode: RepoMode) -> Self {
        CreateOptions {
            mode,
            values: Vec::new(),
            remotes_dir: None,
            overrides: Overrides::default(),
        }
    }

    /// Sets the collection id. The create writes it to
    /// `[core] collection-id`.
    ///
    /// The call and [`set::<repo::CollectionId>`](CreateOptions::set) store
    /// one value, and the last call wins. The create refuses an id that
    /// fails the collection-id rule of [`CollectionIdValue`].
    pub fn collection_id(mut self, id: impl Into<String>) -> Self {
        let text = crate::config::encode_string(&id.into());
        put_entry(
            &mut self.values,
            repo::Group::NAME,
            <repo::CollectionId as Key<repo::Group>>::NAME,
            text,
        );
        self
    }

    /// Sets the value of the key `K` in the new `config`.
    ///
    /// The create writes the text of [`Value::format`] as given. A later
    /// call for the same key replaces the value. [`Repo::create`] states the
    /// place of each key in the file. The value is in the file, so the handle
    /// reads it as a value of the file.
    ///
    /// The key implements [`Settable`]. `[core] mode` and `[core]
    /// repo_version` fail to compile, because [`new`](CreateOptions::new) and
    /// the create write them:
    ///
    /// ```
    /// use ostrya::{CreateOptions, RepoMode};
    /// use ostrya::config::repo;
    ///
    /// let _ = CreateOptions::new(RepoMode::Archive).set::<repo::Locking>(false);
    /// ```
    ///
    /// ```compile_fail,E0277
    /// use ostrya::{CreateOptions, RepoMode};
    /// use ostrya::config::repo;
    ///
    /// let _ = CreateOptions::new(RepoMode::Archive).set::<repo::Mode>(RepoMode::Bare);
    /// ```
    ///
    /// Two keys have more rules:
    ///
    /// - [`repo::CollectionId`]: the call and
    ///   [`collection_id`](CreateOptions::collection_id) store one value, and
    ///   the last call wins.
    /// - [`ex_ostrya::RemotesConfigDir`](crate::config::ex_ostrya::RemotesConfigDir):
    ///   the handle takes the remotes directory that the key names, as an
    ///   open takes it. The create refuses the key together with
    ///   [`remotes_dir`](CreateOptions::remotes_dir).
    pub fn set<K>(mut self, value: ValueOf<K>) -> Self
    where
        K: Settable + Key<<K as SingleKey>::Group>,
    {
        put_settable::<K>(&mut self.values, value);
        self
    }

    /// Sets a fallback value of the key `K` on the handle that the create
    /// returns, as [`OpenOptions::fallback`] does.
    ///
    /// The value is in memory alone, and the create does not write it into
    /// `config`. A later open of the repository does not take it.
    pub fn fallback<K>(mut self, value: ValueOf<K>) -> Self
    where
        K: Overridable + Key<<K as SingleKey>::Group>,
    {
        self.overrides.fallback::<K>(value);
        self
    }

    /// Sets the remotes directory of the repository.
    ///
    /// The create writes nothing into the directory. It writes the key
    /// `[ex-ostrya] remotes-config-dir` into the new `config`:
    ///
    /// - A [`Path`](RemotesDir::Path) value, which is absolute, writes its
    ///   path as given.
    /// - An [`InRepo`](RemotesDir::InRepo) value writes its path as given.
    /// - A [`Fd`](RemotesDir::Fd) value writes no key.
    ///
    /// The handle that a create returns holds `dir` in each case, and
    /// [`Repo::remotes_dir`] gives it. The create reads the remotes of the
    /// directory, as an open does. The create writes no
    /// `[core] add-remotes-config-dir`. It refuses the call together with
    /// [`set::<ex_ostrya::RemotesConfigDir>`](CreateOptions::set).
    pub fn remotes_dir(mut self, dir: RemotesDir) -> Self {
        self.remotes_dir = Some(dir);
        self
    }

    /// Creates and opens a repository at `path`, relative to the working
    /// directory.
    ///
    /// The call creates a new repository only. [`Repo::create`] describes
    /// the layout that it writes.
    ///
    /// # Errors
    ///
    /// - [`Error::RepoExists`] if `path` holds an entry `config` of any
    ///   type. The call checks the entry without following a symlink, and it
    ///   writes nothing. If another process writes `config` after the check
    ///   and before the call puts its own `config` in place, the call gives
    ///   the same error, and the layout directories that it wrote stay.
    /// - [`Error::InvalidInput`] if the remotes directory value is an empty
    ///   path, a path that holds a NUL byte, a relative
    ///   [`Path`](RemotesDir::Path) path, or an [`InRepo`](RemotesDir::InRepo)
    ///   path that is absolute or has a `..` component, or if the value of the
    ///   key is not valid UTF-8. The call checks the value before it writes.
    /// - [`Error::InvalidInput`] if the collection id fails the collection-id
    ///   rule of [`CollectionIdValue`], if the value of
    ///   `[ex-ostrya] remotes-config-dir` fails the rules of
    ///   [`RemotesConfigPath`], if the call has a remotes directory value and
    ///   that key together, or if a key file cannot hold the text of a value
    ///   of [`set`](CreateOptions::set). The call checks the values before it
    ///   writes.
    /// - [`Error::Io`] of kind `NotFound` if a component of `path` above the
    ///   last does not exist, or if a symlink in `path` has no target. The
    ///   message is `<path> does not exist`, with `path` as given.
    /// - [`Error::InvalidFormat`] if `path` or a component of it is not a
    ///   directory, or if a directory of the layout is a symlink or is not a
    ///   directory. The call then writes no `config`.
    /// - [`Error::Io`] of kind `NotFound` if the file system of `tmp/` has
    ///   `O_TMPFILE` and `/proc/self/fd` is not available. The message starts
    ///   with `a link through /proc/self/fd gives ENOENT`. The layout
    ///   directories then stay with no `config`, and a later create at
    ///   `path` writes `config`.
    /// - [`Error::Io`] if a create, a write, a read, or the check of the
    ///   entry `config` fails.
    /// - The errors of [`OpenOptions::open`] for the key
    ///   `[ex-ostrya] remotes-config-dir`, the remotes directory, and its
    ///   `.conf` files. The call reads them after it writes the layout and
    ///   `config`, so a refusal leaves the new repository on disk.
    pub async fn create(&self, path: &Path) -> Result<Repo> {
        self.check()?;
        let opts = self.clone();
        let path = path.to_owned();
        let stored = path.clone();
        let materials =
            ostrya_rt::unblock(move || create_materials(rustix::fs::CWD, &path, opts)).await?;
        Ok(Repo::assemble(materials, stored))
    }

    /// Creates and opens a repository at `path`, relative to the directory
    /// `dir`.
    ///
    /// The call creates a new repository only. [`Repo::create`] describes
    /// the layout that it writes. The path of [`Error::RepoExists`] is
    /// `path`, relative to `dir`.
    ///
    /// # Errors
    ///
    /// - The errors of [`create`](CreateOptions::create).
    /// - [`Error::Io`] if the call cannot duplicate `dir`.
    pub async fn create_at(&self, dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
        self.check()?;
        let opts = self.clone();
        let dir = dir.try_clone_to_owned()?;
        let path = path.to_owned();
        let stored = path.clone();
        let materials = ostrya_rt::unblock(move || create_materials(&dir, &path, opts)).await?;
        Ok(Repo::assemble(materials, stored))
    }

    /// Refuses a value that the create does not take: a collection id that
    /// fails the collection-id rule, a value of `remotes-config-dir` that
    /// the open refuses, the key `remotes-config-dir` together with a
    /// remotes directory value, the remotes directory values that the open
    /// refuses, and a remotes directory path that is not valid UTF-8, because
    /// `config` is UTF-8.
    fn check(&self) -> Result<()> {
        let collection_id = <repo::CollectionId as Key<repo::Group>>::NAME;
        self.check_value::<CollectionIdValue>(repo::Group::NAME, collection_id)?;
        let key = self.check_value::<RemotesConfigPath>(EX_OSTRYA, REMOTES_CONFIG_DIR)?;
        let Some(dir) = &self.remotes_dir else {
            return Ok(());
        };
        if key {
            return Err(Error::InvalidInput(format!(
                "a create takes a remotes directory or the key [{EX_OSTRYA}] \
                 {REMOTES_CONFIG_DIR}, not both"
            )));
        }
        dir.check()?;
        match dir {
            RemotesDir::Path(path) | RemotesDir::InRepo(path) => utf8_key_value(path).map(drop),
            RemotesDir::Fd(_) => Ok(()),
        }
    }

    /// Refuses the text of the key `key` of `group` if it does not parse with
    /// the value type `V`. Returns `true` if the create writes the key.
    fn check_value<V: Value>(&self, group: &str, key: &str) -> Result<bool> {
        let Some(raw) = find_entry(&self.values, group, key) else {
            return Ok(false);
        };
        V::parse(raw)
            .map(|_| true)
            .map_err(|err| Error::InvalidInput(format!("[{group}] {key} {err}")))
    }
}

/// A handle to an open ostree repository.
///
/// A clone of a `Repo` is cheap. The clones share one `Arc` that holds the
/// directory descriptors of the repository and its parsed [`RepoConfig`].
/// A `Repo` is `Send + Sync`, so a handle can move into a task. The handle
/// reads the config and the `.conf` files of its remotes directory one time,
/// when it opens.
///
/// The methods that do I/O are `async fn`. A call runs its file system work on
/// the blocking pool through `ostrya_rt::unblock`, so the call does not block
/// the executor. The open parses `config` on the blocking pool, because the
/// key that names the remotes directory selects the next read.
///
/// # Entry points
///
/// - [`open`](Repo::open) and [`create`](Repo::create) give a handle.
/// - [`OpenOptions`] and [`CreateOptions`] give a handle with options, such as
///   a [`RemotesDir`].
/// - [`transaction`](Repo::transaction) begins a [`Transaction`], which writes objects and refs.
/// - [`load_commit`](Repo::load_commit), [`read_commit`](Repo::read_commit), and
///   [`load_file`](Repo::load_file) read objects.
/// - [`resolve_rev`](Repo::resolve_rev) and [`list_refs`](Repo::list_refs) read refs.
/// - [`checkout_at`](Repo::checkout_at) writes the tree of a commit into a directory.
/// - [`pull`](Repo::pull) and [`pull_local`](Repo::pull_local) copy commits from
///   another repository.
/// - [`prune`](Repo::prune) and [`fsck`](Repo::fsck) maintain the object store.
/// - [`begin_update`](Repo::begin_update) holds the writes of refs and `config`.
#[derive(Debug, Clone)]
pub struct Repo {
    inner: Arc<RepoInner>,
}

#[derive(Debug)]
struct RepoInner {
    // All access to the repository starts from the handle of the root and
    // the handle of `objects/`. The open makes them one time, and the read
    // path and the write path use them.
    root: RepoDir,
    objects: RepoDir,
    config: RepoConfig,
    // The path that opened or created the handle, stored as the caller gave
    // it. It is a record of the argument of the caller, and no I/O uses it.
    // Each access goes through `root` and `objects`.
    path: PathBuf,
    // The remotes directory that the open selected, or that the create took.
    // A value of the caller is stored as the caller gave it.
    remotes_dir: Option<RemotesDir>,
    // The repository lock. The first acquire of the repository lock creates
    // it, and the handle keeps it for its full life. So all clones of this
    // handle share one `.lock` descriptor and one in-process hold count.
    lock: Mutex<Option<Arc<RepoLock>>>,
    // The update lock. The first acquire of the update lock creates it, and
    // the handle keeps it for its full life beside `lock`. So all clones of
    // this handle share one `.update.lock` descriptor and one queue of waiters.
    update_lock: Mutex<Option<Arc<UpdateLock>>>,
    // The anonymous read access of the implicit client groups. The first
    // use builds it from `config`, and all clones of this handle share it.
    implicit_reads: OnceLock<ReadAccess>,
    // The result of the seal probe of `Repo::seals_objects` under
    // `fsverity=maybe`. The first probe sets it, and all clones of this
    // handle share it.
    seal_probe: OnceLock<bool>,
}

impl RepoInner {
    /// Returns the shared [`RepoLock`] of this repository. The first call
    /// creates and registers `<repo>/.lock`. Runs synchronous file system
    /// calls.
    fn repo_lock(&self) -> Result<Arc<RepoLock>> {
        let mut slot = self.lock.lock().unwrap();
        if let Some(existing) = slot.as_ref() {
            return Ok(existing.clone());
        }
        let lock = RepoLock::get_or_create(&self.root)?;
        *slot = Some(lock.clone());
        Ok(lock)
    }

    /// Returns the shared [`UpdateLock`] of this repository. The first call
    /// creates and registers `<repo>/.update.lock`. Runs synchronous file
    /// system calls.
    fn update_lock(&self) -> Result<Arc<UpdateLock>> {
        let mut slot = self.update_lock.lock().unwrap();
        if let Some(existing) = slot.as_ref() {
            return Ok(existing.clone());
        }
        let lock = UpdateLock::get_or_create(&self.root)?;
        *slot = Some(lock.clone());
        Ok(lock)
    }
}

/// The materials of a handle that come from the file system. The blocking
/// pool makes them, and the async side assembles them into a [`Repo`].
struct Materials {
    root: RepoDir,
    objects: RepoDir,
    config: RepoConfig,
    remotes_dir: Option<RemotesDir>,
}

impl Materials {
    /// Selects the remotes directory of the handle: `first`, then the key of
    /// `config`, then `default`. Reads the remotes of the selected directory
    /// into the config. Blocks the calling thread.
    fn select_remotes_dir(
        mut self,
        first: Option<&RemotesDir>,
        default: Option<&RemotesDir>,
    ) -> Result<Materials> {
        let key = remotes_dir::from_key(&self.config)?;
        let selected = first.cloned().or(key).or_else(|| default.cloned());
        if let Some(dir) = &selected {
            self.config = remotes_dir::read_remotes(self.config, self.root.as_fd(), dir)?;
        }
        self.remotes_dir = selected;
        Ok(self)
    }
}

/// Methods that open or create a repository and begin a transaction.
impl Repo {
    /// Opens the repository at `path`, relative to the current working directory.
    ///
    /// The call is [`OpenOptions::open`] with the default options, so the
    /// handle takes the remotes directory that the key
    /// `[ex-ostrya] remotes-config-dir` of `config` names.
    ///
    /// The handle stores `path` as given, and [`path`](Repo::path) returns it.
    ///
    /// The handle holds a descriptor of the repository root and one of
    /// `objects/`, which each repository has. The call opens no descriptor of
    /// `tmp/` and does not read the boot id. A repository that is served
    /// read-only can have no `tmp/`, and the call opens it. A transaction
    /// reads the boot id when it begins, as the `ostree` command does. Each
    /// write that needs `tmp/` opens it, and creates it if it is absent.
    ///
    /// The open opens `objects` and reads `config` with one `openat2` each,
    /// with `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`. A symlink at
    /// `objects` or at `config` fails each open, also an open in the strict
    /// open mode.
    ///
    /// # Errors
    ///
    /// - The errors of [`OpenOptions::open`].
    pub async fn open(path: &Path) -> Result<Repo> {
        OpenOptions::new().open(path).await
    }

    /// Opens the repository at `path`, relative to the directory `dir`.
    ///
    /// The call is [`OpenOptions::open_at`] with the default options, so the
    /// handle takes the remotes directory that the key
    /// `[ex-ostrya] remotes-config-dir` of `config` names.
    ///
    /// The handle stores `path` as given, and [`path`](Repo::path) returns it.
    ///
    /// # Errors
    ///
    /// - The errors of [`OpenOptions::open_at`].
    pub async fn open_at(dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
        OpenOptions::new().open_at(dir, path).await
    }

    /// Opens the repository at `path`, relative to the directory `dir`, in
    /// the strict open mode. A process that reads a repository of another
    /// user with more privileges than that user opens it in this mode.
    ///
    /// The handle is the handle of [`open_at`](Repo::open_at), with one
    /// change: the open reads no `[ex-ostrya] remotes-config-dir` key and no
    /// remotes directory, so the handle has no remotes directory.
    ///
    /// Each read of the handle is the same as in [`open_at`](Repo::open_at).
    /// In each open mode, a read of an object or of a summary through
    /// [`read_summary`](Repo::read_summary),
    /// [`read_summary_signature`](Repo::read_summary_signature), and
    /// [`read_summary_of`](Repo::read_summary_of) opens the file with
    /// `openat2`, `RESOLVE_BENEATH`, `RESOLVE_NO_SYMLINKS`, and `O_NONBLOCK`,
    /// and refuses a file that is not a regular file. A symlink at any
    /// component of the path, a FIFO, or a device fails the read and does not
    /// block it. A local pull from the handle refuses a source object that is
    /// not the type that the source mode stores. The local pull reads
    /// `summary`, `summary.sig`, and the files of a static delta of the
    /// handle by the same rule: a symlink, a FIFO, or a device fails the
    /// pull and does not block it.
    ///
    /// The open of `openat2` has no fallback. On a kernel without the call,
    /// each of these reads fails.
    ///
    /// The function is not a stable API.
    ///
    /// # Errors
    ///
    /// - The errors of [`open_at`](Repo::open_at), except the errors of the
    ///   remotes directory.
    #[doc(hidden)]
    pub async fn open_at_strict(dir: BorrowedFd<'_>, path: &Path) -> Result<Repo> {
        let dir = dir.try_clone_to_owned()?;
        let path = path.to_owned();
        let stored = path.clone();
        let materials =
            ostrya_rt::unblock(move || open_materials(&dir, &path, true, OpenOptions::default()))
                .await?;
        Ok(Repo::assemble(materials, stored))
    }

    /// Opens the repository whose root handle is `root` in the strict open
    /// mode of [`open_at_strict`](Repo::open_at_strict). The handle stores
    /// `path`. Blocks the calling thread.
    ///
    /// `root` is a handle with no repository mode and no other clone, as
    /// [`RepoDir::from_root_fd`] gives it.
    pub(crate) fn open_strict_blocking(root: RepoDir, path: PathBuf) -> Result<Repo> {
        Ok(Repo::assemble(materials_from_root(root)?, path))
    }

    /// Creates and opens a repository at `path`, relative to the working directory.
    ///
    /// The call is [`opts.create(path)`](CreateOptions::create).
    ///
    /// The call creates a new repository only. If `path` holds an entry
    /// `config` before the call, the call refuses with [`Error::RepoExists`]
    /// and writes nothing. The errors of [`CreateOptions::create`] describe
    /// a `config` that another process writes during the call. To get a
    /// handle of an existing repository, use [`Repo::open`]. The handle
    /// stores `path` as given.
    ///
    /// # Layout
    ///
    /// If the directory at `path` does not exist, the call creates it. Then it
    /// creates the layout that the `ostree` command writes:
    ///
    /// - The directories `objects`, `tmp`, `tmp/cache`, `refs`, `refs/heads`,
    ///   `refs/remotes`, `refs/mirrors`, `state`, and `extensions`.
    /// - The `config` file. Its `[core]` group holds `repo_version=1`, `mode`,
    ///   and `collection-id` if [`collection_id`](CreateOptions::collection_id)
    ///   is set. The keys of [`set`](CreateOptions::set) follow, in the order
    ///   of the first call for each key. Each other group comes at the place
    ///   of its first key. If [`remotes_dir`](CreateOptions::remotes_dir) is a
    ///   [`Path`](RemotesDir::Path) or an [`InRepo`](RemotesDir::InRepo)
    ///   value, the key `remotes-config-dir` comes last in the `[ex-ostrya]`
    ///   group.
    ///
    /// A new directory gets the mode `0775`, reduced by the process umask, as
    /// the `ostree` command does. The `config` file gets the mode `0644`, and
    /// the umask does not change it.
    ///
    /// In a directory that has no `config`, the call keeps each directory of
    /// the layout that exists. A symlink or an entry that is not a directory
    /// at a path of the layout makes the call fail before it writes `config`.
    /// The call writes `config` to a temp file in `tmp/`, syncs it, and puts
    /// it at `config` in one step. A crash thus leaves no partial `config`.
    /// The call syncs whatever value of `[core] fsync` the new `config`
    /// holds.
    /// Where the file system of `tmp/` has `O_TMPFILE`, the temp file has no
    /// name, and the call links it at `config` through `/proc/self/fd`. The
    /// call then needs `/proc`. Without it, the call fails after it makes the
    /// layout directories, and it writes no `config`.
    ///
    /// The call syncs the parent directory of a root that it creates, each
    /// directory that it adds an entry to, and the root after it puts
    /// `config` in place.
    ///
    /// In a `bare-user-shared` repository, the call sets the mode `02770` on
    /// each directory that it creates. The umask does not change this mode.
    /// A directory that exists keeps its mode and its group, the root included.
    /// If ostrya did not create the root, the caller sets its group and its mode.
    ///
    /// # Errors
    ///
    /// - The errors of [`CreateOptions::create`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn run() -> ostrya::Result<()> {
    /// use ostrya::repo::CreateOptions;
    /// use ostrya::{Repo, RepoMode};
    ///
    /// let path = std::env::temp_dir().join("example-repo");
    /// let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive)).await?;
    /// assert_eq!(repo.mode(), RepoMode::Archive);
    /// # Ok(()) }
    /// ```
    pub async fn create(path: &Path, opts: CreateOptions) -> Result<Repo> {
        opts.create(path).await
    }

    /// Creates and opens a repository at `path`, relative to the directory `dir`.
    ///
    /// The call is [`opts.create_at(dir, path)`](CreateOptions::create_at).
    /// It creates a new repository only. [`create`](Repo::create) describes
    /// the layout that it writes.
    ///
    /// # Errors
    ///
    /// - The errors of [`CreateOptions::create_at`].
    pub async fn create_at(dir: BorrowedFd<'_>, path: &Path, opts: CreateOptions) -> Result<Repo> {
        opts.create_at(dir, path).await
    }

    /// Returns the storage mode of the repository.
    pub fn mode(&self) -> RepoMode {
        self.inner.config.mode()
    }

    /// Returns the parsed config of the repository and the remotes of its
    /// remotes directory, as the open read them.
    ///
    /// A later change of the files does not change the value. The reads of
    /// the value apply the overrides of [`OpenOptions::force`],
    /// [`OpenOptions::fallback`], and [`CreateOptions::fallback`].
    pub fn config(&self) -> &RepoConfig {
        &self.inner.config
    }

    /// Returns the read access of an anonymous client under the implicit
    /// client groups of the collection id of the repository. The first call
    /// builds the value, and the handle and its clones keep it.
    pub(crate) fn implicit_reads(&self) -> &ReadAccess {
        self.inner.implicit_reads.get_or_init(|| {
            ReadAccess::new(
                Arc::new(ClientAccess::implicit(self.config().collection_id())),
                AuthItem::Anonymous,
                None,
            )
        })
    }

    /// Returns the path that opened or created this handle, as the caller gave it.
    ///
    /// The constructor does not make the path canonical and does not resolve it
    /// with `readlink("/proc/self/fd/N")`, so a relative path stays relative.
    ///
    /// For [`open_at`](Repo::open_at) and [`create_at`](Repo::create_at), the
    /// value is relative to the `dir` descriptor of that call. Without that
    /// descriptor, the value does not resolve.
    ///
    /// A relative path has its meaning only in the process and the working
    /// directory that opened the handle. Another process needs the absolute
    /// form of the path.
    pub fn path(&self) -> &Path {
        &self.inner.path
    }

    /// Returns the remotes directory of the handle.
    ///
    /// For an open, the value is the value that [`OpenOptions`] selected. A
    /// value of an option is as the caller gave it. The key
    /// `[ex-ostrya] remotes-config-dir` gives a [`Path`](RemotesDir::Path)
    /// value for an absolute path and an [`InRepo`](RemotesDir::InRepo) value
    /// for a relative path. For a create, the value is the value of
    /// [`CreateOptions::remotes_dir`], or the value of the key that
    /// [`CreateOptions::set`] wrote, or `None` if the create got neither.
    /// A handle with no remotes directory gives `None`, for example a handle
    /// of [`Repo::open_at_strict`].
    pub fn remotes_dir(&self) -> Option<&RemotesDir> {
        self.inner.remotes_dir.as_ref()
    }

    /// Returns the descriptor of the `objects` directory of the repository.
    ///
    /// The handle opened the directory read-only at the open, so the
    /// descriptor refers to the directory that the handle reads, also after a
    /// rename of the repository. The descriptor is valid while the handle
    /// lives. A caller that needs it for a longer time duplicates it with
    /// [`BorrowedFd::try_clone_to_owned`].
    pub fn objects_dir(&self) -> BorrowedFd<'_> {
        self.objects_fd()
    }

    /// Returns `true` if the repository seals its objects with fs-verity.
    ///
    /// The result comes from [`RepoConfig::fsverity`]:
    ///
    /// - `yes` gives `true`. A write fails if a seal fails.
    /// - `no` gives `false`.
    /// - `maybe` gives the result of a probe. The probe makes a temp file in
    ///   `tmp/`, writes one byte, and enables fs-verity on it. If the enable
    ///   fails, the result is `false`. The probe removes the file. The
    ///   handle runs the probe one time, and each later call on the handle or
    ///   on a clone of it gives the same result. A transaction of the handle
    ///   seals no object when the result is `false`.
    ///
    /// The result covers the objects that a write stages. An object that the
    /// repository holds from before, for example from a write with
    /// `fsverity=no`, can have no seal. A composefs image build reads the
    /// digest of a sealed object from the kernel.
    ///
    /// # Errors
    ///
    /// - The errors of [`RepoConfig::fsverity`].
    /// - [`Error::InvalidFormat`] if `tmp` is a symlink or is not a
    ///   directory.
    /// - [`Error::Io`] if the probe cannot create `tmp/`, or cannot open or
    ///   write its temp file.
    pub async fn seals_objects(&self) -> Result<bool> {
        match self.inner.config.fsverity()? {
            Tristate::Yes => Ok(true),
            Tristate::No => Ok(false),
            Tristate::Maybe => self.probe_seal().await,
        }
    }

    /// Returns `true` if the file system of the repository seals a staged
    /// object, for the `maybe` value of `[ex-integrity] fsverity`.
    ///
    /// The handle runs the probe one time and keeps the result. The call
    /// does not read the config.
    ///
    /// # Errors
    ///
    /// The probe errors of [`seals_objects`](Repo::seals_objects).
    pub(crate) async fn probe_seal(&self) -> Result<bool> {
        if let Some(sealed) = self.inner.seal_probe.get() {
            return Ok(*sealed);
        }
        let repo = self.clone();
        let sealed =
            ostrya_rt::unblock(move || crate::write::probe_seal_blocking(repo.root_dir())).await?;
        Ok(*self.inner.seal_probe.get_or_init(|| sealed))
    }

    /// Begins a transaction that holds the repository lock shared.
    ///
    /// A shared lock matches the read lock that the `ostree` command holds
    /// during a commit. Many transactions can commit at the same time, in this
    /// process and across processes. If `[core] locking` is on, a held
    /// [`UpdateGuard`](crate::UpdateGuard) holds the repository lock shared,
    /// so a transaction can begin and stage objects while a guard is held.
    ///
    /// [`transaction_with_lock`](Repo::transaction_with_lock) describes the
    /// lock wait and the staging directory.
    ///
    /// # Errors
    ///
    /// - [`Error::LockTimeout`] if the wait for the lock passes
    ///   `[core] lock-timeout-secs`.
    /// - [`Error::Core`] if `[core] locking`, `fsync`, or `per-object-fsync`
    ///   is not a boolean, or if `lock-timeout-secs`, `tmp-expiry-secs`, or
    ///   `min-free-space-percent` is not an integer. In an archive
    ///   repository, also if `[archive] zlib-level` is not an integer.
    /// - [`Error::InvalidFormat`] if `lock-timeout-secs` is less than `-1`,
    ///   if `min-free-space-size` is malformed, or if `min-free-space-percent`
    ///   is outside the range `0` to `100`.
    /// - The errors of [`RepoConfig::fsverity`].
    /// - [`Error::InvalidFormat`] if `tmp` or `tmp/cache` is a symlink or is
    ///   not a directory. The call makes each of them that is absent.
    /// - [`Error::InvalidFormat`] if a symlink or an entry that is not a
    ///   regular file is at `.lock`, when `[core] locking` is on, or at the
    ///   lock file of the new staging directory. The lock open follows no
    ///   symlink. If the process cannot open a FIFO, a socket, or a device
    ///   there for write, the error is [`Error::Io`].
    /// - [`Error::Io`] if the call cannot create the lock file or the staging
    ///   directory, or cannot read the free space of the file system.
    pub async fn transaction(&self) -> Result<Transaction> {
        self.transaction_with_lock(LockKind::Shared).await
    }

    /// Begins a transaction that holds the repository lock in `kind`.
    ///
    /// The wait for the lock retries until `[core] lock-timeout-secs` passes.
    /// If the value is `-1`, the wait has no limit. If `[core] locking` is off,
    /// the transaction takes no repository lock. [`LockKind`] describes the
    /// repository lock.
    ///
    /// The call creates a new staging directory under `tmp/`. Before that, it
    /// removes the staging directories of dead transactions and the other
    /// `tmp/` entries older than `[core] tmp-expiry-secs`. [`Transaction`]
    /// describes the staging directory.
    ///
    /// The transaction starts with a free-space budget. The budget is the
    /// number of bytes available on the file system, less the reserve of
    /// [`RepoConfig::min_free_space`]. Each staged object decreases the budget.
    ///
    /// # Lock order
    ///
    /// A writer outside a transaction takes the repository lock shared, for
    /// example [`set_ref_immediate`](Repo::set_ref_immediate) and
    /// [`write_config`](Repo::write_config). If `[core] locking` is on and a
    /// caller holds a transaction in [`LockKind::Exclusive`], a call to such a
    /// writer waits for the lock of the caller. [`LockKind`] states the result
    /// of this wait.
    ///
    /// # Errors
    ///
    /// - [`Error::LockTimeout`] if the wait for the lock passes
    ///   `[core] lock-timeout-secs`.
    /// - [`Error::Core`] if `[core] locking`, `fsync`, or `per-object-fsync`
    ///   is not a boolean, or if `lock-timeout-secs`, `tmp-expiry-secs`, or
    ///   `min-free-space-percent` is not an integer. In an archive
    ///   repository, also if `[archive] zlib-level` is not an integer.
    /// - [`Error::InvalidFormat`] if `lock-timeout-secs` is less than `-1`,
    ///   if `min-free-space-size` is malformed, or if `min-free-space-percent`
    ///   is outside the range `0` to `100`.
    /// - The errors of [`RepoConfig::fsverity`].
    /// - [`Error::InvalidFormat`] if `tmp` or `tmp/cache` is a symlink or is
    ///   not a directory. The call makes each of them that is absent.
    /// - [`Error::InvalidFormat`] if a symlink or an entry that is not a
    ///   regular file is at `.lock`, when `[core] locking` is on, or at the
    ///   lock file of the new staging directory. The lock open follows no
    ///   symlink. If the process cannot open a FIFO, a socket, or a device
    ///   there for write, the error is [`Error::Io`].
    /// - [`Error::Io`] if the call cannot create the lock file or the staging
    ///   directory, or cannot read the free space of the file system.
    pub async fn transaction_with_lock(&self, kind: LockKind) -> Result<Transaction> {
        // The call parses each `[core]` key that it reads before it takes the
        // lock. So a value that the config cannot carry fails the call before
        // any wait on a contended repository.
        let expiry_secs = self.inner.config.get::<repo::TmpExpirySecs>()?;
        let min_free = self.inner.config.min_free_space()?;
        let settings = Settings::read(&self.inner.config, self.mode())?;
        let guard = self.lock_repo(kind).await?;

        let repo = self.clone();
        let staging =
            ostrya_rt::unblock(move || StagingDir::create(repo.root_dir(), expiry_secs)).await?;

        // The initial free-space budget: the available bytes less the reserve
        // of the config. Each staged object decreases it.
        let repo_fd = self.repo_fd().try_clone_to_owned()?;
        let budget = ostrya_rt::unblock(move || free_budget(repo_fd.as_fd(), min_free)).await?;

        Ok(Transaction::new(
            self.clone(),
            guard,
            staging,
            budget,
            settings,
        ))
    }

    /// Takes the repository lock in `kind` and holds it until the guard drops.
    ///
    /// The call reads `[core] locking` and `[core] lock-timeout-secs`. If
    /// `locking` is true, the acquire retries until the timeout passes and then
    /// fails with [`Error::LockTimeout`]. If `lock-timeout-secs` is `-1`, it
    /// retries with no limit.
    ///
    /// If `locking` is false, the guard holds no lock. The call reads
    /// `lock-timeout-secs` in both cases, so a value that the config cannot
    /// carry fails the call.
    pub(crate) async fn lock_repo(&self, kind: LockKind) -> Result<LockGuard> {
        let locking = self.inner.config.get::<repo::Locking>()?;
        let timeout_secs = self.inner.config.get::<repo::LockTimeoutSecs>()?.get();
        if !locking {
            return Ok(LockGuard::disabled());
        }
        // The calling task reads a cached lock. Only the first use of the
        // handle opens the lock file on the blocking pool.
        let cached = self.inner.lock.lock().unwrap().clone();
        let lock = match cached {
            Some(lock) => lock,
            None => {
                let repo = self.clone();
                ostrya_rt::unblock(move || repo.inner.repo_lock()).await?
            }
        };
        lock::acquire(lock, kind, lock_timeout(timeout_secs)).await
    }

    /// Takes the update lock and holds it until the guard drops.
    ///
    /// The lock is exclusive across processes and in the process. The waiters
    /// of one process take it in the order of the first poll of their calls.
    /// Only the first of them makes lock requests.
    ///
    /// The call reads `[core] lock-timeout-secs`. The timeout covers the wait
    /// in the queue and the retries against other processes, and then the call
    /// fails with [`Error::LockTimeout`]. If the value is `-1`, the wait has no
    /// limit. If the value is `0`, the call makes one attempt.
    ///
    /// The call ignores `[core] locking` and always takes the lock.
    ///
    /// The first call on a handle opens the lock file on the blocking pool
    /// before it joins the queue. That call joins the queue when the open
    /// completes, and the timeout does not cover the open. Each later call on
    /// the handle, or on a clone of it, joins the queue on its first poll.
    ///
    /// A release always drops the record lock, so another process can take
    /// the lock between two holders of this process.
    ///
    /// Take the repository lock before the update lock, never the reverse.
    /// Against other processes the lock has no order. A waiter can lose every
    /// retry to another process until the timeout passes.
    pub(crate) async fn lock_update(&self) -> Result<UpdateLockHeld> {
        let timeout_secs = self.inner.config.get::<repo::LockTimeoutSecs>()?.get();
        // The calling task reads a cached lock, so the call joins the queue on
        // its first poll. Only the first use of the handle opens the
        // lock file on the blocking pool.
        let cached = self.inner.update_lock.lock().unwrap().clone();
        let lock = match cached {
            Some(lock) => lock,
            None => {
                let repo = self.clone();
                ostrya_rt::unblock(move || repo.inner.update_lock()).await?
            }
        };
        lock::acquire_update(lock, lock_timeout(timeout_secs)).await
    }

    /// Takes the repository lock shared, then the update lock, and holds both
    /// until the returned value drops.
    ///
    /// The call reads `[core] locking` and `[core] lock-timeout-secs` before
    /// it waits, so a value that the config cannot carry fails the call at
    /// once. Each of the two waits gets the full timeout. If `locking` is
    /// false, the call does not take the repository lock. It always takes the
    /// update lock.
    pub(crate) async fn lock_for_update(&self) -> Result<UpdateLocks> {
        self.inner.config.get::<repo::Locking>()?;
        self.inner.config.get::<repo::LockTimeoutSecs>()?;
        let repo = self.lock_repo(LockKind::Shared).await?;
        let update = self.lock_update().await?;
        Ok(UpdateLocks { update, repo })
    }

    /// Takes the repository lock shared, then the update lock, as
    /// [`lock_for_update`](Repo::lock_for_update) does, and runs `write` on
    /// the blocking pool under both.
    ///
    /// The locks move into the blocking closure and drop at its end. So a
    /// caller that drops the returned future cannot release them while `write`
    /// still runs.
    pub(crate) async fn write_locked<T, F>(&self, write: F) -> Result<T>
    where
        F: FnOnce(&Repo) -> Result<T> + Send + 'static,
        T: Send + 'static,
    {
        let locks = self.lock_for_update().await?;
        self.write_holding(locks, write).await
    }

    /// Runs `write` on the blocking pool under `locks`, and releases them when
    /// `write` ends, as [`write_locked`](Repo::write_locked) does.
    ///
    /// A caller that must read under the locks before its write takes them
    /// first.
    pub(crate) async fn write_holding<T, F>(&self, locks: UpdateLocks, write: F) -> Result<T>
    where
        F: FnOnce(&Repo) -> Result<T> + Send + 'static,
        T: Send + 'static,
    {
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let written = write(&repo);
            drop(locks);
            written
        })
        .await
    }

    /// Returns `true` if `held` is a hold of the update lock of this repository.
    pub(crate) fn holds_update_lock(&self, held: &UpdateLockHeld) -> bool {
        self.inner
            .update_lock
            .lock()
            .unwrap()
            .as_ref()
            .is_some_and(|lock| held.is_of(lock))
    }

    /// Reads `config` from disk and parses it. The call does not read the
    /// remotes directory. The result takes the overrides of the handle.
    ///
    /// The handle keeps the config that it read at the open.
    pub(crate) async fn read_config_file(&self) -> Result<RepoConfig> {
        let repo = self.clone();
        ostrya_rt::unblock(move || repo.read_config_with_overrides()).await
    }

    /// Reads `config` and the `.conf` files of the remotes directory of the
    /// handle from disk and parses them. The call does not read the key
    /// `[ex-ostrya] remotes-config-dir` again. The result takes the
    /// overrides of the handle.
    pub(crate) async fn read_config_and_remotes(&self) -> Result<RepoConfig> {
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let config = repo.read_config_with_overrides()?;
            match repo.remotes_dir() {
                Some(dir) => remotes_dir::read_remotes(config, repo.repo_fd(), dir),
                None => Ok(config),
            }
        })
        .await
    }

    /// Reads `config` from disk and parses it, with the overrides of the
    /// handle. Blocks the calling thread.
    fn read_config_with_overrides(&self) -> Result<RepoConfig> {
        Ok(read_config(self.root_dir())?.with_overrides(self.config().overrides().clone()))
    }

    /// Returns the handle of the repository root.
    pub(crate) fn root_dir(&self) -> &RepoDir {
        &self.inner.root
    }

    /// Returns the descriptor of the repository root. Descriptor-relative
    /// access to `refs/`, `state/`, and the rest of the layout starts from it.
    pub(crate) fn repo_fd(&self) -> BorrowedFd<'_> {
        self.inner.root.as_fd()
    }

    /// Returns the handle of `objects/`. Each read of a loose object starts
    /// from it.
    pub(crate) fn objects(&self) -> &RepoDir {
        &self.inner.objects
    }

    /// Returns the descriptor of `objects/`. Access to loose objects starts
    /// from it.
    pub(crate) fn objects_fd(&self) -> BorrowedFd<'_> {
        self.inner.objects.as_fd()
    }

    /// Assembles the handle. `path` is the argument that the caller gave the
    /// constructor, stored as given for [`Repo::path`].
    fn assemble(materials: Materials, path: PathBuf) -> Repo {
        Repo {
            inner: Arc::new(RepoInner {
                root: materials.root,
                objects: materials.objects,
                config: materials.config,
                path,
                remotes_dir: materials.remotes_dir,
                lock: Mutex::new(None),
                update_lock: Mutex::new(None),
                implicit_reads: OnceLock::new(),
                seal_probe: OnceLock::new(),
            }),
        }
    }
}

/// Refuses the bytes of a `config` larger than [`MAX_CONFIG_SIZE`], so that a
/// write leaves no file that an open refuses. The message is the message of
/// the read of such a file.
pub(crate) fn check_config_size(bytes: &[u8]) -> Result<()> {
    if bytes.len() as u64 > MAX_CONFIG_SIZE {
        return Err(Error::InvalidFormat(format!(
            "config is larger than its cap of {MAX_CONFIG_SIZE} bytes"
        )));
    }
    Ok(())
}

/// Reads `config` at the repository root `root` and parses it, as the open of
/// a handle does. Blocks the calling thread.
///
/// The read is [`RepoDir::read_capped`] with the cap [`MAX_CONFIG_SIZE`]. It
/// follows no symlink, does not block on a FIFO, and refuses a file that is
/// not a regular file or that is larger than the cap.
pub(crate) fn read_config(root: &RepoDir) -> Result<RepoConfig> {
    parse_config(&root.read_capped(RootFile::Config.name(), MAX_CONFIG_SIZE)?)
}

/// Parses the bytes of `config`. This step is CPU work only. The read of the
/// file refuses a file larger than [`MAX_CONFIG_SIZE`].
fn parse_config(bytes: &[u8]) -> Result<RepoConfig> {
    let text = std::str::from_utf8(bytes)
        .map_err(|_| Error::InvalidFormat("config is not valid UTF-8".into()))?;
    RepoConfig::parse(text)
}

/// Returns the lock wait of a `lock-timeout-secs` value. The config reader
/// refuses a value less than -1, so a negative value here is -1, which means
/// no limit.
fn lock_timeout(secs: i64) -> Option<Duration> {
    u64::try_from(secs).ok().map(Duration::from_secs)
}

/// Computes the initial free-space budget of a transaction: the bytes
/// available on the file system of the repository, less the `min-free-space`
/// reserve of the config. Runs a synchronous [`repo_fs::fs_space`].
fn free_budget(repo_fd: BorrowedFd<'_>, min_free: MinFreeSpace) -> Result<u64> {
    let (available, total) = repo_fs::fs_space(repo_fd)?;
    let reserved = match min_free {
        MinFreeSpace::Percent(percent) => ((u128::from(total) * u128::from(percent)) / 100) as u64,
        MinFreeSpace::Size(spec) => spec.bytes(),
    };
    Ok(available.saturating_sub(reserved))
}

/// Opens an existing repository directory and gathers its materials, in the
/// strict open mode if `strict` is set. The strict open mode reads no remotes
/// directory.
fn open_materials<Fd: AsFd>(
    dir: Fd,
    path: &Path,
    strict: bool,
    opts: OpenOptions,
) -> Result<Materials> {
    let mut materials = materials_from_root(RepoDir::open_root(dir, path)?)?;
    if strict {
        return Ok(materials);
    }
    materials.config = materials.config.with_overrides(Arc::new(opts.overrides));
    materials.select_remotes_dir(opts.remotes_dir.as_ref(), opts.default_remotes_dir.as_ref())
}

/// Creates the repository layout and the config, then gathers the
/// materials.
///
/// The call makes the text of a new `config` before it creates a directory,
/// so a refusal of the remotes directory value writes nothing. The call
/// refuses a root that holds an entry `config` before it creates a layout
/// directory, so that refusal writes nothing either. A symlink or an entry
/// that is not a directory at a path of the layout fails the call before it
/// writes `config`.
fn create_materials<Fd: AsFd>(dir: Fd, path: &Path, opts: CreateOptions) -> Result<Materials> {
    let config = initial_config_text(&opts)?;
    let root = RepoDir::create_root(dir, path, opts.mode, true)?;
    if root.exists(RootFile::Config.name())? {
        return Err(Error::RepoExists(path.to_owned()));
    }
    for kind in INIT_KINDS {
        // The handle of `tmp/` stays in the context of the root, for the temp
        // file of `config`. Each other handle drops at once.
        match kind {
            RepoLayout::Tmp => root.tmp_dir(true)?,
            kind => root.ensure_layout(kind, true)?,
        };
    }
    write_initial_config(&root, path, &config)?;
    let mut materials = materials_from_root(root)?;
    materials.config = materials.config.with_overrides(Arc::new(opts.overrides));
    materials.select_remotes_dir(opts.remotes_dir.as_ref(), None)
}

/// Reads and parses the config, and opens `objects/`, given the handle of the
/// repository root. The materials have no remotes directory.
///
/// The open of `objects/` comes after the handle of the root takes the mode of
/// the config, so the handle of `objects/` has that mode too.
fn materials_from_root(root: RepoDir) -> Result<Materials> {
    let config = read_config(&root)?;
    let root = root.with_repo_mode(config.mode());
    let objects = root.open_layout(RepoLayout::Objects)?;
    Ok(Materials {
        root,
        objects,
        config,
        remotes_dir: None,
    })
}

/// Writes the initial `config` text `text` at the repository root `root`.
///
/// The call writes a temp file in `tmp/`, forces the mode `0644` on it
/// whatever the umask, as the `ostree` command does, syncs it, and puts it at
/// `config` only if no entry `config` exists. It then syncs the root. If an
/// entry `config` exists, the call keeps it and gives [`Error::RepoExists`]
/// with `path`, the path of the root as the caller gave it.
fn write_initial_config(root: &RepoDir, path: &Path, text: &str) -> Result<()> {
    match root.write_root_file(
        RootFile::Config,
        text.as_bytes(),
        Publish::KeepExisting,
        true,
    )? {
        Published::Created => Ok(()),
        Published::Existed => Err(Error::RepoExists(path.to_owned())),
    }
}

/// Returns the exact config bytes of a new repository.
///
/// `[core]` starts with `repo_version`, `mode`, and `collection-id`. The
/// other keys of the create follow in the order of their first call, and
/// each group comes at the place of its first key. The key of the remotes
/// directory value comes last in `[ex-ostrya]`.
///
/// # Errors
///
/// [`Error::InvalidInput`] if a key file cannot hold the text of a value.
fn initial_config_text(opts: &CreateOptions) -> Result<String> {
    let core = repo::Group::NAME;
    let collection_id = <repo::CollectionId as Key<repo::Group>>::NAME;
    let mut keyfile = KeyFile::default();
    keyfile.set_value(core, "repo_version", "1")?;
    keyfile.set_value(core, "mode", opts.mode.as_mode_str())?;
    let is_id = |e: &&Entry| e.group == core && e.key == collection_id;
    let ids = opts.values.iter().filter(is_id);
    for entry in ids.chain(opts.values.iter().filter(|e| !is_id(e))) {
        keyfile
            .set_value(entry.group, entry.key, &entry.text)
            .map_err(|err| {
                Error::InvalidInput(format!(
                    "the value of [{}] {}: {err}",
                    entry.group, entry.key
                ))
            })?;
    }
    if let Some(value) = remotes_dir_value(opts.remotes_dir.as_ref())? {
        keyfile.set_string(EX_OSTRYA, REMOTES_CONFIG_DIR, value)?;
    }
    Ok(keyfile.to_string())
}

/// Returns `path` as the UTF-8 text of the key `remotes-config-dir`, or
/// refuses it with [`Error::InvalidInput`].
fn utf8_key_value(path: &Path) -> Result<&str> {
    path.to_str().ok_or_else(|| {
        Error::InvalidInput(format!(
            "the remotes directory path {} is not valid UTF-8",
            path.display()
        ))
    })
}

/// Returns the value of the key `remotes-config-dir` that names `dir` in a
/// new `config`, or `None` if the create writes no key.
///
/// A [`RemotesDir::Path`] value and a [`RemotesDir::InRepo`] value give
/// their path as given. A [`RemotesDir::Fd`] value has no path, so it gives
/// no key.
fn remotes_dir_value(dir: Option<&RemotesDir>) -> Result<Option<&str>> {
    match dir {
        Some(RemotesDir::Path(path) | RemotesDir::InRepo(path)) => utf8_key_value(path).map(Some),
        Some(RemotesDir::Fd(_)) | None => Ok(None),
    }
}

/// Checks at compile time that a repository handle and the options types are
/// `Send + Sync`, so that they can move across tasks and threads, and that the
/// futures of an open and of a create are `Send`.
#[allow(dead_code)]
fn assert_send_sync() {
    fn is_send_sync<T: Send + Sync>() {}
    fn is_send<T: Send>(_: &T) {}
    is_send_sync::<Repo>();
    is_send_sync::<OpenOptions>();
    is_send_sync::<CreateOptions>();
    is_send_sync::<RemotesDir>();
    let _ = |opts: &OpenOptions, path: &Path| is_send(&opts.open(path));
    let _ =
        |opts: &OpenOptions, dir: BorrowedFd<'_>, path: &Path| is_send(&opts.open_at(dir, path));
    let _ = |opts: &CreateOptions, path: &Path| is_send(&opts.create(path));
    let _ = |opts: &CreateOptions, dir: BorrowedFd<'_>, path: &Path| {
        is_send(&opts.create_at(dir, path))
    };
}

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

    #[test]
    fn lock_timeout_maps_the_config_value() {
        assert_eq!(lock_timeout(-1), None);
        assert_eq!(lock_timeout(0), Some(Duration::ZERO));
        assert_eq!(lock_timeout(5), Some(Duration::from_secs(5)));
    }

    /// A `config` that appears after the check of the create, before the
    /// publish of the new file, gives `RepoExists` and keeps its bytes.
    /// `tmp/` then holds no named temp file. On a file system with
    /// `O_TMPFILE`, the write makes no named temp file, so this check can
    /// fail only on a file system without `O_TMPFILE`.
    #[test]
    fn initial_config_write_refuses_an_existing_config() {
        let dir = crate::repo_fs::TestDir::new("initial-config");
        std::fs::write(dir.path().join("config"), b"race").unwrap();
        let root = RepoDir::from_root_fd(rustix::io::dup(dir.fd()).unwrap());

        let err = write_initial_config(&root, Path::new("repo"), "[core]\n").unwrap_err();
        assert!(
            matches!(&err, Error::RepoExists(p) if p == Path::new("repo")),
            "{err:?}"
        );
        assert_eq!(std::fs::read(dir.path().join("config")).unwrap(), b"race");
        let temps: Vec<_> = std::fs::read_dir(dir.path().join("tmp"))
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .filter(|name| name.as_bytes().starts_with(b".ostrya-tmp-"))
            .collect();
        assert!(temps.is_empty(), "{temps:?}");
    }

    /// The create makes each kind that the table of the layout marks as made
    /// at the create, and that has a fixed path. The match has no wildcard
    /// arm, so a new kind fails to compile here until the match names it.
    /// Add each kind that the match names to the list `all` too.
    #[test]
    fn init_kinds_are_the_kinds_created_at_init() {
        let all = [
            RepoLayout::Root,
            RepoLayout::Objects,
            RepoLayout::Staging,
            RepoLayout::Tmp,
            RepoLayout::Refs,
            RepoLayout::State,
            RepoLayout::Extensions,
            RepoLayout::Deltas,
            RepoLayout::DeltaIndexes,
        ];
        for kind in all {
            match kind {
                RepoLayout::Root
                | RepoLayout::Objects
                | RepoLayout::Staging
                | RepoLayout::Tmp
                | RepoLayout::Refs
                | RepoLayout::State
                | RepoLayout::Extensions
                | RepoLayout::Deltas
                | RepoLayout::DeltaIndexes => {}
            }
        }
        let made: Vec<_> = all
            .into_iter()
            .filter(|kind| kind.rules().created_at_init && kind.rules().path.is_some())
            .collect();
        assert_eq!(made, INIT_KINDS);
    }
}