ostrya 0.12.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
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
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
//! Export of a commit as a composefs EROFS image.
//!
//! - [`Repo::export_composefs`] builds the image in memory and returns its
//!   bytes and its fs-verity digest.
//! - [`Repo::export_composefs_to`] writes the image through a file
//!   descriptor.
//! - [`Repo::commit_add_composefs_metadata`] stages a new commit that records
//!   the image digest under `ostree.composefs.digest.v0`.
//! - [`Transaction::composefs_digest`] returns the image digest of a staged
//!   tree.
//!
//! [`ComposefsOptions`] and [`VerityPolicy`] select the verity form of the
//! image.
//!
//! # The image store
//!
//! A repository can store the image of a commit in the file
//! `extensions/ostrya/composefs/<xx>/<rest>.cfs`, outside `objects/`. The
//! name of the file is the checksum of the commit, and its bytes are the image
//! that an export with [`ComposefsOptions::RECORDED`] writes. So its fs-verity
//! digest is the value of the `ostree.composefs.digest.v0` key of the commit.
//! The file has the mode `0644` and no extended attribute in each repository
//! mode.
//!
//! - [`Transaction::build_composefs_image`] writes the image of a tree to the
//!   staging directory, and [`Transaction::attach_composefs_image`] stages it
//!   as the image of a commit.
//! - [`Transaction::write_composefs_image`] stages the image of a commit in
//!   one call.
//! - [`Repo::add_composefs_image`] stores the image of a commit in its own
//!   transaction.
//! - [`Repo::check_composefs_image`] compares a stored image with the key of
//!   its commit, [`Repo::has_composefs_image`] tells if the repository holds
//!   one, and [`Repo::composefs_image_path`] gives its path.
//! - [`Repo::open_composefs_image_checked`] opens a stored image and compares
//!   it with the key through the descriptor that it returns.
//! - [`Repo::objects_dir`] gives the descriptor of the object store. A
//!   composefs mount reads the backing objects of the image through it.
//!
//! Each write refuses a commit without the key and an image whose digest is
//! not the key. A write never holds the whole image in memory. Each read
//! opens the image with `openat2` under the root of the repository, with
//! `RESOLVE_BENEATH`, `RESOLVE_NO_SYMLINKS`, and `O_NONBLOCK`, so a symlink
//! at any component of its path stops the read with
//! [`Error::InvalidFormat`]. The read also refuses an image that is not a
//! regular file with [`Error::InvalidFormat`], and does not wait on a FIFO.
//!
//! If `[ex-ostrya] generate-composefs` is `true`
//! ([`RepoConfig::generate_composefs`](crate::RepoConfig::generate_composefs)),
//! the commit of a transaction builds and stores the image of each complete
//! commit that its writer records and that carries the key.
//! [`Transaction::commit`] states the rule, and [`Repo::seals_objects`] tells
//! if the build can read the fs-verity digests of the objects from the
//! kernel.
//!
//! The prune deletes the image of each commit that it deletes, before the
//! commit. The fsck checks each image against the key of its commit.
//!
//! No transfer carries the image. A pull, a push, a one-way stream, and a
//! static delta carry no composefs image.

use std::collections::HashMap;
use std::future::Future;
use std::io::BufWriter;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::PathBuf;
use std::pin::Pin;

use ostrya_composefs::{
    Content, Directory, Error as WriterError, FsVerityHasher, Image, Metadata, Node, Regular,
    Symlink, build_image, write_image_to, write_image_unhashed_to,
};
use ostrya_core::{
    Checksum, Commit, DirMeta, DirTree, ObjectType, RepoMode, Type, Value, Xattrs, loose_path,
};

use crate::commit::append_dict_entry;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::image_store;
use crate::read::CommitState;
use crate::related::{self, RelatedField};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::{ImageTemp, link_image_blocking, write_image_temp_blocking};

/// The empty top-level directories that the `ostree` command adds to each
/// exported image.
const INJECTED_DIRS: [&str; 5] = ["boot", "etc", "sysroot", "usr", "var"];
/// The mode that the `ostree` command gives each added top-level directory
/// (`040755`).
const INJECTED_DIR_MODE: u32 = 0o040755;
/// The commit metadata key that holds the fs-verity digest of the image.
const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";
/// The GVariant type of the digest value, a 32-byte `ay`.
const DIGEST_SIGNATURE: &str = "ay";
/// The size of each chunk that the hasher reads from a backing object.
pub(crate) const DIGEST_CHUNK: usize = 128 * 1024;
/// The bytes that one xattr spends from the composefs xattr budget of an
/// inode, in addition to its name and its value.
const XATTR_ENTRY_COST: usize = 7;
/// The composefs xattr budget of one inode, in bytes.
const MAX_XATTR_TOTAL: usize = 32755;
/// The longest xattr name that the length field of an EROFS entry can state.
/// The entry stores the name without its prefix, and this suffix is not longer
/// than the full name. The check holds the full name to this bound, so the
/// prefix table stays in the writer.
const MAX_XATTR_NAME: usize = u8::MAX as usize;
/// The repository mode of the loose path that each backing redirect names. The
/// image points at the `.file` objects of a composefs backing store, whatever
/// the mode of the repository that the image comes from.
const BACKING_MODE: RepoMode = RepoMode::BareUser;

/// A boxed `Send` future for the recursive tree walk. Async recursion needs
/// this indirection.
type TreeFuture<'a> = Pin<Box<dyn Future<Output = Result<Directory>> + Send + 'a>>;

/// The place where the composefs walk reads the objects of the tree.
#[derive(Clone, Copy)]
enum ObjectSource<'a> {
    /// A published repository: each object is a loose object under `objects/`.
    Repo(&'a Repo),
    /// A transaction: an object that it staged comes from the staging
    /// directory. An object that deduplicated comes from `objects/`.
    Staged(&'a Transaction),
}

impl ObjectSource<'_> {
    async fn dirtree(&self, checksum: &Checksum) -> Result<DirTree> {
        match self {
            ObjectSource::Repo(repo) => repo.load_dirtree(checksum).await,
            ObjectSource::Staged(txn) => txn.load_dirtree_staged_first(checksum).await,
        }
    }

    async fn dirmeta(&self, checksum: &Checksum) -> Result<DirMeta> {
        match self {
            ObjectSource::Repo(repo) => repo.load_dirmeta(checksum).await,
            ObjectSource::Staged(txn) => txn.load_dirmeta_staged_first(checksum).await,
        }
    }

    /// Loads a file object. If `measure` is set, the same load also reads the
    /// fs-verity digest that the kernel holds for a sealed raw-payload object.
    async fn file(&self, checksum: &Checksum, measure: bool) -> Result<FileObject> {
        match self {
            ObjectSource::Repo(repo) => repo.load_file_with(checksum, measure).await,
            ObjectSource::Staged(txn) => txn.load_file_staged_first_with(checksum, measure).await,
        }
    }
}

/// The verity form of an exported composefs image.
///
/// The policy selects if each backed file carries the fs-verity digest of its
/// content. The export opens each backing object under both policies. The
/// mode, the owner, the size, and the xattrs of the inode come from the file
/// object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerityPolicy {
    /// Each backed file carries the 36-byte metacopy record with the fs-verity
    /// digest of its content.
    ///
    /// This policy is the default.
    ///
    /// If a backing object is sealed with the parameters that
    /// [`Repo::export_composefs`] states, the export reads the digest from the
    /// kernel. For each other backing object, the export streams the payload
    /// to compute the digest.
    #[default]
    Computed,
    /// Each backed file carries the metacopy xattr with an empty value.
    ///
    /// The export reads no payload.
    ///
    /// The image has its own fs-verity digest. This digest is different from
    /// the value that a commit records under `ostree.composefs.digest.v0`.
    /// The recorded value is the digest of the image with verity digests.
    /// [`ComposefsOptions::RECORDED`] gives the options of that image.
    Disabled,
}

/// The options of a composefs export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ComposefsOptions {
    /// The verity policy of the image.
    ///
    /// The default is [`VerityPolicy::Computed`].
    pub verity: VerityPolicy,
}

impl ComposefsOptions {
    /// The options of the image whose fs-verity digest a commit records.
    ///
    /// `ostree.composefs.digest.v0` holds the fs-verity digest of the image
    /// that [`Repo::export_composefs`] and [`Repo::export_composefs_to`] write
    /// with these options. A target machine computes the same digest at boot.
    ///
    /// The policy is [`VerityPolicy::Computed`]. Each backed file in the image
    /// carries the fs-verity digest of its content, so the image digest covers
    /// the content of each backed file.
    /// [`Repo::commit_add_composefs_metadata`] and
    /// [`Transaction::composefs_digest`] use these options, so a change of the
    /// default does not change the recorded digest.
    pub const RECORDED: ComposefsOptions = ComposefsOptions {
        verity: VerityPolicy::Computed,
    };
}

/// The way the export gets the fs-verity digest of each backed file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Digests {
    /// The digest that the kernel holds for a sealed object, or else the
    /// digest of the streamed payload. [`VerityPolicy::Computed`] gives it.
    Computed,
    /// The digest that the kernel holds for a sealed object. An object with
    /// no seal is refused, and no payload is read.
    Sealed,
    /// No digest. [`VerityPolicy::Disabled`] gives it.
    Disabled,
}

/// The fs-verity digests that one build pass computed, keyed by the checksum
/// of the file object.
///
/// A digest that the kernel gives for a sealed object does not go into the
/// cache, because the load of the object reads it at no cost. Each other
/// object is read and hashed one time for each cache.
#[derive(Default)]
struct VerityCache {
    digests: HashMap<Checksum, [u8; 32]>,
    /// The number of objects that the cache read and hashed.
    #[cfg(test)]
    hashed: usize,
}

impl From<VerityPolicy> for Digests {
    fn from(policy: VerityPolicy) -> Digests {
        match policy {
            VerityPolicy::Computed => Digests::Computed,
            VerityPolicy::Disabled => Digests::Disabled,
        }
    }
}

/// The result of a write of the composefs image of a commit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageAdd {
    /// The repository holds no image of the commit. The write adds one.
    Added,
    /// The repository holds an image of the commit, and its digest is the key
    /// of the commit. The write changes nothing.
    ///
    /// An image that the same transaction staged before gives this result
    /// too.
    AlreadyValid,
    /// The repository holds an image of the commit, and its digest is not the
    /// key of the commit or the read of the image fails with an I/O error.
    /// The write replaces it.
    Replaced,
}

/// The state of the stored composefs image of a commit, as
/// [`Repo::check_composefs_image`] gives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageState {
    /// The image is present, and its fs-verity digest is the key of the
    /// commit.
    Valid,
    /// The commit carries the key, and the repository holds no image of it.
    Absent,
    /// The commit does not carry `ostree.composefs.digest.v0`.
    ///
    /// The call does not look for an image in this state.
    NoKey,
    /// The image is present, and its fs-verity digest is not the key of the
    /// commit.
    Mismatch {
        /// The digest that the commit records.
        expected: [u8; 32],
        /// The fs-verity digest of the stored image.
        actual: [u8; 32],
    },
}

/// A composefs image that a transaction wrote to its staging directory and
/// that is not the image of a commit yet.
///
/// [`Transaction::build_composefs_image`] gives it, and
/// [`Transaction::attach_composefs_image`] takes it. A drop removes the image
/// file.
pub struct StagedComposefsImage<'txn> {
    txn: &'txn Transaction,
    /// The image file. `None` after the attach took it.
    image: Option<ImageTemp>,
    digest: [u8; 32],
}

impl StagedComposefsImage<'_> {
    /// Returns the fs-verity digest of the image.
    ///
    /// The value is the one that `ostree.composefs.digest.v0` holds for a
    /// commit of the tree.
    pub fn digest(&self) -> &[u8; 32] {
        &self.digest
    }
}

impl StagedComposefsImage<'_> {
    /// Removes the image file on the blocking pool: the drop of its temp file
    /// runs there.
    async fn discard(mut self) {
        if let Some(image) = self.image.take() {
            ostrya_rt::unblock(move || drop(image)).await;
        }
    }
}

impl std::fmt::Debug for StagedComposefsImage<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StagedComposefsImage")
            .field("digest", &digest_hex(&self.digest))
            .finish_non_exhaustive()
    }
}

/// An error of [`Transaction::build_recorded_images_classified`], with the
/// part of the build that failed.
///
/// A receive session gives each variant its own wire code.
pub(crate) enum RecordedBuildError {
    /// `ostree.composefs.digest.v0` of a commit is not a variant of type `ay`
    /// with 32 bytes.
    Key(Error),
    /// The image of a tree does not have the digest that its commit records:
    /// [`Error::ComposefsDigestMismatch`].
    Mismatch(Error),
    /// Each other error of the build.
    Other(Error),
}

impl From<Error> for RecordedBuildError {
    fn from(e: Error) -> RecordedBuildError {
        RecordedBuildError::Other(e)
    }
}

impl From<RecordedBuildError> for Error {
    fn from(e: RecordedBuildError) -> Error {
        match e {
            RecordedBuildError::Key(e)
            | RecordedBuildError::Mismatch(e)
            | RecordedBuildError::Other(e) => e,
        }
    }
}

/// Methods that compute the composefs digest of a staged tree and stage the
/// composefs image of a commit.
impl Transaction {
    /// Returns the composefs image digest of a tree that this transaction
    /// staged.
    ///
    /// The value is the one that `ostree.composefs.digest.v0` holds: the
    /// fs-verity digest of the image that an export with
    /// [`ComposefsOptions::RECORDED`] writes for the same tree.
    /// [`Repo::export_composefs`] describes the image.
    ///
    /// The call reads each object that this transaction staged from the
    /// staging directory, and each other object from `objects/`. The digest is
    /// available before the transaction commit, so it can go into the metadata
    /// of the commit that the tree belongs to. The value depends on the tree
    /// alone, so a repository of any mode that holds the tree gives the same
    /// digest.
    ///
    /// The image goes to [`std::io::sink`], so the digest needs no image-sized
    /// buffer.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if a dirtree, dirmeta, or file object of the
    ///   tree is in neither the staging directory nor the object store.
    /// - [`Error::Core`] if a dirtree object, a dirmeta object, or the header
    ///   of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`Repo::export_composefs`] lists the limits.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    pub async fn composefs_digest(&self, root: &RepoTree) -> Result<[u8; 32]> {
        let dir = composefs_model(
            ObjectSource::Staged(self),
            root,
            ComposefsOptions::RECORDED.verity.into(),
            &mut VerityCache::default(),
        )
        .await?;
        image_digest(dir).await
    }

    /// Writes the composefs image of a tree to the staging directory of this
    /// transaction.
    ///
    /// The image is the image that an export with
    /// [`ComposefsOptions::RECORDED`] writes for the same tree, so
    /// [`StagedComposefsImage::digest`] is the value of
    /// [`composefs_digest`](Transaction::composefs_digest). The call reads the
    /// objects of the tree as `composefs_digest` reads them. A caller that
    /// writes a new commit takes the digest for the key
    /// `ostree.composefs.digest.v0` of the commit, writes the commit, and then
    /// gives the image to [`attach_composefs_image`](Transaction::attach_composefs_image).
    /// The tree is then read one time.
    ///
    /// The writer computes the fs-verity digest as it writes the image, and
    /// it holds no image-sized buffer. The image file has the mode 0644. If
    /// `[ex-integrity] fsverity` is not `no`, the call seals the file and
    /// compares the digest that the kernel reads with the digest of the
    /// writer. If the `fsync` and `per-object-fsync` values of the
    /// transaction are both on, the call syncs the file. Each value comes from
    /// [`set_fsync`](Transaction::set_fsync) or
    /// [`set_per_object_fsync`](Transaction::set_per_object_fsync) if the
    /// transaction has an override, and else from `[core] fsync` or
    /// `[core] per-object-fsync`.
    ///
    /// # Errors
    ///
    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`.
    /// - The errors of [`composefs_digest`](Transaction::composefs_digest).
    /// - [`Error::Unsupported`] if `[ex-integrity] fsverity` is `yes` and the
    ///   seal fails.
    /// - [`Error::InvalidFormat`] if the digest that the kernel reads for the
    ///   sealed file is not the digest of the writer.
    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` in the
    ///   repository config is malformed.
    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` in the
    ///   repository config is malformed.
    /// - [`Error::Io`] if a write to the image file or another file system
    ///   operation fails.
    pub async fn build_composefs_image(&self, root: &RepoTree) -> Result<StagedComposefsImage<'_>> {
        self.build_composefs_image_with(root, &mut VerityCache::default())
            .await
    }

    /// Makes the steps of
    /// [`build_composefs_image`](Transaction::build_composefs_image), and
    /// takes the fs-verity digest of each object with no seal from `cache`
    /// if it holds one.
    async fn build_composefs_image_with(
        &self,
        root: &RepoTree,
        cache: &mut VerityCache,
    ) -> Result<StagedComposefsImage<'_>> {
        if self.repo().mode() == RepoMode::BareSplitXattrs {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
        let (fsync, per_object_fsync) = self.fsync_flags()?;
        let verity = self.verity().await?;
        let dir = composefs_model(
            ObjectSource::Staged(self),
            root,
            ComposefsOptions::RECORDED.verity.into(),
            cache,
        )
        .await?;
        let staging = self.staging_dir().clone();
        let image = self
            .unblock(move || {
                write_image_temp_blocking(&staging, &dir, fsync && per_object_fsync, verity)
            })
            .await?;
        Ok(StagedComposefsImage {
            txn: self,
            digest: image.digest,
            image: Some(image),
        })
    }

    /// Stages `image` as the composefs image of `commit`.
    ///
    /// The commit comes from the staged set of this transaction, or else from
    /// `objects/`. The call checks the digest of the image against the key
    /// `ostree.composefs.digest.v0` of the commit, and refuses a mismatch. It
    /// then compares the stored image of the commit with the key, if the
    /// repository holds one. The call streams the stored image through the
    /// fs-verity hasher.
    ///
    /// - With no stored image, the call stages the image and returns
    ///   [`ComposefsImageAdd::Added`].
    /// - With a stored image whose digest is the key, the call drops the image
    ///   and returns [`ComposefsImageAdd::AlreadyValid`].
    /// - With a stored image whose digest is not the key, or a stored image
    ///   whose read fails with [`Error::Io`], the call stages the image and
    ///   returns [`ComposefsImageAdd::Replaced`].
    /// - A symlink at a component of the path of the stored image, or a
    ///   stored image that is not a regular file, fails the call with
    ///   [`Error::InvalidFormat`].
    ///
    /// If the call does not stage the image, it removes the image file.
    ///
    /// [`commit`](Transaction::commit) renames a staged image into
    /// `extensions/ostrya/composefs/<xx>/` after it renames the objects of the
    /// transaction into `objects/`. The rename replaces the stored image in
    /// one step. No field of [`TransactionStats`](crate::TransactionStats)
    /// counts the image, and `ostree.sizes` has no entry for it. The image
    /// takes its size from the free-space budget of the transaction.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `image` comes from another transaction.
    /// - [`Error::InvalidInput`] if the commit does not carry
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::InvalidFormat`] if the first entry of that key is not a
    ///   variant of type `ay` with 32 bytes.
    /// - [`Error::ComposefsDigestMismatch`] if the digest of the image is not
    ///   the value of the key.
    /// - [`Error::ObjectNotFound`] if the commit object is not staged and not
    ///   in the object store.
    /// - [`Error::Core`] if the commit object does not parse.
    /// - [`Error::InsufficientFreeSpace`] if the image needs more space than
    ///   the free-space budget of the transaction holds.
    /// - [`Error::InvalidFormat`] if the commit object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] if a symlink is at a component of the path
    ///   of the stored image, or if the stored image is not a regular file.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn attach_composefs_image(
        &self,
        commit: &Checksum,
        image: StagedComposefsImage<'_>,
    ) -> Result<ComposefsImageAdd> {
        if !std::ptr::eq(image.txn, self) {
            image.discard().await;
            return Err(Error::InvalidInput(
                "the composefs image comes from another transaction".into(),
            ));
        }
        let key = async {
            let commit_obj = self.load_commit_staged_first(commit).await?;
            require_recorded_digest(&commit_obj, commit)
        }
        .await;
        match key {
            Ok(key) => self.attach_keyed(commit, &key, image).await,
            Err(e) => {
                image.discard().await;
                Err(e)
            }
        }
    }

    /// Stages `image` as the composefs image of `commit`, with `key` as the
    /// digest that the commit records.
    ///
    /// The call makes the checks and the steps of
    /// [`attach_composefs_image`](Transaction::attach_composefs_image) that
    /// come after the read of the key.
    async fn attach_keyed(
        &self,
        commit: &Checksum,
        key: &[u8; 32],
        image: StagedComposefsImage<'_>,
    ) -> Result<ComposefsImageAdd> {
        let checked = match check_image_digest(commit, key, &image) {
            Ok(()) => self.image_state(commit, key).await,
            Err(e) => Err(e),
        };
        self.finish_attach(commit, checked, image).await
    }

    /// Builds and stages the composefs image of `commit`.
    ///
    /// The call runs [`build_composefs_image`](Transaction::build_composefs_image)
    /// over the root of the commit and
    /// [`attach_composefs_image`](Transaction::attach_composefs_image) with
    /// the result. If the repository holds a valid image of the commit
    /// already, the call builds nothing and returns
    /// [`ComposefsImageAdd::AlreadyValid`].
    ///
    /// The call does not refuse a partial commit. If an object of the tree is
    /// absent, the build fails.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the commit does not carry
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::ComposefsDigestMismatch`] if the image of the tree does not
    ///   have the digest that the commit records.
    /// - The errors of
    ///   [`build_composefs_image`](Transaction::build_composefs_image) and of
    ///   [`attach_composefs_image`](Transaction::attach_composefs_image).
    pub async fn write_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageAdd> {
        let commit_obj = self.load_commit_staged_first(commit).await?;
        let key = require_recorded_digest(&commit_obj, commit)?;
        self.write_keyed_image(commit, commit_obj, &key, &mut VerityCache::default())
            .await
    }

    /// Builds the composefs image of each commit that the writers recorded as
    /// complete, under `[ex-ostrya] generate-composefs`.
    ///
    /// The commit of the transaction calls it before the publication. The call
    /// makes the steps of
    /// [`build_recorded_images_classified`](Transaction::build_recorded_images_classified)
    /// and gives each error as it is.
    pub(crate) async fn build_recorded_images(&self) -> Result<()> {
        self.build_recorded_images_classified()
            .await
            .map_err(Error::from)
    }

    /// Builds the composefs image of each commit that the writers recorded as
    /// complete, under `[ex-ostrya] generate-composefs`. Each error tells the
    /// part of the build that failed.
    ///
    /// With the key `false`, the call builds nothing. The call skips a commit
    /// that this transaction did not stage and that has no `.commitpartial`
    /// marker, a commit whose image is staged, and a commit with no digest
    /// key. For each other commit, it makes the steps of
    /// [`write_composefs_image`](Transaction::write_composefs_image).
    ///
    /// The build reads the fs-verity digest of a sealed object from the
    /// kernel. It reads and hashes each other object one time for each call,
    /// and uses that digest for each commit and each path that names the
    /// object.
    ///
    /// The first error stops the call. The caller then drops the transaction,
    /// so it publishes nothing.
    ///
    /// # Errors
    ///
    /// - [`RecordedBuildError::Key`] if `ostree.composefs.digest.v0` of a
    ///   commit is not a variant of type `ay` with 32 bytes.
    /// - [`RecordedBuildError::Mismatch`] if the image of a tree does not have
    ///   the digest that its commit records.
    /// - [`RecordedBuildError::Other`] for each other error.
    pub(crate) async fn build_recorded_images_classified(
        &self,
    ) -> std::result::Result<(), RecordedBuildError> {
        self.build_recorded_with(&mut VerityCache::default()).await
    }

    /// Makes the steps of
    /// [`build_recorded_images_classified`](Transaction::build_recorded_images_classified)
    /// with `cache` for the fs-verity digests of the objects with no seal.
    async fn build_recorded_with(
        &self,
        cache: &mut VerityCache,
    ) -> std::result::Result<(), RecordedBuildError> {
        let commits = self.take_complete();
        if commits.is_empty() || !self.repo().config().generate_composefs()? {
            return Ok(());
        }
        for commit in &commits {
            if self.is_image_staged(commit) {
                continue;
            }
            if !self.is_staged(commit, ObjectType::Commit)
                && self.repo().commit_state(commit).await? != CommitState::Partial
            {
                continue;
            }
            let commit_obj = self.load_commit_staged_first(commit).await?;
            let key = recorded_digest(&commit_obj).map_err(|e| {
                RecordedBuildError::Key(match e {
                    Error::InvalidFormat(message) => {
                        Error::InvalidFormat(format!("commit {commit}: {message}"))
                    }
                    e => e,
                })
            })?;
            let Some(key) = key else {
                continue;
            };
            self.write_keyed_image(commit, commit_obj, &key, cache)
                .await
                .map_err(|e| match e {
                    e @ Error::ComposefsDigestMismatch { .. } => RecordedBuildError::Mismatch(e),
                    e => RecordedBuildError::Other(e),
                })?;
        }
        Ok(())
    }

    /// Builds and stages the composefs image of `commit`, with `key` as the
    /// digest that `commit_obj`, the commit object, records.
    ///
    /// The call makes the steps of
    /// [`write_composefs_image`](Transaction::write_composefs_image) that
    /// come after the read of the key. The build takes the fs-verity digest
    /// of each object with no seal from `cache` if it holds one.
    async fn write_keyed_image(
        &self,
        commit: &Checksum,
        commit_obj: Commit,
        key: &[u8; 32],
        cache: &mut VerityCache,
    ) -> Result<ComposefsImageAdd> {
        let Some(result) = self.image_state(commit, key).await? else {
            return Ok(ComposefsImageAdd::AlreadyValid);
        };
        let tree = RepoTree::from_parts(
            self.repo().clone(),
            commit_obj.root_dirtree,
            commit_obj.root_dirmeta,
        );
        let image = self.build_composefs_image_with(&tree, cache).await?;
        let checked = check_image_digest(commit, key, &image).map(|()| Some(result));
        self.finish_attach(commit, checked, image).await
    }

    /// Stages `image` as the composefs image of `commit` after the checks of
    /// [`attach_composefs_image`](Transaction::attach_composefs_image).
    ///
    /// `checked` is the result of the checks, as
    /// [`image_state`](Transaction::image_state) gives it. On `Ok(Some(_))`,
    /// the call links the image into the staging directory and returns the
    /// result. On `Ok(None)` or `Err`, it removes the image file and returns
    /// [`ComposefsImageAdd::AlreadyValid`] or the error.
    async fn finish_attach(
        &self,
        commit: &Checksum,
        checked: Result<Option<ComposefsImageAdd>>,
        mut image: StagedComposefsImage<'_>,
    ) -> Result<ComposefsImageAdd> {
        let result = match checked {
            Ok(Some(result)) => result,
            Ok(None) => {
                image.discard().await;
                return Ok(ComposefsImageAdd::AlreadyValid);
            }
            Err(e) => {
                image.discard().await;
                return Err(e);
            }
        };
        let staging = self.staging_dir().clone();
        let temp = image
            .image
            .take()
            .expect("a staged composefs image holds its file until attached");
        let key = *commit;
        let outcome = self
            .unblock(move || link_image_blocking(&staging, temp, &key))
            .await?;
        self.record_image(*commit, outcome)?;
        Ok(result)
    }

    /// Returns the result that a write of a valid image of `commit` gives:
    /// `None` if the transaction staged an image of the commit or the
    /// repository holds a valid one, so the write changes nothing.
    ///
    /// A stored image whose read fails with [`Error::Io`] gives
    /// [`ComposefsImageAdd::Replaced`], so the rename of the publish replaces
    /// it. A symlink on the path of the stored image and a stored image that
    /// is not a regular file give [`Error::InvalidFormat`].
    async fn image_state(
        &self,
        commit: &Checksum,
        key: &[u8; 32],
    ) -> Result<Option<ComposefsImageAdd>> {
        if self.is_image_staged(commit) {
            return Ok(None);
        }
        Ok(match self.repo().stored_image_digest(commit).await {
            Ok(None) => Some(ComposefsImageAdd::Added),
            Ok(Some(digest)) if digest == *key => None,
            Ok(Some(_)) | Err(Error::Io(_)) => Some(ComposefsImageAdd::Replaced),
            Err(e) => return Err(e),
        })
    }
}

/// Methods that export a commit as a composefs image.
impl Repo {
    /// Builds the composefs EROFS image of `commit` in memory.
    ///
    /// The returned [`Image`] holds the bytes of the image and its fs-verity
    /// digest. With [`ComposefsOptions::RECORDED`], the digest is the value
    /// that [`commit_add_composefs_metadata`](Repo::commit_add_composefs_metadata)
    /// records for the tree of the commit. Under [`VerityPolicy::Disabled`],
    /// the digest is different from that value. The image assembly runs on the
    /// blocking pool.
    ///
    /// # Tree model
    ///
    /// The export reads the root tree of the commit. It turns each entry into
    /// a node of the image:
    ///
    /// - A directory gets the mode, the owner, and the xattrs of its dirmeta
    ///   object.
    /// - A symlink stores its target inline.
    /// - An empty regular file has no backing.
    /// - A regular file with content redirects to the loose path of its
    ///   `.file` object, with a leading `/`. Under
    ///   [`VerityPolicy::Computed`], it also carries the fs-verity digest of
    ///   its content.
    ///
    /// The export sets the mtime of each inode to 0, as the `ostree` command
    /// does. It adds the five empty top-level directories that the `ostree`
    /// command adds: `boot`, `etc`, `sysroot`, `usr`, and `var`. Each one has
    /// the mode `040755` and the uid and gid 0. If the root of the commit
    /// already holds one of these names, the entry of the commit stays.
    ///
    /// # Verity digests
    ///
    /// Under [`VerityPolicy::Computed`], the export gets the fs-verity digest
    /// of each backed file in one of two ways:
    ///
    /// - If the object file is the raw payload and `statx` reports its inode
    ///   as sealed, the export reads the digest from the kernel. The seal must
    ///   name SHA-256, 4096-byte blocks, no salt, and the payload size. A
    ///   repository with `[ex-integrity] fsverity` seals with these parameters.
    ///   The read occurs in the blocking-pool call that loads the metadata of
    ///   the object.
    /// - In all other cases, and if the kernel read fails, the export streams
    ///   the payload through the fs-verity hasher in chunks of 128 KiB. It
    ///   buffers no unconstrained blob.
    ///
    /// The export never reads the digest of an `archive` object from the
    /// kernel. The digest of a `.filez` file covers the stored form of the
    /// object, and the image needs the digest of the content.
    ///
    /// The kernel read takes no payload byte, so it does not find damage to
    /// the data or the verity metadata of a sealed object. [`Repo::fsck`] is
    /// the check for object integrity.
    ///
    /// # Repository modes
    ///
    /// The export runs in every repository mode. The EROFS metadata of each
    /// file comes from the file object, as [`Repo::load_file`] reads it in the
    /// mode of the repository. The image stores the logical uid and gid of
    /// each file, whoever runs the export. composefs presents the ownership
    /// through uid mapping at mount.
    ///
    /// The image depends on the committed tree alone. Each regular file
    /// redirects to its `.file` loose path, the form that a composefs backing
    /// store holds. Each digest covers the content of the file, so a
    /// repository of any mode that holds the tree gives the same image and
    /// digest.
    ///
    /// An `archive` repository holds its content objects in `.filez` form. An
    /// image exported from it mounts over a store that holds the same objects
    /// in `.file` form. A `bare-user` repository that pulls the tree is an
    /// example.
    ///
    /// # Limits
    ///
    /// The image cannot hold some trees. The export refuses each of these trees
    /// with [`Error::Unsupported`]:
    ///
    /// - An inode with too many bytes of extended attributes. Each attribute
    ///   spends its name, its value, and 7 bytes from a budget of 32755 bytes
    ///   for the inode. The `ostree` command refuses a tree that spends more.
    ///   At boot, the `ostree` command cannot reproduce a composefs digest of
    ///   such a tree.
    ///   The budget is less than the 65535 bytes that the value-length field
    ///   of an EROFS xattr entry can state, so that field never limits first.
    /// - An xattr name longer than 255 bytes, the limit of the name-length
    ///   field of an EROFS xattr entry. The budget alone does not hold a name
    ///   to this length.
    /// - A symlink target that does not fit in the block of its inode. The
    ///   image stores the target inline, next to the inode header and the
    ///   xattrs of the inode. For a symlink with no xattrs, the limit is 4063
    ///   bytes. The `ostree` command aborts on the same trees. `PATH_MAX` keeps
    ///   a target this long out of a tree that a checkout produces. A tar
    ///   import can produce one.
    /// - A child name longer than 255 bytes. The `ostree` command refuses the
    ///   same trees with `File name too long`. A file system holds no name
    ///   this long. A tar import can produce one.
    /// - A child name that is empty, is `.` or `..`, or holds `/`.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    pub async fn export_composefs(
        &self,
        commit: &Checksum,
        opts: &ComposefsOptions,
    ) -> Result<Image> {
        let dir = self
            .composefs_export_model(commit, opts.verity.into())
            .await?;
        ostrya_rt::unblock(move || build_image(&dir))
            .await
            .map_err(writer_error)
    }

    /// Writes the composefs image of `commit` to `out` and returns its digest.
    ///
    /// The image and its fs-verity digest are the same as those of
    /// [`export_composefs`](Repo::export_composefs), with the same options,
    /// the same repository modes, and the same limits.
    ///
    /// The call writes the image to the file descriptor as it serializes it.
    /// The output is append-only, so the call holds no image-sized buffer. It
    /// writes `out` from its current offset and never seeks it. If the call
    /// fails, the bytes that it already wrote stay in `out`.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`export_composefs`](Repo::export_composefs) lists the limits.
    /// - [`Error::Io`] if the duplicate of `out` fails, or if a write to `out`
    ///   or its flush fails.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if another file system operation fails, or if an
    ///   `archive` payload does not inflate.
    pub async fn export_composefs_to(
        &self,
        commit: &Checksum,
        opts: &ComposefsOptions,
        out: BorrowedFd<'_>,
    ) -> Result<[u8; 32]> {
        let dir = self
            .composefs_export_model(commit, opts.verity.into())
            .await?;
        // The blocking pool needs an owned handle, so the call duplicates the
        // descriptor of the caller for the closure to move.
        let fd = out.try_clone_to_owned()?;
        ostrya_rt::unblock(move || write_image_to_fd(&dir, fd))
            .await
            .map_err(writer_error)
    }

    /// Writes the composefs image of `commit` to `out` for a mount, and
    /// returns the size of the image in bytes.
    ///
    /// The image is the image of
    /// [`export_composefs_to`](Repo::export_composefs_to) with `verity`, with
    /// these changes:
    ///
    /// - Under [`VerityPolicy::Computed`], the call takes the fs-verity digest
    ///   of each backed file from the kernel alone, and reads no payload. An
    ///   object with no seal, or with a seal of other parameters, fails the
    ///   call. An overlay with `verity=require` cannot open such an object.
    /// - The call computes no fs-verity digest of the image.
    /// - The call computes the size of the image before it writes, and
    ///   refuses an image larger than `max_size` bytes with no write.
    ///
    /// The function is not a stable API.
    ///
    /// # Errors
    ///
    /// - [`Error::Unsupported`] if a backed file has no seal under
    ///   [`VerityPolicy::Computed`], or if the image is larger than
    ///   `max_size` bytes.
    /// - The errors of [`export_composefs_to`](Repo::export_composefs_to).
    #[doc(hidden)]
    pub async fn export_composefs_for_mount(
        &self,
        commit: &Checksum,
        verity: VerityPolicy,
        out: BorrowedFd<'_>,
        max_size: u64,
    ) -> Result<u64> {
        let digests = match verity {
            VerityPolicy::Computed => Digests::Sealed,
            VerityPolicy::Disabled => Digests::Disabled,
        };
        let dir = self.composefs_export_model(commit, digests).await?;
        let fd = out.try_clone_to_owned()?;
        ostrya_rt::unblock(move || {
            let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
            write_image_unhashed_to(&dir, &mut out, max_size)
        })
        .await
        .map_err(writer_error)
    }

    /// Returns the composefs tree model of the root of `commit`. The two
    /// export entry points share this step.
    async fn composefs_export_model(
        &self,
        commit: &Checksum,
        digests: Digests,
    ) -> Result<Directory> {
        let (commit_obj, _) = self.load_commit(commit).await?;
        self.composefs_commit_model(&commit_obj, digests).await
    }

    /// Returns the composefs tree model of the root of a loaded commit.
    async fn composefs_commit_model(
        &self,
        commit_obj: &Commit,
        digests: Digests,
    ) -> Result<Directory> {
        let tree = RepoTree::from_parts(
            self.clone(),
            commit_obj.root_dirtree,
            commit_obj.root_dirmeta,
        );
        composefs_model(
            ObjectSource::Repo(self),
            &tree,
            digests,
            &mut VerityCache::default(),
        )
        .await
    }

    /// Stages a new commit that records the composefs image digest of
    /// `commit`.
    ///
    /// The digest is the fs-verity digest of the image that
    /// [`export_composefs`](Repo::export_composefs) writes with
    /// [`ComposefsOptions::RECORDED`]. The `ostree` command stores this value
    /// and verifies it at boot.
    ///
    /// The call appends the key `ostree.composefs.digest.v0` to the metadata
    /// dict of `commit`, with the 32-byte digest as an `ay` value. The other
    /// fields of the commit stay the same. The call stages the new commit in
    /// `txn` and returns its checksum. The new commit publishes when `txn`
    /// commits.
    ///
    /// The new commit keeps field 2 of `commit`, the dependencies, with no
    /// change. Before the call builds the image, it checks field 2 with the
    /// rules of [`write_commit`](Transaction::write_commit): each entry has a
    /// name that is not empty and a checksum of 32 bytes, the entries are
    /// sorted by name in byte order with no name two times, and each
    /// dependency is complete in the repository or in `txn` and has no
    /// dependency of its own.
    ///
    /// The image depends on the tree of the commit alone, so the metadata of
    /// the commit and the repository mode do not change the digest.
    ///
    /// If `[ex-ostrya] generate-composefs` is `false`, the image goes to
    /// [`std::io::sink`], so the digest needs no image-sized buffer, and the
    /// call stores no image. If the key is `true`, the call builds the image
    /// in `txn` with
    /// [`build_composefs_image`](Transaction::build_composefs_image), takes
    /// the digest from it, and stages it as the image of the new commit with
    /// [`attach_composefs_image`](Transaction::attach_composefs_image). So
    /// the call reads the tree one time, and the commit of `txn` stores the
    /// image. A new commit that the repository holds already, complete or
    /// partial, is not staged and gets no image.
    ///
    /// # Errors
    ///
    /// - The errors of
    ///   [`RepoConfig::generate_composefs`](crate::RepoConfig::generate_composefs).
    /// - [`Error::InvalidFormat`] if `commit` already carries
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::InvalidRelated`] with `commit` if field 2 of `commit` is
    ///   defective, if its entries are not sorted or have a name two times,
    ///   or if a dependency is absent, partial, or has a dependency of its
    ///   own.
    /// - [`Error::Core`] if the commit tuple of a dependency does not frame,
    ///   or if its field 2 does not decode.
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`export_composefs`](Repo::export_composefs) lists the limits.
    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`,
    ///   or if `[ex-integrity] fsverity` is `yes` and the fs-verity seal of
    ///   the new commit object fails.
    /// - [`Error::InsufficientFreeSpace`] if the new commit object needs more
    ///   space than the free-space budget of the transaction holds.
    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` in the
    ///   repository config is malformed.
    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` or
    ///   `[ex-integrity] composefs` in the repository config is malformed.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    /// - If `[ex-ostrya] generate-composefs` is `true`, the errors of
    ///   [`build_composefs_image`](Transaction::build_composefs_image) and of
    ///   [`attach_composefs_image`](Transaction::attach_composefs_image).
    pub async fn commit_add_composefs_metadata(
        &self,
        txn: &Transaction,
        commit: &Checksum,
    ) -> Result<Checksum> {
        let (mut commit_obj, _) = self.load_commit(commit).await?;
        if commit_obj.metadata.dict_get(COMPOSEFS_DIGEST_KEY).is_some() {
            return Err(Error::InvalidFormat(format!(
                "commit already carries {COMPOSEFS_DIGEST_KEY}"
            )));
        }
        let deps = related::checked_entries(
            RelatedField::Dependencies,
            Some(*commit),
            related::entries_of(&commit_obj.related),
        )?;
        related::check_order(Some(*commit), deps.iter().map(|(name, _)| name.as_str()))?;
        related::check_dependencies(txn, Some(*commit), &deps).await?;
        // With the key, the one build gives the digest and the image, so the
        // commit of `txn` does not build the image again.
        let image = if self.config().generate_composefs()? {
            let tree = RepoTree::from_parts(
                self.clone(),
                commit_obj.root_dirtree,
                commit_obj.root_dirmeta,
            );
            Some(txn.build_composefs_image(&tree).await?)
        } else {
            None
        };
        let fs_verity = match &image {
            Some(image) => *image.digest(),
            None => {
                let dir = self
                    .composefs_commit_model(&commit_obj, ComposefsOptions::RECORDED.verity.into())
                    .await?;
                image_digest(dir).await?
            }
        };
        let digest_type = Type::parse(DIGEST_SIGNATURE).map_err(ostrya_core::Error::from)?;
        let value = Value::variant(digest_type, Value::Bytes(fs_verity.to_vec()));
        append_dict_entry(&mut commit_obj.metadata, COMPOSEFS_DIGEST_KEY, value)?;
        let bytes = commit_obj.serialize()?;
        let new = txn.write_metadata(ObjectType::Commit, None, &bytes).await?;
        // A new commit that the repository holds already is not staged, and
        // gets no image. The discard of the image removes its file.
        match image {
            Some(image) if txn.is_staged(&new, ObjectType::Commit) => {
                txn.attach_composefs_image(&new, image).await?;
            }
            Some(image) => image.discard().await,
            None => {}
        }
        Ok(new)
    }

    /// Builds and stores the composefs image of `commit`.
    ///
    /// The call begins a transaction before it reads the commit, runs
    /// [`Transaction::write_composefs_image`], and commits the transaction.
    /// The transaction holds the repository lock shared, so a prune cannot
    /// remove the commit or its objects during the build. The transaction
    /// applies the fsync policy, the fs-verity seal, and the free-space budget
    /// of the repository. If the call fails, it stores nothing.
    ///
    /// The commit must carry `ostree.composefs.digest.v0`.
    /// [`commit_add_composefs_metadata`](Repo::commit_add_composefs_metadata)
    /// writes a commit with the key. It stores the image only if
    /// `[ex-ostrya] generate-composefs` is `true`.
    ///
    /// # Errors
    ///
    /// - The errors of [`Repo::transaction`].
    /// - The errors of [`Transaction::write_composefs_image`].
    /// - The errors of [`Transaction::commit`].
    pub async fn add_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageAdd> {
        let txn = self.transaction().await?;
        let result = txn.write_composefs_image(commit).await?;
        txn.commit().await?;
        Ok(result)
    }

    /// Returns the path of the composefs image of `commit`.
    ///
    /// The path is [`path`](Repo::path) joined with
    /// `extensions/ostrya/composefs/<xx>/<rest>.cfs`, where `<xx><rest>` is
    /// the checksum of the commit. The call does no I/O, so the image need not
    /// exist. A relative [`path`](Repo::path) gives a relative result.
    pub fn composefs_image_path(&self, commit: &Checksum) -> PathBuf {
        self.path()
            .join(image_store::IMAGE_DIR)
            .join(image_store::rel_path(commit))
    }

    /// Returns `true` if the repository holds a composefs image of `commit`.
    ///
    /// The call opens the image as
    /// [`open_composefs_image_checked`](Repo::open_composefs_image_checked)
    /// does, and reads none of its bytes. It does not read the commit.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a symlink is at a component of the path
    ///   of the image, if a component before the image is not a directory, or
    ///   if the image is not a regular file.
    /// - [`Error::Io`] if the open fails for a reason other than an
    ///   absent file.
    pub async fn has_composefs_image(&self, commit: &Checksum) -> Result<bool> {
        let repo = self.clone();
        let commit = *commit;
        ostrya_rt::unblock(move || Ok(image_store::open_blocking(&repo, &commit)?.is_some())).await
    }

    /// Compares the stored composefs image of `commit` with the key
    /// `ostree.composefs.digest.v0` of the commit.
    ///
    /// The call streams the image through the fs-verity hasher in chunks of
    /// 128 KiB. It does not read the digest of a sealed image from the kernel.
    /// [`ComposefsImageState`] lists the results.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::Core`] if the commit object does not parse.
    /// - [`Error::InvalidFormat`] if the first entry of
    ///   `ostree.composefs.digest.v0` is not a variant of type `ay` with 32
    ///   bytes.
    /// - [`Error::InvalidFormat`] if the commit object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] if a symlink is at a component of the path
    ///   of the image, or if the image is not a regular file.
    /// - [`Error::Io`] if a read of the image or another file system operation
    ///   fails.
    pub async fn check_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageState> {
        let bytes = self.load_object_bytes(ObjectType::Commit, commit).await?;
        let commit_obj = Commit::parse(&bytes)?;
        let Some(expected) = recorded_digest(&commit_obj)? else {
            return Ok(ComposefsImageState::NoKey);
        };
        Ok(match self.stored_image_digest(commit).await? {
            None => ComposefsImageState::Absent,
            Some(actual) if actual == expected => ComposefsImageState::Valid,
            Some(actual) => ComposefsImageState::Mismatch { expected, actual },
        })
    }

    /// Opens the stored composefs image of `commit` and compares its digest
    /// with the key `ostree.composefs.digest.v0` of the commit.
    ///
    /// The call returns the open file and its size in bytes. The file offset
    /// is 0. The call measures the digest through the same descriptor that it
    /// returns, so a caller that reads the image through this file reads the
    /// inode that the call checked.
    ///
    /// The call opens `extensions/ostrya/composefs/<xx>/<rest>.cfs` with one
    /// `openat2` under the root of the repository, with `RESOLVE_BENEATH`,
    /// `RESOLVE_NO_SYMLINKS`, and `O_NONBLOCK`. A symlink at any component of
    /// the path, and an image that is not a regular file, fail the call with
    /// [`Error::InvalidFormat`]. The open has no fallback: an error of
    /// `openat2`, `ENOSYS` included, fails the call. The returned file keeps
    /// `O_NONBLOCK`, which changes no read of a regular file.
    ///
    /// If the image is sealed with fs-verity with SHA-256, 4096-byte blocks,
    /// no salt, and its full size, the call reads the digest from the kernel.
    /// The kernel then refuses each change of the image. Otherwise the call
    /// streams the image through the fs-verity hasher in chunks of 128 KiB. A
    /// process that can write the unsealed file can change it after the call
    /// returns, so the check holds only for the bytes that the call read.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the commit does not carry
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::InvalidFormat`] if the first entry of
    ///   `ostree.composefs.digest.v0` is not a variant of type `ay` with 32
    ///   bytes.
    /// - [`Error::ComposefsImageNotFound`] if the repository holds no image of
    ///   `commit`.
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::ComposefsDigestMismatch`] if the digest of the image is not
    ///   the key.
    /// - [`Error::Core`] if the commit object does not parse.
    /// - [`Error::InvalidFormat`] if the commit object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] if a symlink is at a component of the path
    ///   of the image, or if the image is not a regular file.
    /// - [`Error::Io`] if a read of the image or another file system operation
    ///   fails.
    pub async fn open_composefs_image_checked(
        &self,
        commit: &Checksum,
    ) -> Result<(std::fs::File, u64)> {
        let bytes = self.load_object_bytes(ObjectType::Commit, commit).await?;
        let commit_obj = Commit::parse(&bytes)?;
        let expected = require_recorded_digest(&commit_obj, commit)?;
        let repo = self.clone();
        let commit = *commit;
        ostrya_rt::unblock(move || {
            use std::io::{Seek, SeekFrom};

            let Some(crate::repo_fs::Opened { mut file, stat }) =
                image_store::open_blocking(&repo, &commit)?
            else {
                return Err(Error::ComposefsImageNotFound { commit });
            };
            let len = stat.size;
            let kernel = stat
                .verity
                .then(|| crate::repo_fs::verity_digest(file.as_fd(), len))
                .flatten();
            let actual = match kernel {
                Some(digest) => digest,
                None => {
                    let digest = image_file_digest(&mut file)?;
                    file.seek(SeekFrom::Start(0))?;
                    digest
                }
            };
            if actual != expected {
                return Err(Error::ComposefsDigestMismatch {
                    commit,
                    expected,
                    actual,
                });
            }
            Ok((file, len))
        })
        .await
    }

    /// Returns the fs-verity digest of the stored composefs image of
    /// `commit`, or `None` if the repository holds no image of it.
    ///
    /// The call streams the image on the blocking pool, as
    /// [`stored_image_digest_blocking`] does.
    pub(crate) async fn stored_image_digest(&self, commit: &Checksum) -> Result<Option<[u8; 32]>> {
        let repo = self.clone();
        let commit = *commit;
        ostrya_rt::unblock(move || stored_image_digest_blocking(&repo, &commit)).await
    }
}

/// Returns the fs-verity digest of the stored composefs image of `commit` in
/// `repo`, or `None` if the image is absent.
///
/// The function reads the image in chunks of 128 KiB and feeds each chunk to
/// the fs-verity hasher, so it holds no image-sized buffer.
pub(crate) fn stored_image_digest_blocking(
    repo: &Repo,
    commit: &Checksum,
) -> Result<Option<[u8; 32]>> {
    let Some(mut opened) = image_store::open_blocking(repo, commit)? else {
        return Ok(None);
    };
    Ok(Some(image_file_digest(&mut opened.file)?))
}

/// Returns the fs-verity digest of the bytes of `file` from its current
/// offset to its end.
///
/// The function reads the file in chunks of 128 KiB and feeds each chunk to
/// the fs-verity hasher, so it holds no image-sized buffer.
pub(crate) fn image_file_digest(file: &mut std::fs::File) -> std::io::Result<[u8; 32]> {
    use std::io::Read;

    let mut hasher = FsVerityHasher::new();
    let mut buf = vec![0u8; DIGEST_CHUNK];
    loop {
        match file.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => hasher.update(&buf[..n]),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(hasher.finalize())
}

/// Returns the digest that `commit` records under
/// `ostree.composefs.digest.v0`, or `None` if the commit does not carry the
/// key.
///
/// The value is the first entry of the key. It must be a variant of type `ay`
/// with 32 bytes, or the call fails with [`Error::InvalidFormat`].
pub(crate) fn recorded_digest(commit: &Commit) -> Result<Option<[u8; 32]>> {
    let Some(entry) = commit.metadata.dict_get(COMPOSEFS_DIGEST_KEY) else {
        return Ok(None);
    };
    entry_digest(entry).map(Some)
}

/// Returns the digest that the metadata `entries` record under
/// `ostree.composefs.digest.v0`, or `None` if no entry has the key.
///
/// Each entry is a key and the bytes of a `v`, as the client of a server
/// commit sends them. The value is the first entry of the key, which is the
/// entry that [`recorded_digest`] reads from a commit with these entries. It
/// must be a variant of type `ay` with 32 bytes, or the call fails with
/// [`Error::InvalidFormat`].
#[cfg(feature = "receive")]
pub(crate) fn entries_digest(entries: &[(String, Vec<u8>)]) -> Result<Option<[u8; 32]>> {
    let Some((_, bytes)) = entries.iter().find(|(key, _)| key == COMPOSEFS_DIGEST_KEY) else {
        return Ok(None);
    };
    let entry = ostrya_core::from_bytes(&Type::Variant, bytes).map_err(ostrya_core::Error::from)?;
    entry_digest(&entry).map(Some)
}

/// Returns the digest that `entry`, the value of an entry under
/// `ostree.composefs.digest.v0`, holds: a variant of type `ay` with 32 bytes.
/// Each other value fails with [`Error::InvalidFormat`].
fn entry_digest(entry: &Value) -> Result<[u8; 32]> {
    entry
        .as_variant()
        .filter(|(ty, _)| ty.signature() == DIGEST_SIGNATURE)
        .and_then(|(_, value)| value.as_bytes())
        .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
        .ok_or_else(|| {
            Error::InvalidFormat(format!(
                "the value of {COMPOSEFS_DIGEST_KEY} is not a variant of type \
                 {DIGEST_SIGNATURE} with 32 bytes"
            ))
        })
}

/// Returns the digest that `commit_obj` records, as [`recorded_digest`] does.
/// A commit without the key is refused with [`Error::InvalidInput`].
fn require_recorded_digest(commit_obj: &Commit, commit: &Checksum) -> Result<[u8; 32]> {
    recorded_digest(commit_obj)?.ok_or_else(|| {
        Error::InvalidInput(format!(
            "commit {commit} does not carry {COMPOSEFS_DIGEST_KEY}, so it has no composefs image"
        ))
    })
}

/// Refuses `image` with [`Error::ComposefsDigestMismatch`] if its digest is
/// not `key`, the digest that `commit` records.
fn check_image_digest(
    commit: &Checksum,
    key: &[u8; 32],
    image: &StagedComposefsImage<'_>,
) -> Result<()> {
    if image.digest != *key {
        return Err(Error::ComposefsDigestMismatch {
            commit: *commit,
            expected: *key,
            actual: image.digest,
        });
    }
    Ok(())
}

/// Returns the lowercase hex form of a 32-byte digest.
pub(crate) fn digest_hex(digest: &[u8; 32]) -> String {
    use std::fmt::Write;

    digest
        .iter()
        .fold(String::with_capacity(64), |mut out, byte| {
            let _ = write!(out, "{byte:02x}");
            out
        })
}

/// Builds the composefs tree model of `root` from the objects in `source`.
/// The model holds the metadata and the backing redirect of each file, and no
/// file content, so the shape of the tree bounds its size. The walk takes the
/// fs-verity digest of each object with no seal from `cache` if it holds one.
async fn composefs_model(
    source: ObjectSource<'_>,
    root: &RepoTree,
    digests: Digests,
    cache: &mut VerityCache,
) -> Result<Directory> {
    let mut dir = build_directory(
        source,
        *root.dirtree_checksum(),
        *root.dirmeta_checksum(),
        digests,
        cache,
    )
    .await?;
    inject_top_level_dirs(&mut dir);
    Ok(dir)
}

/// Serializes `dir` through `fd` and returns the fs-verity digest of the
/// image. A buffer wraps the descriptor, because the writer emits the image in
/// many small writes.
fn write_image_to_fd(dir: &Directory, fd: OwnedFd) -> std::result::Result<[u8; 32], WriterError> {
    let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
    write_image_to(dir, &mut out)
}

/// Returns the fs-verity digest of the image of `dir`, for a caller that needs
/// the digest alone. The image goes to [`std::io::sink`], so the call never
/// holds it.
async fn image_digest(dir: Directory) -> Result<[u8; 32]> {
    ostrya_rt::unblock(move || write_image_to(&dir, &mut std::io::sink()))
        .await
        .map_err(writer_error)
}

/// Returns the library error for an error of the writer. The writer holds the
/// bounds that the image format states. The tree reaches these bounds, so a
/// refusal of the writer is a refusal of the tree.
pub(crate) fn writer_error(err: WriterError) -> Error {
    match err {
        WriterError::Unsupported(msg) => Error::Unsupported(msg),
        WriterError::Io(err) => Error::Io(err),
    }
}

/// Builds the composefs [`Directory`] model of one directory of a committed
/// tree, and recurses into its subdirectories. The future is boxed because the
/// recursion is async.
fn build_directory<'a>(
    source: ObjectSource<'a>,
    dirtree: Checksum,
    dirmeta: Checksum,
    digests: Digests,
    cache: &'a mut VerityCache,
) -> TreeFuture<'a> {
    Box::pin(async move {
        let meta = source.dirmeta(&dirmeta).await?;
        let mut dir = Directory::new(dirmeta_to_metadata(&meta)?);
        let tree = source.dirtree(&dirtree).await?;
        for (name, checksum) in tree.files {
            let node = file_node(source, &checksum, digests, &mut *cache).await?;
            dir.children.insert(name.into_bytes(), node);
        }
        for (name, subtree, submeta) in tree.dirs {
            let sub = build_directory(source, subtree, submeta, digests, &mut *cache).await?;
            dir.children.insert(name.into_bytes(), Node::Directory(sub));
        }
        Ok(dir)
    })
}

/// Builds the composefs [`Node`] of a file object.
///
/// - A symlink stores its target inline.
/// - An empty regular file has no backing.
/// - A regular file with content redirects to its `.file` loose path. Under
///   [`Digests::Computed`] and [`Digests::Sealed`], it carries the fs-verity
///   digest of its content.
///
/// The call reads the file object in each mode, because the metadata of the
/// inode comes from it. Under [`Digests::Computed`], it takes the digest of an
/// object with no seal from `cache` if it holds one.
async fn file_node(
    source: ObjectSource<'_>,
    checksum: &Checksum,
    digests: Digests,
    cache: &mut VerityCache,
) -> Result<Node> {
    let file = source.file(checksum, digests != Digests::Disabled).await?;
    let meta = file_to_metadata(&file)?;
    match &file.kind {
        FileKind::Symlink { target } => Ok(Node::Symlink(Symlink {
            meta,
            target: target.clone().into_bytes(),
        })),
        FileKind::Regular { size } => {
            let content = if *size == 0 {
                Content::Empty
            } else {
                let digest = match digests {
                    Digests::Computed => Some(content_fs_verity(&file, cache).await?),
                    Digests::Sealed => Some(file.kernel_fs_verity().ok_or_else(|| {
                        Error::Unsupported(format!(
                            "the file object {checksum} has no fs-verity seal with SHA-256, \
                             4096-byte blocks, and no salt"
                        ))
                    })?),
                    Digests::Disabled => None,
                };
                Content::Backed {
                    size: *size,
                    redirect: format!("/{}", loose_path(checksum, ObjectType::File, BACKING_MODE)),
                    verity: digest,
                }
            };
            Ok(Node::Regular(Regular { meta, content }))
        }
    }
}

/// Returns the fs-verity digest of the content of a regular file.
///
/// If the object file is a sealed raw payload, the value is the digest that
/// the kernel gave at load. The call then reads no payload byte, and it does
/// not put the digest in `cache`. The seal must name SHA-256, 4096-byte
/// blocks, no salt, and the payload size.
///
/// In all other cases, the call looks for the checksum of the file object in
/// `cache`, and gives the digest that the cache holds. If the cache holds no
/// digest of the object, the call streams the payload of the object through
/// the hasher in bounded chunks, and puts the digest in `cache`. The checksum
/// of the file object covers the content, so it is a key of the digest. The
/// digest covers the content, so a repository that stores the object
/// compressed gives the same value as one that stores it raw.
async fn content_fs_verity(file: &FileObject, cache: &mut VerityCache) -> Result<[u8; 32]> {
    use futures_lite::AsyncReadExt;

    if let Some(digest) = file.kernel_fs_verity() {
        return Ok(digest);
    }
    if let Some(digest) = cache.digests.get(file.checksum()) {
        return Ok(*digest);
    }
    let mut reader = file.reader().await?;
    let mut hasher = FsVerityHasher::new();
    let mut buf = vec![0u8; DIGEST_CHUNK];
    loop {
        let n = reader.read(&mut buf).await.map_err(Error::Io)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    let digest = hasher.finalize();
    cache.digests.insert(*file.checksum(), digest);
    #[cfg(test)]
    {
        cache.hashed += 1;
    }
    Ok(digest)
}

/// Inserts the five top-level directories that the `ostree` command adds. If
/// the root of the commit already holds one of these names, its entry stays.
fn inject_top_level_dirs(root: &mut Directory) {
    for name in INJECTED_DIRS {
        let key = name.as_bytes().to_vec();
        root.children.entry(key).or_insert_with(|| {
            Node::Directory(Directory::new(Metadata {
                mode: INJECTED_DIR_MODE,
                uid: 0,
                gid: 0,
                mtime: (0, 0),
                xattrs: Vec::new(),
            }))
        });
    }
}

/// Returns the composefs [`Metadata`] of a directory. The `ostree` command
/// sets the mtime of each exported inode to 0.
fn dirmeta_to_metadata(dirmeta: &DirMeta) -> Result<Metadata> {
    Ok(Metadata {
        mode: dirmeta.mode,
        uid: dirmeta.uid,
        gid: dirmeta.gid,
        mtime: (0, 0),
        xattrs: xattrs_to_model(&dirmeta.xattrs)?,
    })
}

/// Returns the composefs [`Metadata`] of a file object. The `ostree` command
/// sets the mtime of each exported inode to 0.
fn file_to_metadata(file: &FileObject) -> Result<Metadata> {
    Ok(Metadata {
        mode: file.mode,
        uid: file.uid,
        gid: file.gid,
        mtime: (0, 0),
        xattrs: xattrs_to_model(&file.xattrs)?,
    })
}

/// Converts an [`Xattrs`] set to the `(name, value)` pairs of the writer. A
/// stored name ends in a NUL byte. The writer indexes raw names, so the call
/// drops the NUL.
///
/// Each attribute spends its name, its value, and [`XATTR_ENTRY_COST`] bytes
/// from the budget of [`MAX_XATTR_TOTAL`] bytes of the inode. The call refuses
/// an inode that spends more. It holds each name to [`MAX_XATTR_NAME`] bytes,
/// the one EROFS length field that the budget does not bind. The bytes of the
/// tree enter the image model here, so the refusals are here.
fn xattrs_to_model(xattrs: &Xattrs) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
    let mut spent = 0usize;
    xattrs
        .iter()
        .map(|(name, value)| {
            let name = name.strip_suffix(&[0]).unwrap_or(name).to_vec();
            if name.len() > MAX_XATTR_NAME {
                return Err(Error::Unsupported(format!(
                    "xattr {} is {} bytes long, above the {MAX_XATTR_NAME} \
                     bytes a composefs image states a name in",
                    String::from_utf8_lossy(&name),
                    name.len(),
                )));
            }
            spent += XATTR_ENTRY_COST + name.len() + value.len();
            if spent > MAX_XATTR_TOTAL {
                return Err(Error::Unsupported(format!(
                    "xattr {} takes the inode to {spent} bytes of extended \
                     attributes, above the {MAX_XATTR_TOTAL} bytes a composefs \
                     image holds",
                    String::from_utf8_lossy(&name),
                )));
            }
            Ok((name, value.to_vec()))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use std::os::fd::AsFd;
    use std::os::unix::fs::PermissionsExt;
    use std::path::{Path, PathBuf};

    use ostrya_core::{Checksum, RepoMode, Type, Value};
    use ostrya_rt::block_on;

    use super::{COMPOSEFS_DIGEST_KEY, ComposefsImageState, VerityCache};
    use crate::{CommitOptions, CreateOptions, MutableTree, Repo, Transaction};

    /// A scratch directory that the drop removes.
    struct Scratch {
        path: PathBuf,
    }

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            let path = std::env::temp_dir().join(format!(
                "ostrya-composefs-{tag}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            Scratch { path }
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    /// Writes the regular file `name` under `dir` with `bytes` and the mode
    /// 0644.
    fn write_file(dir: &Path, name: &str, bytes: &[u8]) {
        let path = dir.join(name);
        std::fs::write(&path, bytes).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    /// Walks `base/src` into `txn`, and writes a commit of the tree at
    /// `timestamp` with the composefs digest key of the tree.
    async fn keyed_commit(txn: &Transaction, base: &Path, timestamp: u64) -> Checksum {
        let mut mtree = MutableTree::new();
        let dfd = std::fs::File::open(base).unwrap();
        txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("src"), &mut mtree, None)
            .await
            .unwrap();
        let root = txn.write_mtree(&mut mtree).await.unwrap();
        let digest = txn.composefs_digest(&root).await.unwrap();
        let metadata = Value::Array(vec![Value::Tuple(vec![
            Value::Str(COMPOSEFS_DIGEST_KEY.to_owned()),
            Value::variant(Type::parse("ay").unwrap(), Value::Bytes(digest.to_vec())),
        ])]);
        txn.write_commit(
            CommitOptions {
                timestamp: Some(timestamp),
                metadata: Some(metadata),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap()
    }

    /// One build pass of the recorded images reads and hashes each object
    /// with no seal one time. Two paths of one tree name one object, and a
    /// second commit shares objects with the first. An empty file has no
    /// backing, so the pass hashes no empty object.
    #[test]
    fn one_build_pass_hashes_each_unsealed_object_one_time() {
        let scratch = Scratch::new("verity-cache");
        let root = scratch.path.join("repo");
        block_on(async {
            drop(
                Repo::create(&root, CreateOptions::new(RepoMode::BareUser))
                    .await
                    .unwrap(),
            );
            let cfg = root.join("config");
            let mut text = std::fs::read_to_string(&cfg).unwrap();
            text.push_str("[ex-integrity]\nfsverity=no\n[ex-ostrya]\ngenerate-composefs=true\n");
            std::fs::write(&cfg, text).unwrap();
            let repo = Repo::open(&root).await.unwrap();

            let big: Vec<u8> = (0..9000).map(|i| i as u8).collect();
            let first = scratch.path.join("first");
            let src = first.join("src");
            std::fs::create_dir_all(&src).unwrap();
            write_file(&src, "a", b"shared bytes\n");
            write_file(&src, "b", b"shared bytes\n");
            write_file(&src, "big", &big);
            write_file(&src, "empty", b"");
            let second = scratch.path.join("second");
            let src = second.join("src");
            std::fs::create_dir_all(&src).unwrap();
            write_file(&src, "a", b"shared bytes\n");
            write_file(&src, "new", b"new bytes\n");
            write_file(&src, "empty", b"");

            let txn = repo.transaction().await.unwrap();
            let one = keyed_commit(&txn, &first, 1).await;
            let two = keyed_commit(&txn, &second, 2).await;
            let mut cache = VerityCache::default();
            if let Err(e) = txn.build_recorded_with(&mut cache).await {
                panic!("{}", crate::Error::from(e));
            }
            assert_eq!(cache.hashed, 3);
            txn.commit().await.unwrap();
            for commit in [one, two] {
                assert_eq!(
                    repo.check_composefs_image(&commit).await.unwrap(),
                    ComposefsImageState::Valid
                );
            }
        });
    }
}