ostrya 0.15.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
//! The update guard: an exclusive hold on the writes of refs and `config`.
//!
//! [`Repo::begin_update`] takes the update lock on `<repo>/.update.lock` and
//! returns an [`UpdateGuard`]. The guard writes refs, ref aliases, and
//! `config`, and edits the remotes of `config` and of the remotes directory.
//! [`UpdateGuard::finish`] syncs the changed directories and releases the
//! guard.

use std::collections::BTreeSet;
use std::os::fd::AsFd;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};

use ostrya_core::{Checksum, KeyFile, Ref};
use rustix::io::Errno;

use crate::config::{
    RemoteSource, RepoConfig, remote_group, remote_group_name, remote_keyring_name,
    valid_remote_name,
};
use crate::error::{Error, Result};
use crate::lock::UpdateLocks;
use crate::refs::{
    put_alias_blocking, put_ref_blocking, ref_relpath, remove_alias_blocking, sync_dirs_all,
};
use crate::remotes_dir::{self, DirWriter};
use crate::repo::{RemotesDir, Repo, check_config_size, read_config};
use crate::repo_fs::{FsError, Publish, RepoDir, RootFile};

/// The directory that holds `config`: the repository root.
const ROOT_DIR: &str = ".";

/// A group name that a key file accepts. `check_key` sets a key in this group
/// to check the key name alone.
const KEY_CHECK_GROUP: &str = "remote";

/// An exclusive hold on the writes of refs and `config` of one repository.
///
/// [`Repo::begin_update`] returns the guard. The guard holds the repository
/// lock shared and the update lock. The update lock is exclusive across
/// processes and inside the process.
///
/// The guard is a value: a caller holds it, passes it, and stores it. It is
/// `Send + Sync`.
///
/// The guard reads and writes refs, collection refs, and ref aliases. It
/// reads and writes `config` and the `.conf` files of the remotes directory.
/// It stages no object. Each write of the guard is atomic and visible when
/// the call returns.
///
/// # Remotes
///
/// The guard edits the remotes of `config` and of the `.conf` files of the
/// remotes directory, [`Repo::remotes_dir`], as a read-modify-write of the
/// files on disk:
///
/// - [`add_remote`](UpdateGuard::add_remote)
/// - [`set_remote_key`](UpdateGuard::set_remote_key)
/// - [`unset_remote_key`](UpdateGuard::unset_remote_key)
/// - [`replace_remote`](UpdateGuard::replace_remote)
/// - [`delete_remote`](UpdateGuard::delete_remote), which also removes the
///   repository keyring of the remote
///
/// An add writes a new remote into the remotes directory if the handle has
/// one and `[core] add-remotes-config-dir` of `config` is not `false`. Else
/// it writes into `config`. Each other call edits the file that holds the
/// remote, so a remote stays in its file.
///
/// Each of these calls reads `config` and the remotes directory again, and
/// [`write_config`](UpdateGuard::write_config) reads the remotes directory
/// again. A `.conf` file that an open refuses, and that comes into the
/// directory after the open, makes each of these calls fail.
///
/// A write of a `.conf` file is atomic: the guard writes a temp file
/// `.ostrya-tmp-<pid>-XXXXXX` in the directory, whose name does not end in
/// `.conf`, and renames it over the file. With `[core] fsync` on, the write
/// syncs the file and the directory with `fsync` before the call returns. A
/// rewrite of a regular file keeps its permission bits, and does not keep
/// its owner. A rewrite of a `.conf` file that is a symlink replaces the link
/// with a regular file at the mode of a new file, and does not write through
/// the link: the target keeps its content.
///
/// The update lock is the lock of one repository. Two repositories that
/// share one remotes directory do not exclude each other. Each write changes
/// one entry of the directory, so a race of the two loses at most the edit
/// of one file.
///
/// These calls and [`write_config`](UpdateGuard::write_config) run one at a
/// time on one guard.
///
/// # Writers that wait for the guard
///
/// A holder of the guard must write refs and `config` through the guard.
/// These writers wait for the guard:
///
/// - [`Transaction::commit`](crate::Transaction::commit) of a transaction
///   that writes a ref or detached metadata, at the step that writes them. A
///   pull and the transaction commit of a receive session wait at this step.
/// - [`Repo::set_ref_immediate`], [`Repo::set_ref_alias_immediate`], and
///   [`Repo::remove_ref_alias_immediate`].
/// - [`Repo::write_config`], [`Repo::remove_remote_keyring`], and, under the
///   `verify-gpg` feature, `Repo::gpg_import_keys`.
/// - [`Repo::regenerate_summary`], [`Repo::regenerate_summaries`],
///   [`Repo::sign_summary`], [`Repo::sign_summary_all`], and the `summary`
///   and `summary.sig` writes of a mirror pull.
/// - [`Repo::write_commit_detached_metadata`],
///   [`Repo::add_supplement`], [`Repo::sign_commit`], and
///   [`Repo::delete_signatures`].
///
/// If `[core] locking` is on, [`Repo::prune`] also waits for the guard,
/// because the guard holds the repository lock shared.
///
/// # A holder that waits for its own guard
///
/// No call detects a holder that waits for its own guard. This wait occurs
/// if a task that holds the guard calls one of the writers that wait for the
/// guard. It also occurs if that task waits for another task that calls one
/// of these writers.
///
/// In both cases the wait lasts until `[core] lock-timeout-secs` passes. The
/// writer then fails with [`Error::LockTimeout`]. If `lock-timeout-secs` is
/// `-1`, the task waits forever.
///
/// # Release
///
/// [`finish`](UpdateGuard::finish) releases the guard. A guard that drops
/// without `finish` runs the directory syncs of `finish` synchronously, on
/// the thread that drops the last reference to its state. It hides every
/// error and then releases both locks.
///
/// That thread is the thread that drops the guard, or the blocking-pool
/// thread of a write that still runs. The syncs block that thread, so an
/// async caller releases the guard with `finish`.
#[derive(Debug)]
pub struct UpdateGuard {
    held: Arc<Held>,
}

/// The state of a guard that a write in flight shares: both locks, the
/// writes in flight, and the directories to sync. The last reference to drop
/// runs the syncs that are still recorded and then releases the locks.
#[derive(Debug)]
struct Held {
    /// The repository handle that the blocking closures use.
    repo: Repo,
    /// `[core] fsync`, read once when the guard is taken.
    fsync: bool,
    /// The writes in flight and the directories to sync.
    state: Mutex<Writes>,
    /// Held for the whole of each edit and each write of `config`, so the
    /// read-modify-writes of one guard do not interleave.
    config: Mutex<()>,
    /// Signaled when the last write in flight ends.
    idle: Condvar,
    /// Both locks, until [`finish`](UpdateGuard::finish) releases them.
    /// Declared last, so a guard that drops without `finish` releases the
    /// locks after the syncs of the drop ran.
    locks: Mutex<Option<UpdateLocks>>,
}

/// The writes of a guard.
#[derive(Debug, Default)]
struct Writes {
    /// The number of write closures that exist and have not ended.
    in_flight: usize,
    /// Each directory, relative to the repository root, that a write changed
    /// and that no sync has run on yet.
    dirs: BTreeSet<String>,
}

impl Held {
    fn writes(&self) -> MutexGuard<'_, Writes> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Waits until no write is in flight, syncs each recorded directory, and
    /// releases both locks. Blocks the calling thread.
    fn finish_blocking(&self) -> Result<()> {
        let mut writes = self.writes();
        while writes.in_flight > 0 {
            writes = self
                .idle
                .wait(writes)
                .unwrap_or_else(PoisonError::into_inner);
        }
        let dirs = std::mem::take(&mut writes.dirs);
        drop(writes);
        let synced = sync_dirs_all(self.repo.root_dir(), dirs.into_iter().collect());
        self.release();
        synced
    }

    /// Releases both locks.
    fn release(&self) {
        let locks = self
            .locks
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        drop(locks);
    }
}

impl Drop for Held {
    fn drop(&mut self) {
        let writes = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
        let dirs = std::mem::take(&mut writes.dirs);
        let _ = sync_dirs_all(self.repo.root_dir(), dirs.into_iter().collect());
    }
}

/// One write closure of a guard, counted in flight from its creation to its
/// drop. The closure owns it, so the count falls when the closure ends, when
/// it panics, and when the pool drops it unrun.
struct InFlight {
    held: Arc<Held>,
}

impl InFlight {
    fn start(held: &Arc<Held>) -> InFlight {
        held.writes().in_flight += 1;
        InFlight { held: held.clone() }
    }
}

impl Drop for InFlight {
    fn drop(&mut self) {
        let mut writes = self.held.writes();
        writes.in_flight -= 1;
        if writes.in_flight == 0 {
            self.held.idle.notify_all();
        }
    }
}

/// Methods that hold the update lock.
impl Repo {
    /// Takes the repository lock shared and the update lock, and returns the
    /// guard.
    ///
    /// The returned [`UpdateGuard`] holds both locks until
    /// [`finish`](UpdateGuard::finish) or its drop releases them.
    ///
    /// # Lock order
    ///
    /// The call takes the repository lock first. A transaction also holds it
    /// shared, so a pull does not make this step wait. If `[core] locking` is
    /// on, the call waits for a [`Repo::prune`] and for each other holder of
    /// the repository lock in
    /// [`LockKind::Exclusive`](crate::LockKind::Exclusive).
    ///
    /// If `[core] locking` is `false`, the call does not take the repository
    /// lock. It always takes the update lock.
    ///
    /// # Update lock
    ///
    /// The update lock is exclusive across processes and inside the process.
    /// The waiters of one process take it in the order of the first poll of
    /// their wait for the update lock. A release always drops the record lock,
    /// so another process can take the lock between two holders of this
    /// process.
    ///
    /// The `ostree` command never opens `.update.lock`, so the update lock
    /// excludes ostrya processes alone.
    ///
    /// The lock file opens by the rules of `.lock`
    /// ([`LockKind`](crate::LockKind), "Lock file"). The open follows no
    /// symlink, and refuses an entry that is not a regular file.
    ///
    /// # Waits
    ///
    /// Each of the two waits gets the whole of `[core] lock-timeout-secs`. If
    /// `lock-timeout-secs` is `-1`, a wait has no limit. If it is `0`, a wait
    /// makes one attempt. This crate has no variant of this call that fails at
    /// once.
    ///
    /// The call reads `[core] fsync`, `[core] locking`, and `[core]
    /// lock-timeout-secs` before it waits. It reads them from the config that
    /// the handle read at open. The guard keeps these values, and a
    /// [`write_config`](UpdateGuard::write_config) through the guard does not
    /// change them.
    ///
    /// # While a caller holds the guard
    ///
    /// A caller can hold the guard for minutes. While it holds the guard:
    ///
    /// - Each other writer that [`UpdateGuard`] lists waits for the guard. If
    ///   the wait passes `lock-timeout-secs`, the writer fails with
    ///   [`Error::LockTimeout`]. A pull then fails at the step of its commit
    ///   that writes detached metadata and refs. A push then fails at `Commit`
    ///   with `internal`.
    /// - If `[core] locking` is on, a prune waits for the whole hold.
    /// - A transaction opens, stages, and publishes its objects in parallel
    ///   with the hold. It waits only at the step that writes detached
    ///   metadata and refs. A transaction that writes neither commits in
    ///   parallel with the hold.
    ///
    /// A holder must write through the guard. [`UpdateGuard`] states the
    /// result if a holder waits for its own guard.
    ///
    /// # Errors
    ///
    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` is not a
    ///   boolean, or if `[core] lock-timeout-secs` is not an integer.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
    ///   `-1`.
    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
    ///   lock-timeout-secs`.
    /// - [`Error::InvalidFormat`] if a symlink or an entry that is not a
    ///   regular file is at `.lock` or at `.update.lock`. 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 open of a lock file or a lock request fails.
    pub async fn begin_update(&self) -> Result<UpdateGuard> {
        let fsync = self.config().fsync()?;
        let locks = self.lock_for_update().await?;
        Ok(UpdateGuard {
            held: Arc::new(Held {
                repo: self.clone(),
                fsync,
                state: Mutex::new(Writes::default()),
                config: Mutex::new(()),
                idle: Condvar::new(),
                locks: Mutex::new(Some(locks)),
            }),
        })
    }
}

impl UpdateGuard {
    fn repo(&self) -> &Repo {
        &self.held.repo
    }

    /// Returns the commit that a ref names in the ref store.
    ///
    /// The call reads the ref as [`Repo::resolve_ref_tip`] reads it. For a
    /// collection ref of the `[core] collection-id` of the repository, the
    /// call reads `refs/heads/NAME`, and it does not read
    /// `refs/mirrors/ID/`. If the store holds the ref as an alias, the call
    /// reads the ref that the alias names, by the alias rule of
    /// [`Repo::resolve_ref_tip`]. A ref path that passes through a file holds
    /// no ref. The result is `None` if the store holds no such ref.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRefspec`] if the ref fails [`Ref::validate`]. The
    ///   call reads no file.
    /// - [`Error::NotARef`] if the ref path names a directory, a FIFO, a
    ///   socket, or a device file, or an alias that breaks the alias rule.
    /// - [`Error::InvalidFormat`] if the ref file is not UTF-8 or is larger
    ///   than 4096 bytes, or if a component of the ref path is a symlink.
    /// - [`Error::Core`] if the ref file holds no checksum.
    /// - [`Error::Io`] if the read fails, for example on a ref file that the
    ///   process cannot read.
    pub async fn read_ref(&self, r: &Ref) -> Result<Option<Checksum>> {
        self.repo().resolve_ref_tip(r).await
    }

    /// Writes one ref atomically, as [`Repo::set_ref_immediate`] writes it.
    ///
    /// The ref gives the path that [`Repo::set_ref_immediate`] writes:
    /// `refs/heads/NAME` for a collection ref of the `[core] collection-id`
    /// of the repository. If `checksum` is `None`, the call removes the ref
    /// file. The ref is visible when the call returns. The sync of each
    /// directory that changed waits for [`finish`](UpdateGuard::finish).
    ///
    /// The id is the `[core] collection-id` that the open of the handle read.
    /// After [`write_config`](UpdateGuard::write_config) sets a new id `NEW`,
    /// the call writes `@NEW:NAME` to `refs/mirrors/NEW/NAME` until a new
    /// open. The ref resolve, the collection ref listings, and the summary of
    /// a new open ignore that file.
    ///
    /// The call does not write or remove an alias. To remove an alias, use
    /// [`remove_ref_alias`](UpdateGuard::remove_ref_alias).
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRefspec`] if the ref fails [`Ref::validate`]. The
    ///   call writes nothing.
    /// - [`Error::RefNotWritable`] if the path of the ref names an alias. The
    ///   call writes nothing, and the alias stays. The call gives the same
    ///   error, with the reason `passes through an alias`, if `refs` or a
    ///   component above the ref is a symlink, also a dangling one. It then
    ///   writes nothing through the symlink.
    /// - [`Error::InvalidFormat`] if a file is at a directory component of
    ///   the path, if a symlink is at `tmp`, or if a writer puts a symlink at
    ///   a component of the path after the check of the path. The call then
    ///   writes nothing through the symlink.
    /// - [`Error::Io`] if a file system operation fails.
    ///
    /// If a directory of `refs/mirrors/` has a name that fails the rule, a
    /// ref under it cannot be written or removed through this call. Remove
    /// such a ref by hand.
    pub async fn set_ref(&self, r: &Ref, checksum: Option<&Checksum>) -> Result<()> {
        let own = self.repo().config().collection_id();
        let relpath = ref_relpath(own, r)?;
        let name = r.clone().canonical(own).to_string();
        self.set_relpath(name, relpath, checksum).await
    }

    /// Writes `alias` as an alias of `target`, as
    /// [`Repo::set_ref_alias_immediate`] writes it.
    ///
    /// The alias is a relative symlink. It replaces the entry that `alias`
    /// named before. The call checks both refs, and the two refs do not have
    /// to exist. An alias whose target is an alias is refused, as
    /// [`Repo::set_ref_alias_immediate`] states.
    ///
    /// Each ref gives its path as [`set_ref`](UpdateGuard::set_ref) states:
    /// `refs/heads/NAME` for a collection ref of the `[core] collection-id`,
    /// and `refs/mirrors/ID/NAME` for a collection ref of each other id. The
    /// id is the one that the open of the handle read, also after
    /// [`write_config`](UpdateGuard::write_config) sets a new id. An error
    /// names a ref by the text of its canonical form, as [`Ref::canonical`]
    /// gives it.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRefspec`] if `alias` or `target` fails
    ///   [`Ref::validate`]. The call checks `alias` first.
    /// - [`Error::RefNotWritable`] if `refs` or a component above the path
    ///   of `alias` is a symlink, also a dangling one. The reason is
    ///   `passes through an alias`, and the call writes nothing.
    /// - [`Error::RefNotWritable`] for `alias` if `target` names an alias
    ///   or the path of `alias` itself (reason `targets an alias`), or if
    ///   `refs` or a component above the path of `target` is a symlink
    ///   (reason `passes through an alias`). The call writes nothing.
    /// - [`Error::InvalidFormat`] if a file is at a directory component of
    ///   the path, if a symlink is at `tmp`, or if a writer puts a symlink at
    ///   a component of the path after the check of the path. The call then
    ///   writes nothing through the symlink.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn set_ref_alias(&self, alias: &Ref, target: &Ref) -> Result<()> {
        let own = self.repo().config().collection_id();
        let relpath = ref_relpath(own, alias)?;
        let target = ref_relpath(own, target)?;
        let name = alias.clone().canonical(own).to_string();
        self.write(move |root, fsync, dirs| {
            put_alias_blocking(root, &name, &relpath, &target, fsync, dirs)
        })
        .await
    }

    /// Removes the alias `alias`, as [`Repo::remove_ref_alias_immediate`]
    /// removes it.
    ///
    /// The ref gives the path as [`set_ref_alias`](UpdateGuard::set_ref_alias)
    /// states. The ref that the alias names stays. The removal of an absent
    /// path is not an error. The sync of the directory that held the link
    /// waits for [`finish`](UpdateGuard::finish).
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidRefspec`] if `alias` fails [`Ref::validate`].
    /// - [`Error::RefNotWritable`] if the path of `alias` names a ref file,
    ///   names a directory, passes through a file or an alias, or names a
    ///   special file. The call removes nothing.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn remove_ref_alias(&self, alias: &Ref) -> Result<()> {
        let own = self.repo().config().collection_id();
        let relpath = ref_relpath(own, alias)?;
        let name = alias.clone().canonical(own).to_string();
        self.write(move |root, fsync, dirs| {
            remove_alias_blocking(root, &name, &relpath, fsync, dirs)
        })
        .await
    }

    /// Reads the `config` file and the `.conf` files of the remotes directory
    /// of the handle from disk and parses them.
    ///
    /// The repository handle keeps the config that it read at open. A
    /// read-modify-write of `config` under the guard reads the file with this
    /// call. The call reads the directory of
    /// [`Repo::remotes_dir`](crate::Repo::remotes_dir), and does not read the
    /// key `[ex-ostrya] remotes-config-dir` again.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] of kind `NotFound` if `config` does not exist.
    /// - [`Error::InvalidFormat`] if `config` is a symlink, is not a regular
    ///   file, is larger than 1 MiB (1048576 bytes), or is not UTF-8.
    /// - An error of [`RepoConfig::parse`] if `config` does not parse.
    /// - [`Error::Io`] if the read fails.
    /// - The errors of [`OpenOptions::open`](crate::OpenOptions::open) for the
    ///   remotes directory and its `.conf` files.
    pub async fn read_config(&self) -> Result<RepoConfig> {
        self.repo().read_config_and_remotes().await
    }

    /// Reads the `config` file from disk and parses it, as
    /// [`read_config`](UpdateGuard::read_config) does. The call does not read
    /// the remotes directory, so the config has no remotes of the directory.
    ///
    /// The function is not a stable API.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] of kind `NotFound` if `config` does not exist.
    /// - [`Error::InvalidFormat`] if `config` is a symlink, is not a regular
    ///   file, is larger than 1 MiB (1048576 bytes), or is not UTF-8.
    /// - An error of [`RepoConfig::parse`] if `config` does not parse.
    /// - [`Error::Io`] if the read fails.
    #[doc(hidden)]
    pub async fn read_config_file(&self) -> Result<RepoConfig> {
        self.repo().read_config_file().await
    }

    /// Replaces `config` with the document that `keyfile` holds.
    ///
    /// The call writes the file as [`Repo::write_config`] writes it. The new
    /// file is visible when the call returns. The sync of the repository
    /// directory waits for [`finish`](UpdateGuard::finish).
    ///
    /// The call writes the document as given. The repository handle and the
    /// guard keep the values that they read before. A new open of the
    /// repository reads the new values. This also applies to `[core]
    /// collection-id`, as [`set_ref`](UpdateGuard::set_ref) states. The write
    /// does not interleave with a remote call of the same guard.
    ///
    /// The call refuses a document with a `[remote "NAME"]` group when a
    /// `.conf` file of the remotes directory defines `NAME`, as
    /// [`Repo::write_config`] does. It reads the directory again for this
    /// check.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the document is larger than 1 MiB, the
    ///   size that an open accepts. The call then writes nothing.
    /// - [`Error::RemoteExists`] if the document has a group of a remote of
    ///   the remotes directory. The call then writes nothing.
    /// - The errors of [`OpenOptions::open`](crate::OpenOptions::open) for the
    ///   remotes directory and its `.conf` files.
    /// - [`Error::InvalidFormat`] if `tmp` or `tmp/cache` is a symlink or is
    ///   not a directory. The write of `config` makes its temp file in
    ///   `tmp/`.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
        let bytes = config_bytes(keyfile)?;
        let names = remotes_dir::config_remote_names(keyfile);
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            remotes_dir::check_config_remotes(root.as_fd(), dir.as_ref(), &names)?;
            put_config_blocking(root, &bytes, fsync, dirs)
        })
        .await
    }

    /// Adds the remote `name`, with the keys of `keys` in order.
    ///
    /// If the handle has a remotes directory and `[core]
    /// add-remotes-config-dir` of `config` is not `false`, the call writes
    /// the file `<name>.conf` into the directory. The file holds the one
    /// group `[remote "<name>"]`. Its mode is `0666` with the umask applied.
    /// If the directory is absent, the call creates it and each absent
    /// parent, at mode `0777` with the umask applied. In a
    /// `bare-user-shared` repository, each directory that the call creates
    /// for an [`InRepo`](crate::RemotesDir::InRepo) value gets the mode
    /// `02770`. The call refuses the name if the directory holds an entry
    /// `<name>.conf` of any type, also a symlink. The check and the write are
    /// one step: the move of the temp file to `<name>.conf` does not replace
    /// an entry.
    ///
    /// Else the `[remote "<name>"]` group goes at the end of `config`. The
    /// call does not touch a trusted keyring of the name. A refusal writes
    /// nothing.
    ///
    /// The call reads `config` and the remotes directory from disk, edits
    /// the target, and writes it in one step on the blocking pool. It writes
    /// `config` as [`write_config`](UpdateGuard::write_config) does:
    /// atomically, with the sync of the repository directory left to
    /// [`finish`](UpdateGuard::finish). It writes a `.conf` file as
    /// [`UpdateGuard`] states in "Remotes". [`Repo::config`] keeps the copy
    /// that the handle read at open.
    ///
    /// The rewrite of `config` keeps the groups and keys of the file in their
    /// order. It drops the comment lines and the blank lines of the file.
    ///
    /// The remote calls and [`write_config`](UpdateGuard::write_config) of one
    /// guard run one at a time, so concurrent calls on one guard lose no edit.
    /// If the future of a call drops after its first poll, the call makes the
    /// whole edit or none of it. An edit that runs completes, and `finish`
    /// waits for it.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `name`, if
    ///   `keys` is empty, or if a key file cannot hold a key name of `keys`.
    /// - [`Error::RemoteExists`] if `config` or a `.conf` file has a remote
    ///   of that name.
    /// - [`Error::Io`] of the kind
    ///   [`AlreadyExists`](std::io::ErrorKind::AlreadyExists) if the call
    ///   writes into the remotes directory and the directory holds an entry
    ///   `<name>.conf`. The message starts with the path of the entry.
    /// - [`Error::Core`] if `[core] add-remotes-config-dir` is not a boolean.
    ///   The call reads the key only for a handle with a remotes directory.
    /// - The errors of [`read_config`](UpdateGuard::read_config).
    /// - [`Error::InvalidFormat`] if the new file is larger than 1 MiB.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn add_remote(&self, name: &str, keys: &[(&str, &str)]) -> Result<()> {
        if !valid_remote_name(name) {
            return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
        }
        if keys.is_empty() {
            return Err(Error::InvalidInput(format!(
                "remote {name} is added with no keys"
            )));
        }
        let name = name.to_owned();
        let keys: Vec<(String, String)> = keys
            .iter()
            .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
            .collect();
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            let (config, writer) = read_sources(root, dir.as_ref(), fsync)?;
            if config.remote(&name).is_some() {
                return Err(Error::RemoteExists(name));
            }
            let writer = match writer {
                Some(writer) if config.add_remotes_config_dir()? => Some(writer),
                _ => None,
            };
            let group = remote_group(&name);
            let mut keyfile = match writer {
                Some(_) => KeyFile::default(),
                None => config.into_keyfile(),
            };
            for (key, value) in &keys {
                check_key(key)?;
                keyfile.set_string(&group, key, value)?;
            }
            match writer {
                Some(writer) => {
                    let file = remote_file_name(&name);
                    writer.put(&file, keyfile.to_string().as_bytes(), Publish::KeepExisting)
                }
                None => put_config_blocking(root, &config_bytes(&keyfile)?, fsync, dirs),
            }
        })
        .await
    }

    /// Sets the key `key` of the remote `name` to `value`, in the file that
    /// holds the remote: `config` or a `.conf` file of the remotes directory.
    ///
    /// A key that exists keeps its position. A new key goes at the end of the
    /// group. If the key holds `value` already, the call writes nothing.
    ///
    /// The call reads the files and writes `config` as
    /// [`add_remote`](UpdateGuard::add_remote) does. A rewrite of a `.conf`
    /// file keeps the other groups of the file and the groups and keys in
    /// their order, and drops the comment lines and the blank lines. A
    /// refusal writes nothing.
    ///
    /// # Errors
    ///
    /// - [`Error::RemoteNotFound`] if no source holds the remote.
    /// - [`Error::InvalidInput`] if a key file cannot hold the key name.
    /// - The errors of [`read_config`](UpdateGuard::read_config).
    /// - [`Error::InvalidFormat`] if the new file is larger than 1 MiB.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn set_remote_key(&self, name: &str, key: &str, value: &str) -> Result<()> {
        let name = name.to_owned();
        let key = key.to_owned();
        let value = value.to_owned();
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            let group = remote_group(&name);
            let mut source = Source::read(root, dir.as_ref(), fsync, &name)?;
            check_key(&key)?;
            let keyfile = source.keyfile_mut();
            if matches!(keyfile.get_string(&group, &key), Ok(Some(held)) if held == value) {
                return Ok(());
            }
            keyfile.set_string(&group, &key, &value)?;
            source.put(root, fsync, dirs)
        })
        .await
    }

    /// Removes the key `key` of the remote `name` from the file that holds
    /// the remote.
    ///
    /// The call returns `true` if it removed the key. If the key is absent,
    /// the call returns `false` and writes nothing. The group stays, also when
    /// it has no key left.
    ///
    /// The call reads and writes the files as
    /// [`set_remote_key`](UpdateGuard::set_remote_key) does.
    ///
    /// # Errors
    ///
    /// - [`Error::RemoteNotFound`] if no source holds the remote. The call
    ///   then writes nothing.
    /// - The errors of [`read_config`](UpdateGuard::read_config).
    /// - [`Error::InvalidFormat`] if the new file is larger than 1 MiB.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn unset_remote_key(&self, name: &str, key: &str) -> Result<bool> {
        let name = name.to_owned();
        let key = key.to_owned();
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            let group = remote_group(&name);
            let mut source = Source::read(root, dir.as_ref(), fsync, &name)?;
            if !source.keyfile_mut().remove_key(&group, &key) {
                return Ok(false);
            }
            source.put(root, fsync, dirs)?;
            Ok(true)
        })
        .await
    }

    /// Replaces the remote `name` with a remote of the keys of `keys`, in
    /// order, in the file that holds it.
    ///
    /// The call removes the `[remote "<name>"]` group from its source,
    /// `config` or a `.conf` file of the remotes directory, and writes a new
    /// group with `keys` at the end of the same source. The other groups of
    /// the source stay. The call does not touch a trusted keyring of the
    /// name. A refusal writes nothing.
    ///
    /// The call reads and writes the source as
    /// [`set_remote_key`](UpdateGuard::set_remote_key) does.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `name`, if
    ///   `keys` is empty, or if a key file cannot hold a key name of `keys`.
    /// - [`Error::RemoteNotFound`] if no source holds the remote.
    /// - The errors of [`read_config`](UpdateGuard::read_config).
    /// - [`Error::InvalidFormat`] if the new file is larger than 1 MiB.
    /// - [`Error::Io`] if a file system operation fails.
    pub async fn replace_remote(&self, name: &str, keys: &[(&str, &str)]) -> Result<()> {
        if !valid_remote_name(name) {
            return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
        }
        if keys.is_empty() {
            return Err(Error::InvalidInput(format!(
                "remote {name} is replaced with no keys"
            )));
        }
        let name = name.to_owned();
        let keys: Vec<(String, String)> = keys
            .iter()
            .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
            .collect();
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            let group = remote_group(&name);
            let mut source = Source::read(root, dir.as_ref(), fsync, &name)?;
            let keyfile = source.keyfile_mut();
            keyfile.remove_group(&group);
            for (key, value) in &keys {
                check_key(key)?;
                keyfile.set_string(&group, key, value)?;
            }
            source.put(root, fsync, dirs)
        })
        .await
    }

    /// Deletes the remote `name` from the file that holds it, together with
    /// its repository keyring.
    ///
    /// The call removes the trusted keyring `<name>.trustedkeys.gpg` at the
    /// repository root, and then the group of the remote from its file. For a
    /// symlink at the keyring, it removes the link, and the target stays. An
    /// absent keyring is not an error. A keyring name that is too long for the
    /// file system is not an error, because no file can have that name. The
    /// call does not remove a keyring of the remotes directory.
    ///
    /// In a `.conf` file of the remotes directory, the call removes the group.
    /// If the file then holds no `[remote "NAME"]` group, the call removes the
    /// file, together with each other group of it. For a symlink, it removes
    /// the link, and the target stays. Else it writes the file back, as
    /// [`set_remote_key`](UpdateGuard::set_remote_key) does.
    ///
    /// The repository keyring goes with the remote. A keyring of the remotes
    /// directory stays, as the `ostree` command keeps it. A later remote of the
    /// same name trusts the keys of that keyring while the repository holds no
    /// keyring of that name. The repository keyring goes first, so a failure
    /// between the two steps can leave a remote with no repository keyring. It
    /// cannot leave a repository keyring with no remote.
    ///
    /// The removal is visible when the call returns. The sync of the
    /// repository directory waits for [`finish`](UpdateGuard::finish). The
    /// call reads the files and writes `config` as
    /// [`add_remote`](UpdateGuard::add_remote) does. A refusal removes no
    /// file and writes nothing.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `name`.
    /// - [`Error::RemoteNotFound`] if no source holds the remote.
    /// - The errors of [`read_config`](UpdateGuard::read_config).
    /// - [`Error::InvalidFormat`] if the new file is larger than 1 MiB.
    /// - [`Error::Io`] if the removal of the keyring or the write of the file
    ///   fails.
    pub async fn delete_remote(&self, name: &str) -> Result<()> {
        if !valid_remote_name(name) {
            return Err(Error::InvalidInput(format!("invalid remote name: {name}")));
        }
        let name = name.to_owned();
        let dir = self.repo().remotes_dir().cloned();
        self.edit_config(move |root, fsync, dirs| {
            let group = remote_group(&name);
            let keyring = remote_keyring_name(&name);
            match Source::read(root, dir.as_ref(), fsync, &name)? {
                Source::Config(mut keyfile) => {
                    keyfile.remove_group(&group);
                    let bytes = config_bytes(&keyfile)?;
                    let removed = remove_keyring_blocking(root, &keyring)?;
                    let put = put_config_blocking(root, &bytes, fsync, dirs);
                    if fsync && removed && put.is_err() {
                        dirs.push(ROOT_DIR.to_owned());
                    }
                    put
                }
                Source::File {
                    writer,
                    file,
                    mut keyfile,
                } => {
                    keyfile.remove_group(&group);
                    // Each check comes before the removal of the keyring.
                    let rewrite = if keyfile.groups().any(|g| remote_group_name(g).is_some()) {
                        let bytes = keyfile.to_string().into_bytes();
                        writer.check_size(&file, &bytes)?;
                        Some(bytes)
                    } else {
                        None
                    };
                    if remove_keyring_blocking(root, &keyring)? && fsync {
                        dirs.push(ROOT_DIR.to_owned());
                    }
                    match rewrite {
                        Some(bytes) => writer.put(&file, &bytes, Publish::Replace),
                        None => writer.remove(&file),
                    }
                }
            }
        })
        .await
    }

    /// Syncs the directories that the writes changed, and releases both locks.
    ///
    /// The call first waits until each write of the guard ends. It then runs
    /// `fsync` once on each directory that a write changed, deepest first. It
    /// then releases the update lock and the repository lock. If `[core]
    /// fsync` is off, the guard records no directory, and the call runs no
    /// sync.
    ///
    /// The wait covers a write whose future was dropped while its work on the
    /// blocking pool still ran. That work ends before the syncs start, so the
    /// call syncs the directories of each write of the guard. Both locks are
    /// free when the call returns.
    ///
    /// The call runs each sync, also after a sync that fails. The release of
    /// the locks comes after the syncs, also if the returned future drops
    /// before it completes.
    ///
    /// # Errors
    ///
    /// - [`Error::Io`] if a sync fails. The call returns the error of the
    ///   first sync that fails.
    pub async fn finish(self) -> Result<()> {
        let held = self.held;
        {
            let writes = held.writes();
            if writes.in_flight == 0 && writes.dirs.is_empty() {
                drop(writes);
                held.release();
                return Ok(());
            }
        }
        ostrya_rt::unblock(move || held.finish_blocking()).await
    }

    async fn set_relpath(
        &self,
        name: String,
        relpath: String,
        checksum: Option<&Checksum>,
    ) -> Result<()> {
        let checksum = checksum.copied();
        self.write(move |root, fsync, dirs| {
            put_ref_blocking(root, &name, &relpath, checksum, fsync, dirs)
        })
        .await
    }

    /// Runs `edit` as a write of the guard, as [`write`](UpdateGuard::write)
    /// runs it, and holds the `config` lock of the guard for the whole edit.
    async fn edit_config<T, F>(&self, edit: F) -> Result<T>
    where
        F: FnOnce(&RepoDir, bool, &mut Vec<String>) -> Result<T> + Send + 'static,
        T: Send + 'static,
    {
        let held = self.held.clone();
        self.write(move |root, fsync, dirs| {
            let _config = held.config.lock().unwrap_or_else(PoisonError::into_inner);
            edit(root, fsync, dirs)
        })
        .await
    }

    /// Runs the write `put` on the blocking pool and records the directories
    /// that it changed.
    ///
    /// The closure owns a reference to the held state and counts in flight
    /// until it ends. A write whose future drops still holds both locks until
    /// it ends, and still records its directories. It also holds
    /// [`finish`](UpdateGuard::finish) back until it ends.
    async fn write<T, F>(&self, put: F) -> Result<T>
    where
        F: FnOnce(&RepoDir, bool, &mut Vec<String>) -> Result<T> + Send + 'static,
        T: Send + 'static,
    {
        let flight = InFlight::start(&self.held);
        ostrya_rt::unblock(move || {
            let held = &flight.held;
            let mut dirs = Vec::new();
            let written = put(held.repo.root_dir(), held.fsync, &mut dirs);
            if held.fsync {
                held.writes().dirs.extend(dirs);
            }
            drop(flight);
            written
        })
        .await
    }
}

/// Refuses a key name that no key file can hold, as an argument error of the
/// caller. The check sets the key alone in an empty key file. As a result, an
/// error of the group of `config` does not count as an error of the key.
fn check_key(key: &str) -> Result<()> {
    KeyFile::default()
        .set_string(KEY_CHECK_GROUP, key, "")
        .map_err(|e| Error::InvalidInput(e.to_string()))
}

/// Returns the name of the `.conf` file that an add writes for the remote
/// `name`.
fn remote_file_name(name: &str) -> String {
    format!("{name}.conf")
}

/// Reads `config` and the `.conf` files of the remotes directory `dir` from
/// disk, as [`UpdateGuard::read_config`] reads them. Returns the directory
/// open for a write if the handle has one.
fn read_sources<'a>(
    root: &'a RepoDir,
    dir: Option<&'a RemotesDir>,
    fsync: bool,
) -> Result<(RepoConfig, Option<DirWriter<'a>>)> {
    let config = read_config(root)?;
    match dir {
        Some(dir) => remotes_dir::open_for_write(config, root.as_fd(), dir, fsync)
            .map(|(config, writer)| (config, Some(writer))),
        None => Ok((config, None)),
    }
}

/// The file on disk that holds a remote, with its parsed text.
enum Source<'a> {
    /// The `config` file of the repository.
    Config(KeyFile),
    /// The `.conf` file `file` of the remotes directory.
    File {
        writer: DirWriter<'a>,
        file: String,
        keyfile: KeyFile,
    },
}

impl<'a> Source<'a> {
    /// Reads the sources from disk, as [`read_sources`] does, and returns the
    /// source that holds the remote `name`.
    ///
    /// # Errors
    ///
    /// [`Error::RemoteNotFound`] if no source holds the remote, and the
    /// errors of the read.
    fn read(
        root: &'a RepoDir,
        dir: Option<&'a RemotesDir>,
        fsync: bool,
        name: &str,
    ) -> Result<Source<'a>> {
        let (config, writer) = read_sources(root, dir, fsync)?;
        let not_found = || Error::RemoteNotFound(name.to_owned());
        let file = match config.remote(name).ok_or_else(not_found)?.source() {
            RemoteSource::Config => None,
            RemoteSource::File(file) => Some(file.to_owned()),
        };
        let Some(file) = file else {
            return Ok(Source::Config(config.into_keyfile()));
        };
        let keyfile = config.into_remote_file(&file).ok_or_else(not_found)?;
        Ok(Source::File {
            writer: writer.ok_or_else(not_found)?,
            file,
            keyfile,
        })
    }

    fn keyfile_mut(&mut self) -> &mut KeyFile {
        match self {
            Source::Config(keyfile) | Source::File { keyfile, .. } => keyfile,
        }
    }

    /// Writes the edited text back to its file.
    ///
    /// A write of `config` records the repository root for the sync of
    /// [`UpdateGuard::finish`]. A write of a `.conf` file keeps the permission
    /// bits of a regular file, replaces a symlink with a regular file, and
    /// syncs before it returns.
    fn put(&self, root: &RepoDir, fsync: bool, dirs: &mut Vec<String>) -> Result<()> {
        match self {
            Source::Config(keyfile) => {
                put_config_blocking(root, &config_bytes(keyfile)?, fsync, dirs)
            }
            Source::File {
                writer,
                file,
                keyfile,
            } => writer.put(file, keyfile.to_string().as_bytes(), Publish::Replace),
        }
    }
}

/// Returns the bytes of `keyfile` as `config` holds them. Refuses a document
/// larger than the size that an open accepts.
fn config_bytes(keyfile: &KeyFile) -> Result<Vec<u8>> {
    let bytes = keyfile.to_string().into_bytes();
    check_config_size(&bytes)?;
    Ok(bytes)
}

/// Writes `bytes` to `config` atomically and records the repository root.
fn put_config_blocking(
    root: &RepoDir,
    bytes: &[u8],
    fsync: bool,
    dirs: &mut Vec<String>,
) -> Result<()> {
    root.stage_root_file(&RootFile::Config, bytes, fsync)?
        .publish(root, RootFile::Config.name(), Publish::Replace, false)?;
    if fsync {
        dirs.push(ROOT_DIR.to_owned());
    }
    Ok(())
}

/// Removes the trusted keyring `name` at the repository root, and returns
/// `true` if a file was removed. For a symlink, the call removes the link,
/// and the target stays. An absent file is not an error. A name that is too
/// long for the file system is not an error, because no file can have that
/// name. The call syncs nothing: the caller records the root for the sync of
/// [`UpdateGuard::finish`].
fn remove_keyring_blocking(root: &RepoDir, name: &str) -> Result<bool> {
    match root.remove_file(name, false) {
        Ok(removed) => Ok(removed),
        Err(FsError::Io(e)) if e.raw_os_error() == Some(Errno::NAMETOOLONG.raw_os_error()) => {
            Ok(false)
        }
        Err(e) => Err(e.into()),
    }
}

/// Compile-time checks that the guard is `Send + Sync` and that the futures of
/// its calls are `Send`.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    fn assert_send<T: Send>(_: &T) {}
    assert_send_sync::<UpdateGuard>();
    let _ = |repo: &Repo| assert_send(&repo.begin_update());
    let _ = |guard: &UpdateGuard, r: &Ref, c: &Checksum| assert_send(&guard.set_ref(r, Some(c)));
    let _ = |guard: &UpdateGuard, k: &KeyFile| assert_send(&guard.write_config(k));
    let _ = |guard: &UpdateGuard| assert_send(&guard.add_remote("r", &[("url", "u")]));
    let _ = |guard: &UpdateGuard| assert_send(&guard.set_remote_key("r", "url", "u"));
    let _ = |guard: &UpdateGuard| assert_send(&guard.unset_remote_key("r", "url"));
    let _ = |guard: &UpdateGuard| assert_send(&guard.replace_remote("r", &[("url", "u")]));
    let _ = |guard: &UpdateGuard| assert_send(&guard.delete_remote("r"));
    let _ = |guard: UpdateGuard| assert_send(&guard.finish());
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lock::LockKind;
    use crate::refs::test_syncs;
    use crate::{CreateOptions, RepoMode};
    use futures_lite::future::poll_once;
    use std::path::PathBuf;

    /// A scratch directory that holds a repository at `repo`. The drop of the
    /// value removes the directory.
    struct Scratch {
        dir: PathBuf,
    }

    impl Scratch {
        fn new(label: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "ostrya-update-guard-{label}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Scratch { dir }
        }

        fn path(&self) -> PathBuf {
            self.dir.join("repo")
        }

        fn create(&self) -> Repo {
            ostrya_rt::block_on(Repo::create(
                &self.path(),
                CreateOptions::new(RepoMode::BareUser),
            ))
            .unwrap()
        }

        /// Creates the repository with `line` added to the `[core]` group.
        fn create_with(&self, line: &str) -> Repo {
            drop(self.create());
            let config = self.path().join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(line);
            text.push('\n');
            std::fs::write(&config, text).unwrap();
            ostrya_rt::block_on(Repo::open(&self.path())).unwrap()
        }
    }

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

    fn checksum() -> Checksum {
        Checksum::from_bytes([7; 32])
    }

    /// Takes both locks again, as another writer does, and returns the number
    /// of directory syncs under the repository at that point.
    async fn syncs_when_free(repo: &Repo, root: &std::path::Path) -> usize {
        let held = repo.lock_update().await.unwrap();
        let exclusive = repo.lock_repo(LockKind::Exclusive).await.unwrap();
        let count = test_syncs::count(root);
        drop((exclusive, held));
        count
    }

    /// Writes two refs in two directories and a config through `guard`, so
    /// the guard records three directories.
    async fn write_three_dirs(guard: &UpdateGuard) {
        guard
            .set_ref(&Ref::local("a/one"), Some(&checksum()))
            .await
            .unwrap();
        guard
            .set_ref(&Ref::local("b"), Some(&checksum()))
            .await
            .unwrap();
        let keyfile = guard.read_config().await.unwrap().keyfile().clone();
        guard.write_config(&keyfile).await.unwrap();
    }

    #[test]
    fn a_dropped_guard_syncs_before_the_locks_go() {
        let scratch = Scratch::new("drop");
        let repo = scratch.create();
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            write_three_dirs(&guard).await;
            let before = test_syncs::count(&scratch.path());
            drop(guard);
            // refs/heads/a, refs/heads, and the repository root.
            assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
            assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
        });
    }

    #[test]
    fn a_finish_polled_once_and_dropped_syncs_before_the_locks_go() {
        let scratch = Scratch::new("finish-dropped");
        let repo = scratch.create();
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            write_three_dirs(&guard).await;
            let before = test_syncs::count(&scratch.path());
            let mut finish = Box::pin(guard.finish());
            let _ = poll_once(&mut finish).await;
            drop(finish);
            assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
            assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
        });
    }

    #[test]
    fn a_finish_never_polled_syncs_before_the_locks_go() {
        let scratch = Scratch::new("finish-unpolled");
        let repo = scratch.create();
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            write_three_dirs(&guard).await;
            let before = test_syncs::count(&scratch.path());
            drop(guard.finish());
            assert_eq!(syncs_when_free(&repo, &scratch.path()).await, before + 3);
            assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
        });
    }

    #[test]
    fn finish_syncs_each_directory_once() {
        let scratch = Scratch::new("finish");
        let repo = scratch.create();
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            write_three_dirs(&guard).await;
            guard
                .set_ref(&Ref::local("a/two"), Some(&checksum()))
                .await
                .unwrap();
            let before = test_syncs::count(&scratch.path());
            guard.finish().await.unwrap();
            assert_eq!(test_syncs::count(&scratch.path()), before + 3);
            assert_eq!(test_syncs::unlocked(&scratch.path()), 0);
        });
    }

    #[test]
    fn finish_waits_for_a_write_whose_future_was_dropped() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::mpsc;
        use std::time::Duration;

        let scratch = Scratch::new("in-flight");
        // A second take of the repository lock makes one attempt.
        let repo = scratch.create_with("lock-timeout-secs=0");
        let root = scratch.path();
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            let (started_tx, started_rx) = mpsc::channel();
            let (go_tx, go_rx) = mpsc::channel::<()>();
            let ended = Arc::new(AtomicBool::new(false));
            let ended_in = ended.clone();
            let mut write = Box::pin(guard.write(move |root, fsync, dirs| {
                started_tx.send(()).unwrap();
                go_rx.recv().unwrap();
                let written = put_ref_blocking(
                    root,
                    "late/one",
                    "refs/heads/late/one",
                    Some(checksum()),
                    fsync,
                    dirs,
                );
                ended_in.store(true, Ordering::SeqCst);
                written
            }));
            assert!(poll_once(&mut write).await.is_none());
            started_rx
                .recv_timeout(Duration::from_secs(10))
                .expect("the write started on the blocking pool");
            drop(write);

            let before = test_syncs::count(&root);
            let mut finish = Box::pin(guard.finish());
            assert!(poll_once(&mut finish).await.is_none(), "finish waits");
            ostrya_rt::Timer::after(Duration::from_millis(100)).await;
            assert!(poll_once(&mut finish).await.is_none(), "finish waits");
            assert!(crate::lock::update_lock_held_in_process(repo.repo_fd()));

            go_tx.send(()).unwrap();
            finish.await.unwrap();
            assert!(ended.load(Ordering::SeqCst), "the write ended first");
            // refs/heads/late. The write synced refs/heads when it made
            // refs/heads/late.
            assert_eq!(test_syncs::count(&root), before + 1);
            assert_eq!(test_syncs::unlocked(&root), 0);
            assert!(!crate::lock::update_lock_held_in_process(repo.repo_fd()));
            let exclusive = repo.lock_repo(LockKind::Exclusive).await.unwrap();
            drop(exclusive);
        });
    }

    #[test]
    fn fsync_off_records_no_directory() {
        let scratch = Scratch::new("no-fsync");
        let repo = scratch.create_with("fsync=false");
        ostrya_rt::block_on(async {
            let guard = repo.begin_update().await.unwrap();
            write_three_dirs(&guard).await;
            let before = test_syncs::count(&scratch.path());
            guard.finish().await.unwrap();
            assert_eq!(test_syncs::count(&scratch.path()), before);
        });
    }
}