runnerd-core 0.1.4

Config, domain logic and API types shared by runnerd and its clients
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
//! Runner containers through the Docker Engine API: the connection, container, volume and image requests, and the
//! `DockerApi` trait the engine and the caches call. It decides nothing about scheduling, and a JIT config only
//! ever reaches a container as a root-only file, never the create request or a log line.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::time::{Duration, Instant};

use bollard::exec::{CreateExecOptions, StartExecResults};
use std::pin::Pin;

use bollard::models::{
    ChangeType, ContainerConfig, ContainerCreateBody, CreateImageInfo, HostConfig, Mount,
    NetworkCreateRequest, SystemInfo, VolumeCreateRequest,
};
use bollard::query_parameters::{
    AttachContainerOptionsBuilder, CommitContainerOptionsBuilder, CreateContainerOptionsBuilder,
    CreateImageOptionsBuilder, DataUsageOptionsBuilder, DownloadFromContainerOptionsBuilder,
    EventsOptionsBuilder, InspectContainerOptionsBuilder, ListContainersOptionsBuilder,
    ListImagesOptionsBuilder, ListVolumesOptionsBuilder, LogsOptionsBuilder,
    RemoveContainerOptionsBuilder, RemoveImageOptionsBuilder, RemoveVolumeOptionsBuilder,
    ResizeContainerTTYOptionsBuilder, UploadToContainerOptionsBuilder, WaitContainerOptionsBuilder,
};
use futures_util::stream::BoxStream;
use futures_util::{StreamExt, TryStreamExt};
use tracing::info;

use crate::config::ByteSize;
use crate::isolation::Isolation;

pub use bollard::errors::Error;

/// One runner container: a profile's image stage with the profile's limits.
#[derive(Debug, Clone)]
pub struct RunnerSpec {
    /// The container's name; for a runner, also the runner's.
    pub name: String,
    /// The image, such as `runnerd-runner:base`.
    pub image: String,
    /// The profile, put on the `runnerd.profile` label.
    pub profile: String,
    /// The systemd slice the container is placed in.
    pub slice: String,
    /// CPUs the container may use.
    pub cpus: u32,
    /// Memory the container may use, swap included.
    pub memory: ByteSize,
    /// `NAME=value` environment variables.
    pub env: Vec<String>,
    /// Volumes to mount.
    pub mounts: Vec<Mount>,
    /// The network the container joins; `None` is Docker's default bridge.
    pub network: Option<String>,
    /// Labels on top of `runnerd.profile` and `runnerd.isolation`.
    pub labels: BTreeMap<String, String>,
    /// Replaces the image's entrypoint; `None` runs the runner.
    pub entrypoint: Option<Vec<String>>,
    /// The runner's just-in-time config, which the entrypoint reads from `JIT_CONFIG_PATH`.
    pub jit_config: Option<JitConfig>,
}

/// Where `start` puts the just-in-time config in the container: a root-only file, never the create request,
/// which Docker stores and clients may log.
pub const JIT_CONFIG_PATH: &str = "/run/runnerd/jitconfig";

/// What a runner container's environment holds to have its image answer the runner's sync calls without syncing
/// (`[host] skip_syncs`, ADR 0141). runnerd sets it only for an image that carries `SKIP_SYNCS_LABEL`; an image
/// without `runnerd-skip-syncs` would ignore it and sync.
pub const SKIP_SYNCS: &str = "RUNNERD_SKIP_SYNCS=1";

/// The label of a runner image whose entrypoint runs `runnerd-skip-syncs` (`image/Dockerfile`), with the version of
/// what it answers to: `1`, `SKIP_SYNCS`. Runner images before it lack it, and their runners keep their syncs.
pub const SKIP_SYNCS_LABEL: &str = "runnerd.skip-syncs";

/// The label of a runner image whose entrypoint, asked `SKIP_SYNCS`, also mounts the slot's layers `volatile`, so
/// unmounting them syncs nothing (ADR 0142): `1`. The crash guard is the same as for the sync calls, so runnerd asks
/// by `SKIP_SYNCS_LABEL` alone; this one tells doctor what such a runner skips. Any value reads as volatile layers: a
/// later version of the label still says the image has them.
pub const VOLATILE_LAYERS_LABEL: &str = "runnerd.volatile-layers";

/// Whether an image's labels say it answers `SKIP_SYNCS`.
pub fn skips_syncs<S: std::hash::BuildHasher>(labels: &HashMap<String, String, S>) -> bool {
    labels
        .get(SKIP_SYNCS_LABEL)
        .is_some_and(|version| version == "1")
}

/// What an image's runners skip when runnerd asks them, as its labels say: sync calls and their layers' unmount
/// syncs, sync calls only, or nothing.
pub fn image_syncs<S: std::hash::BuildHasher>(
    labels: &HashMap<String, String, S>,
) -> crate::config::ImageSyncs {
    use crate::config::ImageSyncs;
    if !skips_syncs(labels) {
        ImageSyncs::Syncs
    } else if labels.contains_key(VOLATILE_LAYERS_LABEL) {
        ImageSyncs::Skips
    } else {
        ImageSyncs::SkipsCalls
    }
}

/// A runner's just-in-time config from GitHub: credentials, never printed.
#[derive(Clone)]
pub struct JitConfig(pub String);

impl fmt::Debug for JitConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("JitConfig(<redacted>)")
    }
}

/// What `inspect` reports about a runner container.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunnerState {
    /// Whether the container runs.
    pub running: bool,
    /// Its exit code, once it stopped.
    pub exit_code: Option<i64>,
    /// Whether the kernel killed a process in it for memory, as Docker saw.
    pub oom_killed: bool,
    /// True under `unsafe-dind`: a job in the container can take over the host.
    pub privileged: bool,
    /// The runtime Docker runs it with, such as `sysbox-runc`.
    pub runtime: Option<String>,
    /// Its main process on the host, while it runs.
    pub pid: Option<u32>,
    /// Its address on its first network.
    pub address: Option<String>,
    /// When it started, in milliseconds since the epoch.
    pub started_at: Option<u64>,
    /// When it stopped, in milliseconds since the epoch; `None` while it runs.
    pub finished_at: Option<u64>,
    /// Its memory cap in bytes; `None` when it has none.
    pub memory: Option<u64>,
    /// Its CPU limit in millicores; `None` when it has none.
    pub cpus: Option<u64>,
}

/// What a command run in a container prints on stdout, as it prints it.
pub type Output = BoxStream<'static, Result<Vec<u8>, Error>>;

/// An image `images` found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// Its first tag, such as `runnerd-record:42`; its ID when it has none.
    pub reference: String,
    /// Its labels.
    pub labels: HashMap<String, String>,
    /// The disk it takes beyond its parent image: what removing it frees.
    pub bytes: u64,
}

/// An image `tagged_images` found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaggedImage {
    /// Its ID, such as `sha256:224e…`.
    pub id: String,
    /// Its tags, such as `ghcr.io/ayagmar/runnerd-runner:node-0.1.4`.
    pub tags: Vec<String>,
    /// The registry digests it was pulled by, such as `ghcr.io/ayagmar/runnerd-runner@sha256:9e79…`.
    pub digests: Vec<String>,
}

/// A file `files` read from a container.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct File {
    /// Its name in the directory read, such as `Worker_20261031-120000-utc.log`.
    pub name: String,
    /// What it holds, as text: invalid UTF-8 is replaced. Cut short past `FILES_LIMIT`.
    pub contents: String,
}

/// What `files` read of a directory.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Files {
    /// The files read, in the archive's order.
    pub files: Vec<File>,
    /// Whether they are all there and whole: the archive ended as a tar does, and none was cut at `FILES_LIMIT`. A
    /// file missing from an incomplete read may be in the directory.
    pub complete: bool,
}

/// The most of the files `files` keeps, together. What it skips, such as a runner's job log pages below `_diag`,
/// does not count: it is read through and dropped.
pub(crate) const FILES_LIMIT: usize = 16 << 20;

/// A container's terminal, attached once it was created and before it started, so none of its output is missed.
pub struct Tty {
    /// The container's ID.
    pub container: String,
    /// What the terminal shows, as it shows it; it ends when the container's process exits.
    pub output: BoxStream<'static, Result<Vec<u8>, Error>>,
    /// What is typed into it.
    pub input: Pin<Box<dyn tokio::io::AsyncWrite + Send>>,
}

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

/// A terminal's size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TtySize {
    /// Columns.
    pub cols: u16,
    /// Rows.
    pub rows: u16,
}

/// The CPU shares of a runner's container or a record's shell with `cpus` CPUs: 1024 a CPU, within the 2 to 262144
/// Docker takes, which it writes as the container's `cpu.weight`. They sit in the slice beside each other, so when the
/// slice's CPUs are all in use they share them in proportion to their `cpus`, not evenly; a container with work still
/// gets at most its `cpus` (`nano_cpus`). The mirror keeps Docker's default weight, which every job's pulls go
/// through, and programs outside the slice share the host's CPUs with the slice by its own weight (ADR 0079).
pub fn cpu_shares(cpus: u32) -> i64 {
    (i64::from(cpus) * 1024).clamp(2, 262_144)
}

/// The create-container request for a runner container under an isolation backend.
pub fn create_body(spec: &RunnerSpec, isolation: &dyn Isolation) -> ContainerCreateBody {
    // Clamped to 8 EiB, the most Docker takes.
    let memory = i64::try_from(spec.memory.0).unwrap_or(i64::MAX);
    let mut host_config = HostConfig {
        cgroup_parent: Some(spec.slice.clone()),
        memory: Some(memory),
        // Swap equal to memory: the container gets no swap on top of its memory.
        memory_swap: Some(memory),
        nano_cpus: Some(i64::from(spec.cpus) * 1_000_000_000),
        cpu_shares: Some(cpu_shares(spec.cpus)),
        init: Some(true),
        mounts: Some(spec.mounts.clone()),
        network_mode: spec.network.clone(),
        ..Default::default()
    };
    isolation.configure(&mut host_config);
    let mut labels: HashMap<String, String> = spec.labels.clone().into_iter().collect();
    labels.insert("runnerd.profile".to_owned(), spec.profile.clone());
    labels.insert("runnerd.isolation".to_owned(), isolation.name().to_owned());
    ContainerCreateBody {
        image: Some(spec.image.clone()),
        env: Some(spec.env.clone()),
        entrypoint: spec.entrypoint.clone(),
        labels: Some(labels),
        host_config: Some(host_config),
        ..Default::default()
    }
}

/// A container `list` found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Container {
    /// The Docker container ID.
    pub id: String,
    /// Without Docker's leading `/`.
    pub name: String,
    /// Whether it runs.
    pub running: bool,
    /// Its labels.
    pub labels: HashMap<String, String>,
}

/// A runner start that failed, with the container it may have left: Docker may have made, or even started, it before
/// the request failed, as when its answer is lost.
#[derive(Debug)]
pub struct StartError {
    /// The container the start left, by ID, or by name when Docker could not say whether one exists; `None` when
    /// none does. It may run.
    pub container: Option<String>,
    /// Whether Docker may have started the container before the start failed: its runner may have taken a job,
    /// even if the container is gone now.
    pub may_have_run: bool,
    /// Why the start failed.
    pub error: Error,
}

impl fmt::Display for StartError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt(f)
    }
}

impl std::error::Error for StartError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// For callers that go on whether or not a container was left.
impl From<StartError> for Error {
    fn from(failed: StartError) -> Error {
        failed.error
    }
}

/// Whether Docker answered a request with a refusal, so it did nothing: a 4xx answer. Any other error may come after
/// Docker carried the request out.
fn refused(error: &Error) -> bool {
    matches!(
        error,
        Error::DockerResponseServerError {
            status_code: 400..=499,
            ..
        }
    )
}

/// Whether a Docker error says the Engine did not answer at all: its socket is gone, refuses connections or closed
/// the connection, as while the machine shuts down. Not an answer the Engine gave, nor a timeout, which a busy Engine
/// also gives.
pub fn is_unreachable(error: &Error) -> bool {
    matches!(
        error,
        Error::HyperLegacyError { .. }
            | Error::HyperResponseError { .. }
            | Error::IOError { .. }
            | Error::SocketNotFoundError(_)
    )
}

/// Whether Docker answered that it cannot or will not do what was asked: a 4xx, or 501 for what it lacks, such as
/// the log of a container whose log driver keeps none. Asking again gets the same answer; any other error may not.
pub fn is_declined(error: &Error) -> bool {
    matches!(
        error,
        Error::DockerResponseServerError {
            status_code: 400..=499 | 501,
            ..
        }
    )
}

/// Whether a Docker error says the container, volume or image does not exist.
pub fn is_not_found(error: &Error) -> bool {
    matches!(
        error,
        Error::DockerResponseServerError {
            status_code: 404,
            ..
        }
    )
}

/// Whether Docker refused because it is removing the container already, as after a `docker rm -f`: it says so only in
/// the words of its 409, which a running container's refusal shares. It may still be stopping.
pub fn is_being_removed(error: &Error) -> bool {
    matches!(
        error,
        Error::DockerResponseServerError { status_code: 409, message }
            if message.contains("is already in progress") || message.contains("marked for removal")
    )
}

/// Whether Docker refused an exec because the container stopped, as one that ended while it was adopted: its log
/// is read once it is released.
pub fn is_not_running(error: &Error) -> bool {
    matches!(
        error,
        Error::DockerResponseServerError { status_code: 409, message } if message.ends_with(" is not running")
    )
}

/// Whether a container's log is out of reach because it is gone or going. A removal under way can still fail, so this
/// says nothing of whether the container will go.
pub fn is_log_gone(error: &Error) -> bool {
    is_not_found(error) || is_being_removed(error)
}

/// The Docker Engine calls the scheduler and the caches make. `Docker` is the real one; the engine's tests use a
/// fake.
pub trait DockerApi: Send + Sync {
    /// Creates and starts a runner container; returns its ID. A start that fails removes what it made, and says
    /// which container is left when it cannot.
    fn start(
        &self,
        spec: &RunnerSpec,
        isolation: &dyn Isolation,
    ) -> impl Future<Output = Result<String, StartError>> + Send;
    /// A container's state and isolation.
    fn inspect(&self, container: &str) -> impl Future<Output = Result<RunnerState, Error>> + Send;
    /// Removes a runner container, stopping it first if it runs.
    fn remove(&self, container: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// Creates and starts a container that is not a runner, such as the mirror; returns its ID.
    fn run(
        &self,
        name: &str,
        body: ContainerCreateBody,
    ) -> impl Future<Output = Result<String, Error>> + Send;
    /// Every container, running or not, that has the label.
    fn list(&self, label: &str) -> impl Future<Output = Result<Vec<Container>, Error>> + Send;
    /// The IDs of runner containers (labelled `runnerd.job`) as each stops, from Docker's events. A hint: Docker sends
    /// an event once at most, none while the stream is down, and keeps none to replay. The stream fails or ends with
    /// the connection, or when Docker restarts.
    fn exits(&self) -> BoxStream<'static, Result<String, Error>>;
    /// Waits for a container to exit; returns its exit code.
    fn wait(&self, container: &str) -> impl Future<Output = Result<i64, Error>> + Send;
    /// A container's output so far, stdout and stderr interleaved.
    fn logs(&self, container: &str) -> impl Future<Output = Result<String, Error>> + Send;
    /// A container's output since `since` (seconds since the epoch), each line prefixed with Docker's RFC 3339
    /// timestamp and a space.
    fn logs_since(
        &self,
        container: &str,
        since: u64,
    ) -> impl Future<Output = Result<String, Error>> + Send;
    /// Runs a command as root in a running container; its stdout streams until it exits or the container stops.
    /// Its stderr is dropped.
    fn exec(
        &self,
        container: &str,
        command: Vec<String>,
    ) -> impl Future<Output = Result<Output, Error>> + Send;
    /// Whether Docker has an image.
    fn image_present(&self, image: &str) -> impl Future<Output = Result<bool, Error>> + Send;
    /// Whether Docker has an image and it answers `SKIP_SYNCS`, as its labels say (`skips_syncs`).
    fn image_skips_syncs(&self, image: &str) -> impl Future<Output = Result<bool, Error>> + Send;
    /// Pulls an image, logging its progress every few seconds.
    fn pull(&self, image: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// Creates a bridge network unless it exists.
    fn ensure_network(&self, name: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// Creates a volume unless it exists.
    fn ensure_volume(&self, name: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// Removes a volume; a volume that does not exist is not an error. Docker refuses one a container mounts, even
    /// a stopped one.
    fn remove_volume(&self, name: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// Every container, running or not, that mounts the volume.
    fn holders(&self, volume: &str) -> impl Future<Output = Result<Vec<Container>, Error>> + Send;
    /// The disk size of every volume Docker knows, by name. Slow: Docker measures each volume.
    fn volume_sizes(&self) -> impl Future<Output = Result<BTreeMap<String, u64>, Error>> + Send;
    /// The names of the volumes Docker has whose names start with `prefix`. Fast: nothing is measured.
    fn volumes(&self, prefix: &str) -> impl Future<Output = Result<Vec<String>, Error>> + Send;
    /// The paths a container's own layer added or changed, not those it deleted.
    fn changes(&self, container: &str) -> impl Future<Output = Result<Vec<String>, Error>> + Send;
    /// The bytes a container's own layer holds.
    fn written(&self, container: &str) -> impl Future<Output = Result<u64, Error>> + Send;
    /// The files directly in a container's `directory` whose names start with `prefix`, not those in the
    /// directories below it, read from its filesystem whether it runs or stopped, without starting it.
    fn files(
        &self,
        container: &str,
        directory: &str,
        prefix: &str,
    ) -> impl Future<Output = Result<Files, Error>> + Send;
    /// Commits a stopped container's own layer as the image `reference` (`repository:tag`) with `labels`; returns
    /// the disk the image takes beyond its parent.
    fn commit(
        &self,
        container: &str,
        reference: &str,
        labels: BTreeMap<String, String>,
    ) -> impl Future<Output = Result<u64, Error>> + Send;
    /// Every image with the label.
    fn images(&self, label: &str) -> impl Future<Output = Result<Vec<Image>, Error>> + Send;
    /// The ID of the image a reference (tag, digest or ID) names; `None` when Docker does not have it.
    fn image_id(
        &self,
        reference: &str,
    ) -> impl Future<Output = Result<Option<String>, Error>> + Send;
    /// Every image Docker has a tag for.
    fn tagged_images(&self) -> impl Future<Output = Result<Vec<TaggedImage>, Error>> + Send;
    /// The image ID of every container, running or stopped.
    fn container_images(&self) -> impl Future<Output = Result<BTreeSet<String>, Error>> + Send;
    /// Removes an image and the layers only it used; one that does not exist is not an error.
    fn remove_image(&self, reference: &str) -> impl Future<Output = Result<(), Error>> + Send;
    /// The free disk where Docker keeps its images and containers: on a root in a file, on a loop device, the least
    /// of its own and the free disk under the file (`observe::disk::free_space`).
    fn free_space(&self) -> impl Future<Output = Result<u64, Error>> + Send;
    /// Where Docker keeps its images, containers and volumes (`DockerRootDir`), whose disks runners write to.
    fn root_dir(&self) -> impl Future<Output = Result<String, Error>> + Send;
    /// Creates a container with a terminal of `size`, attaches to it and starts it. The container's stdin closes
    /// when `Tty::input` is dropped.
    fn shell(
        &self,
        name: &str,
        body: ContainerCreateBody,
        size: TtySize,
    ) -> impl Future<Output = Result<Tty, Error>> + Send;
}

/// The local Docker Engine.
#[derive(Debug)]
pub struct Docker {
    api: bollard::Docker,
}

impl Docker {
    /// Removes the container a failed start `made`, if any; the start's `error` is the one worth reporting. The
    /// container stays in the answer unless its removal is confirmed.
    async fn clean_up(&self, made: Option<String>, error: Error, may_have_run: bool) -> StartError {
        let container = match made {
            Some(container) => match self.remove(&container).await {
                Err(failed) if !is_not_found(&failed) => Some(container),
                _ => None,
            },
            None => None,
        };
        StartError {
            container,
            may_have_run,
            error,
        }
    }

    /// Connects to the Docker Engine at `DOCKER_HOST`, or its local socket. Only `unix://` hosts are supported.
    pub fn connect() -> Result<Docker, Error> {
        connect_to(std::env::var("DOCKER_HOST").ok().as_deref())
    }

    /// The Engine's system information.
    pub async fn info(&self) -> Result<SystemInfo, Error> {
        self.api.info().await
    }

    /// An image's labels; `None` when Docker does not have it.
    pub async fn image_labels(
        &self,
        image: &str,
    ) -> Result<Option<HashMap<String, String>>, Error> {
        match self.api.inspect_image(image).await {
            Ok(inspect) => Ok(Some(
                inspect
                    .config
                    .and_then(|config| config.labels)
                    .unwrap_or_default(),
            )),
            Err(error) if is_not_found(&error) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Every container, running or not, that `filter` matches with `value`, as `docker ps --all --filter` does.
    async fn containers(&self, filter: &str, value: &str) -> Result<Vec<Container>, Error> {
        let options = ListContainersOptionsBuilder::new()
            .all(true)
            .filters(&HashMap::from([(filter, vec![value])]))
            .build();
        let containers = self.api.list_containers(Some(options)).await?;

        Ok(containers
            .into_iter()
            .map(|container| Container {
                id: container.id.unwrap_or_default(),
                name: container
                    .names
                    .and_then(|names| names.into_iter().next())
                    .unwrap_or_default()
                    .trim_start_matches('/')
                    .to_owned(),
                running: container.state
                    == Some(bollard::models::ContainerSummaryStateEnum::RUNNING),
                labels: container.labels.unwrap_or_default(),
            })
            .collect())
    }

    /// Asks the image's registry for its manifest, without pulling it, and returns the platforms it is built for,
    /// such as `linux/amd64`. An error means `pull` could not get it.
    pub async fn registry_platforms(&self, image: &str) -> Result<Vec<String>, Error> {
        let inspect = self.api.inspect_registry_image(image, None).await?;
        Ok(inspect
            .platforms
            .into_iter()
            .filter_map(|platform| Some(format!("{}/{}", platform.os?, platform.architecture?)))
            // Attestation manifests in an index carry the platform unknown/unknown.
            .filter(|platform| platform != "unknown/unknown")
            .collect())
    }
}

impl DockerApi for Docker {
    async fn start(
        &self,
        spec: &RunnerSpec,
        isolation: &dyn Isolation,
    ) -> Result<String, StartError> {
        let options = CreateContainerOptionsBuilder::new()
            .name(&spec.name)
            .build();
        let id = match self
            .api
            .create_container(Some(options), create_body(spec, isolation))
            .await
        {
            Ok(created) => created.id,
            Err(error) if refused(&error) => {
                return Err(StartError {
                    container: None,
                    may_have_run: false,
                    error,
                });
            }
            // Docker may have made it and lost the answer: its name, unique to this start, finds it.
            Err(error) => {
                let made = match self.api.inspect_container(&spec.name, None).await {
                    Ok(found) => Some(found.id.unwrap_or_else(|| spec.name.clone())),
                    Err(missing) if is_not_found(&missing) => None,
                    Err(_) => Some(spec.name.clone()),
                };
                // Made at most, never started.
                return Err(self.clean_up(made, error, false).await);
            }
        };
        let uploaded = async {
            if let Some(jit_config) = &spec.jit_config {
                let options = UploadToContainerOptionsBuilder::new().path("/").build();
                let tar = jit_config_tar(jit_config)?;
                // As a stream: bollard traces a full body's bytes, but a stream only as "(stream)".
                let tar = futures_util::stream::once(std::future::ready(tar.into()));
                self.api
                    .upload_to_container(&id, Some(options), bollard::body_stream(tar))
                    .await?;
            }
            Ok::<(), Error>(())
        };
        if let Err(error) = uploaded.await {
            return Err(self.clean_up(Some(id), error, false).await);
        }
        // A start whose answer is lost may have started it.
        if let Err(error) = self.api.start_container(&id, None).await {
            return Err(self.clean_up(Some(id), error, true).await);
        }
        Ok(id)
    }

    async fn inspect(&self, container: &str) -> Result<RunnerState, Error> {
        let response = self.api.inspect_container(container, None).await?;
        let state = response.state.unwrap_or_default();
        let host_config = response.host_config.unwrap_or_default();
        let address = response
            .network_settings
            .and_then(|settings| settings.networks)
            .and_then(|networks| {
                networks
                    .into_values()
                    .find_map(|network| network.ip_address.filter(|address| !address.is_empty()))
            });
        Ok(RunnerState {
            running: state.running.unwrap_or(false),
            exit_code: state.exit_code,
            oom_killed: state.oom_killed.unwrap_or(false),
            privileged: host_config.privileged.unwrap_or(false),
            runtime: host_config.runtime,
            pid: state
                .pid
                .and_then(|pid| u32::try_from(pid).ok())
                .filter(|pid| *pid > 0),
            address,
            started_at: state.started_at.as_deref().and_then(crate::time::parse_ms),
            // Docker says 0001-01-01 for one that never stopped, which reads as none.
            finished_at: state.finished_at.as_deref().and_then(crate::time::parse_ms),
            memory: host_config
                .memory
                .and_then(|memory| u64::try_from(memory).ok())
                .filter(|memory| *memory > 0),
            cpus: host_config
                .nano_cpus
                .and_then(|nano| u64::try_from(nano / 1_000_000).ok())
                .filter(|cpus| *cpus > 0),
        })
    }

    async fn remove(&self, container: &str) -> Result<(), Error> {
        // With its anonymous volumes, such as a shell's /state.
        let options = RemoveContainerOptionsBuilder::new()
            .force(true)
            .v(true)
            .build();
        self.api.remove_container(container, Some(options)).await
    }

    async fn run(&self, name: &str, body: ContainerCreateBody) -> Result<String, Error> {
        let options = CreateContainerOptionsBuilder::new().name(name).build();
        let id = self.api.create_container(Some(options), body).await?.id;
        if let Err(error) = self.api.start_container(&id, None).await {
            let _ = self.remove(&id).await;
            return Err(error);
        }
        Ok(id)
    }

    async fn list(&self, label: &str) -> Result<Vec<Container>, Error> {
        self.containers("label", label).await
    }

    async fn holders(&self, volume: &str) -> Result<Vec<Container>, Error> {
        self.containers("volume", volume).await
    }

    fn exits(&self) -> BoxStream<'static, Result<String, Error>> {
        let filters = HashMap::from([
            ("type", vec!["container"]),
            ("event", vec!["die"]),
            ("label", vec!["runnerd.job"]),
        ]);
        let options = EventsOptionsBuilder::new().filters(&filters).build();
        self.api
            .events(Some(options))
            .try_filter_map(|event| std::future::ready(Ok(event.actor.and_then(|actor| actor.id))))
            .boxed()
    }

    async fn wait(&self, container: &str) -> Result<i64, Error> {
        let options = WaitContainerOptionsBuilder::new()
            .condition("not-running")
            .build();
        let mut responses = self.api.wait_container(container, Some(options));
        match responses.next().await {
            Some(Ok(response)) => Ok(response.status_code),
            // Bollard reports a non-zero exit as an error.
            Some(Err(Error::DockerContainerWaitError { code, .. })) => Ok(code),
            Some(Err(error)) => Err(error),
            None => Ok(0),
        }
    }

    async fn logs(&self, container: &str) -> Result<String, Error> {
        let options = LogsOptionsBuilder::new().stdout(true).stderr(true).build();
        let chunks: Vec<_> = self
            .api
            .logs(container, Some(options))
            .try_collect()
            .await?;
        Ok(chunks.iter().map(ToString::to_string).collect())
    }

    async fn logs_since(&self, container: &str, since: u64) -> Result<String, Error> {
        let options = LogsOptionsBuilder::new()
            .stdout(true)
            .stderr(true)
            .timestamps(true)
            .since(i32::try_from(since).unwrap_or(i32::MAX))
            .build();
        let chunks: Vec<_> = self
            .api
            .logs(container, Some(options))
            .try_collect()
            .await?;
        Ok(chunks.iter().map(ToString::to_string).collect())
    }

    async fn exec(&self, container: &str, command: Vec<String>) -> Result<Output, Error> {
        let options = CreateExecOptions {
            cmd: Some(command),
            user: Some("root".to_owned()),
            attach_stdout: Some(true),
            attach_stderr: Some(true),
            ..Default::default()
        };
        let exec = self.api.create_exec(container, options).await?;
        match self.api.start_exec(&exec.id, None).await? {
            StartExecResults::Attached { output, .. } => Ok(output
                .try_filter_map(|output| {
                    std::future::ready(Ok(match output {
                        bollard::container::LogOutput::StdOut { message } => Some(message.to_vec()),
                        _ => None,
                    }))
                })
                .boxed()),
            StartExecResults::Detached => Ok(futures_util::stream::empty().boxed()),
        }
    }

    async fn image_present(&self, image: &str) -> Result<bool, Error> {
        Ok(self.image_labels(image).await?.is_some())
    }

    async fn image_skips_syncs(&self, image: &str) -> Result<bool, Error> {
        Ok(self
            .image_labels(image)
            .await?
            .is_some_and(|labels| skips_syncs(&labels)))
    }

    async fn pull(&self, image: &str) -> Result<(), Error> {
        let options = CreateImageOptionsBuilder::new().from_image(image).build();
        let mut stream = self.api.create_image(Some(options), None, None);
        let mut progress = PullProgress::default();
        let mut logged = Instant::now();
        info!("pulling {image}");
        while let Some(update) = stream.try_next().await? {
            progress.update(&update);
            if logged.elapsed() >= PULL_LOG_INTERVAL {
                logged = Instant::now();
                info!("pulling {image}: {progress}");
            }
        }
        info!("pulled {image}");
        Ok(())
    }

    async fn ensure_network(&self, name: &str) -> Result<(), Error> {
        match self.api.inspect_network(name, None).await {
            Err(error) if is_not_found(&error) => {
                let request = NetworkCreateRequest {
                    name: name.to_owned(),
                    driver: Some("bridge".to_owned()),
                    ..Default::default()
                };
                self.api.create_network(request).await.map(|_| ())
            }
            other => other.map(|_| ()),
        }
    }

    async fn ensure_volume(&self, name: &str) -> Result<(), Error> {
        // Creating a volume that exists is a no-op in Docker.
        let request = VolumeCreateRequest {
            name: Some(name.to_owned()),
            ..Default::default()
        };
        self.api.create_volume(request).await.map(|_| ())
    }

    async fn remove_volume(&self, name: &str) -> Result<(), Error> {
        let options = RemoveVolumeOptionsBuilder::new().build();
        match self.api.remove_volume(name, Some(options)).await {
            Err(error) if is_not_found(&error) => Ok(()),
            other => other,
        }
    }

    async fn volumes(&self, prefix: &str) -> Result<Vec<String>, Error> {
        // Docker's name filter matches anywhere in the name; the prefix is checked here.
        let options = ListVolumesOptionsBuilder::new()
            .filters(&HashMap::from([("name", vec![prefix])]))
            .build();
        Ok(self
            .api
            .list_volumes(Some(options))
            .await?
            .volumes
            .unwrap_or_default()
            .into_iter()
            .map(|volume| volume.name)
            .filter(|name| name.starts_with(prefix))
            .collect())
    }

    async fn volume_sizes(&self) -> Result<BTreeMap<String, u64>, Error> {
        // Without a type filter: bollard cannot encode one in the query.
        let options = DataUsageOptionsBuilder::new().verbose(true).build();
        let usage = self.api.df(Some(options)).await?;
        // API 1.53 leaves the items untyped; they are volumes as `GET /volumes` describes them.
        Ok(usage
            .volume_usage
            .and_then(|volumes| volumes.items)
            .unwrap_or_default()
            .into_iter()
            .filter_map(|volume| {
                let name = volume.get("Name")?.as_str()?.to_owned();
                let size = volume.get("UsageData")?.get("Size")?.as_u64()?;
                Some((name, size))
            })
            .collect())
    }

    async fn changes(&self, container: &str) -> Result<Vec<String>, Error> {
        Ok(self
            .api
            .container_changes(container)
            .await?
            .unwrap_or_default()
            .into_iter()
            .filter(|change| change.kind != ChangeType::_2)
            .map(|change| change.path)
            .collect())
    }

    async fn written(&self, container: &str) -> Result<u64, Error> {
        let options = InspectContainerOptionsBuilder::new().size(true).build();
        let response = self.api.inspect_container(container, Some(options)).await?;
        Ok(response
            .size_rw
            .and_then(|bytes| u64::try_from(bytes).ok())
            .unwrap_or(0))
    }

    async fn files(&self, container: &str, directory: &str, prefix: &str) -> Result<Files, Error> {
        let options = DownloadFromContainerOptionsBuilder::new()
            .path(directory)
            .build();
        let mut archive = self.api.download_from_container(container, Some(options));
        // The archive is read as it arrives, by a blocking reader, so what it skips is never held.
        let (chunks, received) = tokio::sync::mpsc::channel(4);
        let prefix = prefix.to_owned();
        let reader = tokio::task::spawn_blocking(move || {
            files_in(
                Chunks {
                    received,
                    chunk: Vec::new(),
                    at: 0,
                },
                &prefix,
            )
        });
        let mut failed = None;
        while let Some(chunk) = archive.next().await {
            match chunk {
                // Fails once the reader is done, at the archive's end or `FILES_LIMIT`.
                Ok(chunk) => {
                    if chunks.send(chunk.to_vec()).await.is_err() {
                        break;
                    }
                }
                Err(error) => {
                    failed = Some(error);
                    break;
                }
            }
        }
        drop(chunks);
        let files = match reader.await {
            Ok(files) => files,
            Err(error) => match error.try_into_panic() {
                Ok(panic) => std::panic::resume_unwind(panic),
                // Only while the runtime shuts down.
                Err(_) => Files::default(),
            },
        };
        match failed {
            Some(error) => Err(error),
            None => Ok(files),
        }
    }

    async fn commit(
        &self,
        container: &str,
        reference: &str,
        labels: BTreeMap<String, String>,
    ) -> Result<u64, Error> {
        let (repository, tag) = reference.rsplit_once(':').unwrap_or((reference, "latest"));
        let options = CommitContainerOptionsBuilder::new()
            .container(container)
            .repo(repository)
            .tag(tag)
            .pause(false)
            .build();
        let config = ContainerConfig {
            labels: Some(labels.into_iter().collect()),
            ..Default::default()
        };
        // The image the container runs is the record's parent.
        let parent = match self.api.inspect_container(container, None).await?.image {
            Some(parent) => self.api.inspect_image(&parent).await?.size.unwrap_or(0),
            None => 0,
        };
        let id = self.api.commit_container(options, config).await?.id;
        let size = self.api.inspect_image(&id).await?.size.unwrap_or(0);
        Ok(u64::try_from(size - parent).unwrap_or(0))
    }

    async fn images(&self, label: &str) -> Result<Vec<Image>, Error> {
        let options = ListImagesOptionsBuilder::new()
            .filters(&HashMap::from([("label", vec![label])]))
            .build();
        let images = self.api.list_images(Some(options)).await?;
        let mut parents: HashMap<String, i64> = HashMap::new();
        let mut found = Vec::new();
        for image in images {
            let parent = if image.parent_id.is_empty() {
                0
            } else if let Some(size) = parents.get(&image.parent_id) {
                *size
            } else {
                let size = self
                    .api
                    .inspect_image(&image.parent_id)
                    .await
                    .ok()
                    .and_then(|parent| parent.size)
                    .unwrap_or(0);
                parents.insert(image.parent_id.clone(), size);
                size
            };
            found.push(Image {
                reference: image.repo_tags.into_iter().next().unwrap_or(image.id),
                labels: image.labels,
                bytes: u64::try_from(image.size - parent).unwrap_or(0),
            });
        }
        Ok(found)
    }

    async fn image_id(&self, reference: &str) -> Result<Option<String>, Error> {
        match self.api.inspect_image(reference).await {
            Ok(inspect) => Ok(inspect.id),
            Err(error) if is_not_found(&error) => Ok(None),
            Err(error) => Err(error),
        }
    }

    async fn tagged_images(&self) -> Result<Vec<TaggedImage>, Error> {
        let images = self
            .api
            .list_images(Some(ListImagesOptionsBuilder::new().build()))
            .await?;
        Ok(images
            .into_iter()
            .map(|image| TaggedImage {
                id: image.id,
                tags: image
                    .repo_tags
                    .into_iter()
                    .filter(|tag| tag != "<none>:<none>")
                    .collect(),
                digests: image
                    .repo_digests
                    .into_iter()
                    .filter(|digest| digest != "<none>@<none>")
                    .collect(),
            })
            .filter(|image| !image.tags.is_empty())
            .collect())
    }

    async fn container_images(&self) -> Result<BTreeSet<String>, Error> {
        let options = ListContainersOptionsBuilder::new().all(true).build();
        let containers = self.api.list_containers(Some(options)).await?;
        Ok(containers
            .into_iter()
            .filter_map(|container| container.image_id)
            .collect())
    }

    async fn remove_image(&self, reference: &str) -> Result<(), Error> {
        let options = RemoveImageOptionsBuilder::new().build();
        match self.api.remove_image(reference, Some(options), None).await {
            Err(error) if is_not_found(&error) => Ok(()),
            other => other.map(|_| ()),
        }
    }

    async fn root_dir(&self) -> Result<String, Error> {
        Ok(self.api.info().await?.docker_root_dir.unwrap_or_default())
    }

    async fn free_space(&self) -> Result<u64, Error> {
        let root = self.api.info().await?.docker_root_dir.unwrap_or_default();
        // Only the directories above Docker's root need to be searchable: the daemon's user cannot read the root.
        let statfs = |path: &std::path::Path| {
            let stat = rustix::fs::statvfs(path).map_err(std::io::Error::from)?;
            Ok(stat.f_bavail.saturating_mul(stat.f_frsize))
        };
        let paths = crate::observe::metrics::Paths::default();
        crate::observe::disk::free_space(&paths, std::path::Path::new(&root), statfs).map_err(
            |error| Error::IOError {
                err: std::io::Error::other(format!("cannot measure the disk of {root}: {error}")),
            },
        )
    }

    async fn shell(
        &self,
        name: &str,
        body: ContainerCreateBody,
        size: TtySize,
    ) -> Result<Tty, Error> {
        let options = CreateContainerOptionsBuilder::new().name(name).build();
        let id = self.api.create_container(Some(options), body).await?.id;
        let attached = async {
            let options = AttachContainerOptionsBuilder::new()
                .stream(true)
                .stdin(true)
                .stdout(true)
                .stderr(true)
                .build();
            let attached = self.api.attach_container(&id, Some(options)).await?;
            self.api.start_container(&id, None).await?;
            let resize = ResizeContainerTTYOptionsBuilder::new()
                .w(i32::from(size.cols))
                .h(i32::from(size.rows))
                .build();
            self.api.resize_container_tty(&id, resize).await?;
            Ok::<_, Error>(attached)
        };
        match attached.await {
            Ok(attached) => Ok(Tty {
                container: id,
                output: attached
                    .output
                    .map_ok(|output| output.into_bytes().to_vec())
                    .boxed(),
                input: attached.input,
            }),
            Err(error) => {
                let _ = self.remove(&id).await;
                Err(error)
            }
        }
    }
}

/// How often `pull` logs its progress.
const PULL_LOG_INTERVAL: Duration = Duration::from_secs(10);

/// A pull's layers so far, from the statuses Docker streams per layer.
#[derive(Debug, Default)]
struct PullProgress {
    layers: BTreeMap<String, Layer>,
}

#[derive(Debug, Default)]
struct Layer {
    downloaded: u64,
    size: u64,
    done: bool,
}

impl PullProgress {
    fn update(&mut self, update: &CreateImageInfo) {
        let (Some(id), Some(status)) = (&update.id, &update.status) else {
            return;
        };
        let bytes = |value: Option<i64>| value.and_then(|value| u64::try_from(value).ok());
        let detail = update.progress_detail.as_ref();
        match status.as_str() {
            "Pulling fs layer" | "Waiting" => {
                self.layers.entry(id.clone()).or_default();
            }
            "Downloading" => {
                let layer = self.layers.entry(id.clone()).or_default();
                layer.downloaded =
                    bytes(detail.and_then(|detail| detail.current)).unwrap_or(layer.downloaded);
                layer.size = bytes(detail.and_then(|detail| detail.total)).unwrap_or(layer.size);
            }
            "Download complete" => {
                if let Some(layer) = self.layers.get_mut(id) {
                    layer.downloaded = layer.size;
                }
            }
            "Pull complete" | "Already exists" => {
                let layer = self.layers.entry(id.clone()).or_default();
                layer.downloaded = layer.size;
                layer.done = true;
            }
            _ => {}
        }
    }
}

impl fmt::Display for PullProgress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let done = self.layers.values().filter(|layer| layer.done).count();
        let downloaded: u64 = self.layers.values().map(|layer| layer.downloaded).sum();
        let size: u64 = self.layers.values().map(|layer| layer.size).sum();
        write!(
            f,
            "{done} of {} layers done, {} of {} downloaded",
            self.layers.len(),
            ByteSize(downloaded),
            ByteSize(size)
        )
    }
}

fn connect_to(docker_host: Option<&str>) -> Result<Docker, Error> {
    let api = match docker_host.filter(|host| !host.is_empty()) {
        None => bollard::Docker::connect_with_socket_defaults()?,
        Some(host) if host.starts_with("unix://") => {
            bollard::Docker::connect_with_socket(host, 120, bollard::API_DEFAULT_VERSION)?
        }
        // Bollard would quietly fall back to the local socket: a different Engine than the one asked for.
        Some(host) => {
            return Err(Error::UnsupportedURISchemeError {
                uri: host.to_owned(),
            });
        }
    };
    Ok(Docker { api })
}

/// A tar archive, to extract at `/`, holding the config as a root-only file at `JIT_CONFIG_PATH`.
/// The chunks of an archive as they arrive, for a blocking reader: it ends when no more come.
struct Chunks {
    received: tokio::sync::mpsc::Receiver<Vec<u8>>,
    chunk: Vec<u8>,
    at: usize,
}

impl std::io::Read for Chunks {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        while self.at == self.chunk.len() {
            match self.received.blocking_recv() {
                Some(chunk) => {
                    self.chunk = chunk;
                    self.at = 0;
                }
                None => return Ok(0),
            }
        }
        let n = buf.len().min(self.chunk.len() - self.at);
        buf[..n].copy_from_slice(&self.chunk[self.at..self.at + n]);
        self.at += n;
        Ok(n)
    }
}

/// A reader that notes whether its last read found the end: `tar` reads past a zero block, the archive's end, no
/// further, and takes running out between entries as the end too.
struct Ends<R> {
    inner: R,
    ran_out: bool,
}

impl<R: std::io::Read> std::io::Read for Ends<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.ran_out = n == 0 && !buf.is_empty();
        Ok(n)
    }
}

/// The regular files at the top of a directory's `tar` whose names start with `prefix`. Docker roots the archive at
/// the directory's own name. Every other entry is read through and dropped, so only the files kept count against
/// `FILES_LIMIT`. Complete only once the archive's end marker is read: one that breaks off, between entries too, or
/// a file cut at the limit is not; what was read is kept.
pub(crate) fn files_in(tar: impl std::io::Read, prefix: &str) -> Files {
    let mut tar = Ends {
        inner: tar,
        ran_out: false,
    };
    let mut read = Files::default();
    let ended = files_until_end(&mut tar, prefix, &mut read.files);
    read.complete = ended && !tar.ran_out;
    read
}

/// Reads `tar` into `files` as `files_in` says; whether it got to the archive's end, which `files_in` checks was its
/// marker.
fn files_until_end(tar: impl std::io::Read, prefix: &str, files: &mut Vec<File>) -> bool {
    let mut archive = tar::Archive::new(tar);
    let Ok(entries) = archive.entries() else {
        return false;
    };
    let mut kept = 0;
    for entry in entries {
        let Ok(mut entry) = entry else {
            return false;
        };
        let name = match entry.path() {
            Ok(path) if path.components().count() == 2 => path
                .file_name()
                .map(|name| name.to_string_lossy().into_owned()),
            _ => None,
        };
        let Some(name) =
            name.filter(|name| name.starts_with(prefix) && entry.header().entry_type().is_file())
        else {
            continue;
        };
        let room = FILES_LIMIT - kept;
        let mut contents = Vec::new();
        // One byte past the room tells a file cut at the limit from one that fits it exactly.
        let whole = std::io::Read::read_to_end(
            &mut std::io::Read::take(&mut entry, room as u64 + 1),
            &mut contents,
        )
        .is_ok()
            && contents.len() <= room;
        contents.truncate(room);
        kept += contents.len();
        files.push(File {
            name,
            contents: String::from_utf8_lossy(&contents).into_owned(),
        });
        if !whole {
            return false;
        }
    }
    true
}

fn jit_config_tar(jit_config: &JitConfig) -> std::io::Result<Vec<u8>> {
    let mut tar = tar::Builder::new(Vec::new());
    let path = JIT_CONFIG_PATH.trim_start_matches('/');
    let mut dir = tar::Header::new_gnu();
    dir.set_entry_type(tar::EntryType::Directory);
    dir.set_mode(0o700);
    dir.set_size(0);
    tar.append_data(
        &mut dir,
        path.rsplit_once('/').map_or("", |(dir, _)| dir),
        std::io::empty(),
    )?;
    let mut file = tar::Header::new_gnu();
    file.set_mode(0o400);
    file.set_size(jit_config.0.len() as u64);
    tar.append_data(&mut file, path, jit_config.0.as_bytes())?;
    tar.into_inner()
}

#[cfg(test)]
pub(crate) mod tests;