foundation_deployment_docker 0.1.2

Docker Engine API v1.53 client over DynNetClient + valtron (bollard-free)
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
//! Hand-written `DockerClient` — Unix-socket transport, version negotiation, and
//! container lifecycle over the generated async `*_request` functions.
//!
//! WHY: The generator produces the raw per-endpoint calls, but the Docker-specific
//! glue — resolving the daemon socket, negotiating the API version, and the
//! create → start → wait → stop → remove lifecycle — is hand-written.
//!
//! WHAT: [`DockerClient`] built on `foundation_netio::DynNetClient` over a Unix
//! socket, plus P0 container operations.
//!
//! HOW: `HttpClientBuilder::new().unix_socket(path).build()` yields a
//! `DynNetClient`; each method calls the matching generated `async fn`.

use foundation_netio::shared::http::SimpleHeader;
use foundation_netio::{DynNetClient, HttpClientBuilder, PreparedRequestBuilder};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use crate::error::DockerError;
use crate::generated::auth::AuthResponse;
use crate::generated::containers::{container_delete_request, ContainerDeleteArgs};
use crate::generated::create::{container_create_request, ContainerCreateArgs, ContainerCreateResponse};
use crate::generated::json::{container_inspect_request, ContainerInspectArgs, ContainerInspectResponse};
use crate::generated::pause::{container_pause_request, ContainerPauseArgs};
use crate::generated::shared::{ApiError, IDResponse};
use crate::generated::start::{container_start_request, ContainerStartArgs};
use crate::generated::stop::{container_stop_request, ContainerStopArgs};
use crate::generated::unpause::{container_unpause_request, ContainerUnpauseArgs};
use crate::generated::version::{system_version_request, SystemVersion, SystemVersionArgs};
use crate::generated::wait::{container_wait_request, ContainerWaitArgs, ContainerWaitResponse};

/// Default Docker daemon Unix socket path.
pub const DEFAULT_DOCKER_SOCKET: &str = "/var/run/docker.sock";

/// The Docker Engine API version this client targets.
pub const DEFAULT_API_VERSION: &str = "1.53";

/// A closure type for the (empty) `builder_mod` argument — no request mutation.
pub(crate) type NoMod = fn(&mut PreparedRequestBuilder);

// ── Container create body (hand-written; the spec has this as an unnamed allOf) ─

/// The body of `POST /containers/create` — combines `ContainerConfig` with an
/// optional `HostConfig` (networking + resources) and `NetworkingConfig`.
///
/// The Docker Engine API spec models this as an unnamed `allOf` of
/// `ContainerConfig` + `{HostConfig, NetworkingConfig}`, so the code generator
/// can't give it a name. This hand-written struct fills the gap, using the
/// generated component types. Resource limits use [`ContainerHostConfig`] which
/// merges the generated `HostConfig` + `Resources` (the spec has them as one
/// object; the generator split them).
#[derive(Debug, Clone, Default, Serialize)]
pub struct ContainerCreateBody {
    // ── Flattened ContainerConfig fields (generated) ──
    #[serde(flatten)]
    pub config: crate::generated::json::ContainerConfig,

    /// Port bindings, volumes, capabilities PLUS CPU/memory/device limits.
    #[serde(
        rename = "HostConfig",
        skip_serializing_if = "Option::is_none"
    )]
    pub host_config: Option<ContainerHostConfig>,

    /// Per-network endpoint configuration (aliases, static IPs, MAC address).
    #[serde(
        rename = "NetworkingConfig",
        skip_serializing_if = "Option::is_none"
    )]
    pub networking_config: Option<NetworkingConfig>,
}

impl ContainerCreateBody {
    /// Create a minimal body with just the image set.
    #[must_use]
    pub fn new(image: impl Into<String>) -> Self {
        let mut config = crate::generated::json::ContainerConfig::default();
        config.image = Some(image.into());
        Self { config, host_config: None, networking_config: None }
    }

    /// Set the command to run in the container.
    #[must_use]
    pub fn with_cmd(mut self, cmd: Vec<String>) -> Self {
        self.config.cmd = Some(cmd);
        self
    }

    /// Add environment variables.
    #[must_use]
    pub fn with_env(mut self, env: Vec<(String, String)>) -> Self {
        self.config.env = Some(env.into_iter().map(|(k, v)| format!("{k}={v}")).collect());
        self
    }

    /// Set exposed ports (keys are `"port/proto"`, values are `{}` per Docker spec).
    #[must_use]
    pub fn with_exposed_ports(mut self, ports: serde_json::Value) -> Self {
        self.config.exposed_ports = Some(ports);
        self
    }

    /// Set container labels.
    #[must_use]
    pub fn with_labels(mut self, labels: serde_json::Value) -> Self {
        self.config.labels = Some(labels);
        self
    }

    /// Attach a host config (port bindings, binds, resources, capabilities).
    #[must_use]
    pub fn with_host_config(mut self, hc: ContainerHostConfig) -> Self {
        self.host_config = Some(hc);
        self
    }
}

/// Merged `HostConfig` + `Resources` for container creation.
///
/// The Docker Engine API spec defines `HostConfig` as a single object that
/// includes both networking/runtime fields and CPU/memory/device resource
/// limits. Our generated code splits them into two types (`HostConfig` and
/// `Resources`). This struct re-merges them for the `POST /containers/create`
/// body via `#[serde(flatten)]` — the field name sets (`PortBindings`, … and
/// `Memory`, `NanoCpus`, …) are disjoint, so the serialized JSON is correct.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ContainerHostConfig {
    /// Networking, runtime, security fields from `HostConfig`.
    #[serde(flatten)]
    pub base: crate::generated::json::HostConfig,
    /// CPU, memory, device resource limits from `Resources`.
    #[serde(flatten)]
    pub resources: crate::generated::json::Resources,
}

/// Container networking configuration — maps network names to endpoint settings.
///
/// Corresponds to the `NetworkingConfig` definition in the Docker Engine API spec.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NetworkingConfig {
    /// A mapping of network name to endpoint configuration for that network.
    #[serde(rename = "EndpointsConfig")]
    pub endpoints_config: std::collections::HashMap<String, crate::generated::connect::EndpointSettings>,
}

/// Container lifecycle operations (restart, kill, rename, resize, top, changes,
/// logs, stats, export, archive, attach, list, prune).
pub mod containers_lifecycle;

/// Network operations (list, inspect, create, delete, connect, disconnect, prune).
pub mod networks;

/// Volume operations (list, inspect, create, delete, update, prune).
pub mod volumes;

/// Image operations (list, inspect, tag, delete, search, history,
/// load, commit, prune, build, push, pull).
pub mod images;

/// Build contexts (tar streams) for `POST /build`.
pub mod build_context;

/// Exec instance operations (create, start, inspect, resize).
pub mod exec;

/// System operations (info, ping, events, data usage, auth).
/// (`version` lives directly on [`DockerClient`].)
pub mod system;

/// SSH transport (`ssh://user@host` via `docker system dial-stdio`).
///
/// Behind the `ssh` feature: it links libssh2/OpenSSL, which cannot share a
/// binary with the BoringSSL the `buildkit` feature pulls in.
#[cfg(feature = "ssh")]
pub mod ssh;

/// Docker daemon client over a Unix socket.
///
/// WHY: Talks to `dockerd` without bollard/tokio — a `DynNetClient` over the Unix
/// socket, driven by valtron.
///
/// WHAT: Holds the client handle, the socket path, and the negotiated API version.
///
/// HOW: Constructed via [`DockerClient::connect_unix`] /
/// [`DockerClient::connect_with_defaults`].
#[derive(Clone)]
pub struct DockerClient {
    http: DynNetClient,
    socket_path: PathBuf,
    api_version: String,
    /// Optional remote host:port for TCP connections (e.g. "192.168.1.10:2375").
    /// When `None`, the base URL uses `localhost` (the Unix-socket default).
    remote_host: Option<String>,
    /// Whether the transport is TLS — controls the `https://` vs `http://`
    /// scheme in [`Self::base_url`].
    tls: bool,
}

/// Mutual-TLS material for a remote Docker daemon (the `DOCKER_CERT_PATH`
/// `ca.pem` / `cert.pem` / `key.pem` trio).
#[derive(Clone)]
pub struct DockerTls {
    /// `ca.pem` — the CA that signed the daemon's cert. `None` uses the system
    /// roots (rarely what a private Docker CA wants).
    pub ca_pem: Option<Vec<u8>>,
    /// `cert.pem` — the client certificate presented to the daemon.
    pub cert_pem: Vec<u8>,
    /// `key.pem` — the client private key.
    pub key_pem: Vec<u8>,
    /// Verify the daemon's certificate against `ca_pem` (`DOCKER_TLS_VERIFY`).
    /// `false` accepts any server cert — encrypted but unauthenticated.
    pub verify: bool,
}

impl DockerTls {
    /// Load the `ca.pem` / `cert.pem` / `key.pem` trio from a `DOCKER_CERT_PATH`
    /// directory.
    ///
    /// # Errors
    ///
    /// Returns [`DockerError::Unavailable`] if `cert.pem` or `key.pem` cannot be
    /// read.
    pub fn from_cert_dir(dir: impl AsRef<Path>, verify: bool) -> Result<Self, DockerError> {
        let dir = dir.as_ref();
        let read = |name: &str| {
            std::fs::read(dir.join(name))
                .map_err(|e| DockerError::Unavailable(format!("read {name}: {e}")))
        };
        Ok(Self {
            ca_pem: std::fs::read(dir.join("ca.pem")).ok(),
            cert_pem: read("cert.pem")?,
            key_pem: read("key.pem")?,
            verify,
        })
    }
}

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

impl DockerClient {
    /// Connect to the Docker daemon over the given Unix socket path.
    ///
    /// WHY: The socket is Docker's default, TLS-free, permission-authenticated
    /// local transport.
    ///
    /// WHAT: Builds a `DynNetClient` routed over `socket_path`.
    ///
    /// HOW: `HttpClientBuilder::new().unix_socket(path).build()`.
    ///
    /// # Panics
    ///
    /// Never panics.
    #[must_use]
    pub fn connect_unix(socket_path: impl Into<PathBuf>) -> Self {
        let socket_path = socket_path.into();
        // Docker's blocking endpoints (stop, wait, restart) may not send
        // response headers for tens of seconds — 120 s covers the worst case.
        let http = HttpClientBuilder::new()
            .unix_socket(&socket_path)
            .read_timeout(std::time::Duration::from_secs(120))
            .build();
        Self {
            http,
            socket_path,
            api_version: DEFAULT_API_VERSION.to_string(),
            remote_host: None,
            tls: false,
        }
    }

    /// Connect via TCP to a remote Docker daemon (e.g. "192.168.1.10:2375").
    ///
    /// WHY: Docker daemons can be exposed over TCP (TLS or plaintext). This is the
    /// remote / non-localhost path. For a `--tlsverify` daemon use
    /// [`Self::connect_tls`].
    ///
    /// WHAT: Uses `HttpClientBuilder` default (TCP) + sets `remote_host` so
    /// [`Self::base_url`] generates the correct URL.
    #[must_use]
    pub fn connect_tcp(host: &str) -> Self {
        let socket_path = PathBuf::from(format!("tcp://{host}"));
        let http = HttpClientBuilder::new()
            .read_timeout(std::time::Duration::from_secs(120))
            .build();
        Self {
            http,
            socket_path,
            api_version: DEFAULT_API_VERSION.to_string(),
            remote_host: Some(host.to_string()),
            tls: false,
        }
    }

    /// Connect to a remote Docker daemon over **mutual TLS** (the standard
    /// `tcp://host:2376` + `DOCKER_CERT_PATH` setup).
    ///
    /// WHY: TCP-exposed daemons are normally protected with client-cert mTLS.
    ///
    /// WHAT: Builds a TLS connector from `tls` (client cert/key + CA) and dials
    /// `host` over `https://`.
    ///
    /// # Errors
    ///
    /// Returns [`DockerError::Unavailable`] if the certificate material is
    /// invalid.
    pub fn connect_tls(host: &str, tls: DockerTls) -> Result<Self, DockerError> {
        use foundation_netio::netcap::ssl::SSLConnector;

        let connector = SSLConnector::from_client_mutual_pem(
            tls.ca_pem.as_deref(),
            &tls.cert_pem,
            &tls.key_pem,
            tls.verify,
        )
        .map_err(|e| DockerError::Unavailable(format!("build TLS connector: {e}")))?;

        let http = HttpClientBuilder::new()
            .with_tls_connector(connector)
            .read_timeout(std::time::Duration::from_secs(120))
            .build();
        Ok(Self {
            http,
            socket_path: PathBuf::from(format!("tcp://{host}")),
            api_version: DEFAULT_API_VERSION.to_string(),
            remote_host: Some(host.to_string()),
            tls: true,
        })
    }

    /// Connect to a remote Docker daemon over **SSH** (`ssh://user@host[:port]`).
    ///
    /// WHY: SSH is Docker's port-less remote transport — it reuses an existing
    /// SSH login instead of exposing a TCP port or managing TLS certs.
    ///
    /// WHAT: SSHes in and runs `docker system dial-stdio`, whose stdio bridges to
    /// the remote `/var/run/docker.sock`. The client then speaks the ordinary
    /// Docker HTTP API over that channel (base URL `http://localhost`).
    ///
    /// HOW: Installs an [`ssh::SshConnector`] on the HTTP client via
    /// [`HttpClientBuilder::with_connector`]; each request opens a fresh
    /// `dial-stdio` channel (session reused across requests, channel not pooled).
    /// The target is resolved through `~/.ssh/config` (HostName/User/Port/
    /// IdentityFile), the server's key is checked against `~/.ssh/known_hosts`
    /// (trust-on-first-use), and auth follows OpenSSH order: agent, then the
    /// resolved/default `~/.ssh/id_*` keys — see [`foundation_sshkit::Host`].
    ///
    /// # Errors
    ///
    /// Never fails at construction (the SSH session is established lazily on the
    /// first request); returns [`DockerError`] only via later API calls.
    #[cfg(feature = "ssh")]
    pub fn connect_ssh(url: &str) -> Result<Self, DockerError> {
        use foundation_sshkit::Host;

        // `Host::resolve` accepts `[user@]alias[:port]` and layers in
        // `~/.ssh/config` (HostName/User/Port/IdentityFile) — strip the scheme first.
        let spec = url.strip_prefix("ssh://").unwrap_or(url);
        let host = Host::resolve(spec);
        let connector = std::sync::Arc::new(ssh::SshConnector::new(host));
        let http = HttpClientBuilder::new()
            .with_connector(connector)
            .read_timeout(std::time::Duration::from_secs(120))
            .build();
        Ok(Self {
            http,
            socket_path: PathBuf::from(url),
            api_version: DEFAULT_API_VERSION.to_string(),
            // dial-stdio bridges to the remote's *local* docker.sock — Host: localhost.
            remote_host: None,
            tls: false,
        })
    }

    /// Set a custom remote host (e.g. for Docker contexts, SSH tunnels).
    ///
    /// WHY: Lets callers use `connect_unix` then override the URL for cases
    /// where the socket path is correct but the Host header / URL must differ.
    #[must_use]
    pub fn with_remote_host(mut self, host: &str) -> Self {
        self.remote_host = Some(host.to_string());
        self
    }

    /// Connect using the default socket resolution.
    ///
    /// WHY: Most callers want the standard local daemon without specifying a path.
    ///
    /// WHAT: Uses `DOCKER_HOST` when it names a `unix://` socket, else
    /// [`DEFAULT_DOCKER_SOCKET`].
    ///
    /// HOW: Parses `DOCKER_HOST`; falls back to `/var/run/docker.sock`. A
    /// `tcp://` host with `DOCKER_TLS_VERIFY` set (or a `DOCKER_CERT_PATH` with
    /// certs) is dialed over mutual TLS via [`Self::connect_tls`]; a `tcp://`
    /// host without TLS env is plaintext [`Self::connect_tcp`]; an `ssh://` host
    /// is driven over `docker system dial-stdio` via [`Self::connect_ssh`].
    ///
    /// # Errors
    ///
    /// Returns [`DockerError::Unavailable`] if `DOCKER_HOST` names an unrecognized
    /// transport or if TLS material is invalid.
    pub fn connect_with_defaults() -> Result<Self, DockerError> {
        let host = std::env::var("DOCKER_HOST").unwrap_or_default();
        if host.is_empty() {
            return Ok(Self::connect_unix(DEFAULT_DOCKER_SOCKET));
        }
        if let Some(path) = host.strip_prefix("unix://") {
            return Ok(Self::connect_unix(path));
        }
        if let Some(addr) = host.strip_prefix("tcp://") {
            // TLS when DOCKER_TLS_VERIFY is set, or a DOCKER_CERT_PATH is given.
            let verify = std::env::var("DOCKER_TLS_VERIFY").is_ok_and(|v| v != "0" && !v.is_empty());
            let cert_dir = std::env::var("DOCKER_CERT_PATH").ok();
            if verify || cert_dir.is_some() {
                let dir = cert_dir.ok_or_else(|| {
                    DockerError::Unavailable(
                        "DOCKER_TLS_VERIFY set but DOCKER_CERT_PATH is missing".to_string(),
                    )
                })?;
                let tls = DockerTls::from_cert_dir(&dir, verify)?;
                return Self::connect_tls(addr, tls);
            }
            return Ok(Self::connect_tcp(addr));
        }
        if host.starts_with("ssh://") {
            #[cfg(feature = "ssh")]
            {
                return Self::connect_ssh(&host);
            }
            // Say so plainly rather than falling through to "unrecognized
            // transport", which would send the caller hunting for a typo in a
            // DOCKER_HOST that is in fact perfectly valid.
            #[cfg(not(feature = "ssh"))]
            {
                return Err(DockerError::Unavailable(format!(
                    "DOCKER_HOST is {host}, but this build has the `ssh` feature off — \
                     enable foundation_deployment_docker/ssh (note it cannot be combined \
                     with `buildkit`: libssh2/OpenSSL vs BoringSSL)"
                )));
            }
        }
        Err(DockerError::Unavailable(format!(
            "unrecognized DOCKER_HOST transport: {host}"
        )))
    }

    /// The cross-platform HTTP client handle (cheap `Arc` clone).
    #[must_use]
    pub fn http(&self) -> DynNetClient {
        self.http.clone()
    }

    /// The negotiated (or default) API version, e.g. `"1.53"`.
    #[must_use]
    pub fn api_version(&self) -> &str {
        &self.api_version
    }

    /// The base URL for API calls: `http://{host}/v{version}`.
    ///
    /// WHY: Generated functions take a `base_url: &str` so callers can point at
    /// remote Docker daemons over TCP, not just Unix-socket-local. Uses
    /// `remote_host` when set (via [`Self::connect_tcp`] or
    /// [`Self::with_remote_host`]), otherwise defaults to `localhost`.
    ///
    /// WHAT: `http://localhost/v1.53` for Unix-socket, `http://192.168.1.10:2375/v1.53`
    /// for remote.
    #[must_use]
    pub fn base_url(&self) -> String {
        let host = self.remote_host.as_deref().unwrap_or("localhost");
        let scheme = if self.tls { "https" } else { "http" };
        format!("{scheme}://{host}/v{}", self.api_version)
    }

    /// The Unix socket path this client dials.
    #[must_use]
    pub fn socket_path(&self) -> &std::path::Path {
        &self.socket_path
    }

    /// Fetch daemon version info (`GET /version`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn version(&self) -> Result<SystemVersion, DockerError> {
        let response =
            system_version_request(self.http(), &SystemVersionArgs::default(), &self.base_url(), None::<NoMod>)
                .await?;
        Ok(response.body)
    }

    /// Negotiate the effective API version with the daemon.
    ///
    /// WHY: The client and server may support different API versions; Docker
    /// negotiates the minimum common version.
    ///
    /// WHAT: Reads the daemon's `ApiVersion`; picks the lower of client/server.
    ///
    /// HOW: `GET /version` → compare with [`DEFAULT_API_VERSION`].
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn negotiate_version(&mut self) -> Result<(), DockerError> {
        let version = self.version().await?;
        if let Some(server) = version.api_version {
            // Both are dotted "major.minor"; the lexicographically-lower valid
            // version is the safe common denominator for our fixed client version.
            if version_lt(&server, &self.api_version) {
                self.api_version = server;
            }
        }
        Ok(())
    }

    /// Create a container (`POST /containers/create`).
    ///
    /// WHAT: Serializes `config` as the JSON body and returns the created
    /// container id + warnings.
    ///
    /// Accepts any `impl Serialize` — `serde_json::json!({...})` for quick inline
    /// configs, or [`ContainerCreateBody`] for typed construction.
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure, non-2xx status, or a config
    /// that cannot be serialized.
    pub async fn create_container(
        &self,
        config: &impl Serialize,
        name: Option<&str>,
    ) -> Result<ContainerCreateResponse, DockerError> {
        let json = serde_json::to_value(config)
            .map_err(|e| DockerError::JsonParse(format!("serialize container config: {e}")))?;
        let args = ContainerCreateArgs {
            name: name.map(str::to_string),
            platform: None,
        };
        let response = container_create_request(
            self.http(),
            &args,
            &self.base_url(),
            Some(move |b: &mut PreparedRequestBuilder| {
                b.set_header(SimpleHeader::CONTENT_TYPE, "application/json");
                let _ = b.set_body_json(&json);
            }),
        )
        .await?;
        Ok(response.body)
    }

    /// Start a container (`POST /containers/{id}/start`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn start_container(&self, id: &str) -> Result<(), DockerError> {
        let args = ContainerStartArgs {
            id: id.to_string(),
            detach_keys: None,
        };
        container_start_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(())
    }

    /// Wait for a container to reach a condition (`POST /containers/{id}/wait`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn wait_container(
        &self,
        id: &str,
        condition: Option<&str>,
    ) -> Result<ContainerWaitResponse, DockerError> {
        let args = ContainerWaitArgs {
            id: id.to_string(),
            condition: condition.map(str::to_string),
        };
        let response = container_wait_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(response.body)
    }

    /// Stop a container (`POST /containers/{id}/stop`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx/304 status.
    ///
    /// # Note
    ///
    /// Docker returns `304 Not Modified` when the container is already stopped
    /// (or never started). This is not an error — the desired state is reached.
    pub async fn stop_container(
        &self,
        id: &str,
        timeout_secs: Option<u32>,
    ) -> Result<(), DockerError> {
        let args = ContainerStopArgs {
            id: id.to_string(),
            signal: None,
            t: timeout_secs.map(|t| t.to_string()),
        };
        match container_stop_request(self.http(), &args, &self.base_url(), None::<NoMod>).await {
            Ok(_) => Ok(()),
            // Docker returns 304 when the container is already exited — not an error.
            Err(ApiError::HttpStatus { code: 304, .. }) => Ok(()),
            Err(e) => Err(e.into()),
        }
    }

    /// Remove a container (`DELETE /containers/{id}`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn remove_container(&self, id: &str, force: bool) -> Result<(), DockerError> {
        let args = ContainerDeleteArgs {
            id: id.to_string(),
            v: None,
            force: Some(force.to_string()),
            link: None,
        };
        container_delete_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(())
    }

    /// Inspect a container (`GET /containers/{id}/json`).
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn inspect_container(
        &self,
        id: &str,
    ) -> Result<ContainerInspectResponse, DockerError> {
        let args = ContainerInspectArgs {
            id: id.to_string(),
            size: None,
        };
        let response = container_inspect_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(response.body)
    }

    /// Pause a container (`POST /containers/{id}/pause`).
    ///
    /// WHY: Freezes all processes in the container via cgroups freezer.
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn pause_container(&self, id: &str) -> Result<(), DockerError> {
        let args = ContainerPauseArgs {
            id: id.to_string(),
        };
        container_pause_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(())
    }

    /// Unpause a container (`POST /containers/{id}/unpause`).
    ///
    /// WHY: Resumes a paused container.
    ///
    /// # Errors
    ///
    /// Returns [`DockerError`] on transport failure or non-2xx status.
    pub async fn unpause_container(&self, id: &str) -> Result<(), DockerError> {
        let args = ContainerUnpauseArgs {
            id: id.to_string(),
        };
        container_unpause_request(self.http(), &args, &self.base_url(), None::<NoMod>).await?;
        Ok(())
    }

    // ── Exec ───────────────────────────────────────────────────────────

    /// Create an exec instance in a running container (`POST /containers/{id}/exec`).
    ///
    /// Delegates to [`exec::exec_create`].
    pub async fn exec_create(&self, id: &str, cmd: &[&str]) -> Result<IDResponse, DockerError> {
        exec::exec_create(self, id, cmd).await
    }

    /// Start a previously-created exec instance (`POST /exec/{id}/start`).
    ///
    /// Delegates to [`exec::exec_start`].
    pub async fn exec_start(&self, id: &str, detach: bool) -> Result<Vec<u8>, DockerError> {
        exec::exec_start(self, id, detach).await
    }

    /// Inspect an exec instance (`GET /exec/{id}/json`).
    ///
    /// Delegates to [`exec::exec_inspect`].
    pub async fn exec_inspect(&self, id: &str) -> Result<serde_json::Value, DockerError> {
        exec::exec_inspect(self, id).await
    }

    /// Resize the TTY of an exec instance (`POST /exec/{id}/resize`).
    ///
    /// Delegates to [`exec::exec_resize`].
    pub async fn exec_resize(&self, id: &str, h: u32, w: u32) -> Result<(), DockerError> {
        exec::exec_resize(self, id, h, w).await
    }

    // ── System ─────────────────────────────────────────────────────────

    /// Get system information (`GET /info`).
    ///
    /// Delegates to [`system::system_info`].
    ///
    /// Returns `serde_json::Value` because Docker's `LocalNodeState` is a raw
    /// string (`"inactive"`) that the generated `SystemInfo` struct can't parse.
    pub async fn system_info(&self) -> Result<serde_json::Value, DockerError> {
        system::system_info(self).await
    }

    /// Ping the daemon (`GET /_ping`).
    ///
    /// Delegates to [`system::system_ping`].
    pub async fn system_ping(&self) -> Result<(), DockerError> {
        system::system_ping(self).await
    }

    /// Stream daemon events (`GET /events`).
    ///
    /// Delegates to [`system::system_events`].
    pub async fn system_events(
        &self,
        since: Option<&str>,
        until: Option<&str>,
        filters: Option<&str>,
    ) -> Result<Vec<u8>, DockerError> {
        system::system_events(self, since, until, filters).await
    }

    /// Get data usage information (`GET /system/df`).
    ///
    /// Delegates to [`system::system_data_usage`].
    pub async fn system_data_usage(&self, types: Option<&str>) -> Result<serde_json::Value, DockerError> {
        system::system_data_usage(self, types).await
    }

    /// Check auth configuration (`POST /auth`).
    ///
    /// Delegates to [`system::system_auth`].
    pub async fn system_auth(&self, username: &str, password: &str) -> Result<AuthResponse, DockerError> {
        system::system_auth(self, username, password).await
    }
}

/// Compare two dotted `"major.minor"` version strings, returning `true` when
/// `a < b`. Non-numeric components sort as 0.
///
/// # Panics
///
/// Never panics.
fn version_lt(a: &str, b: &str) -> bool {
    let parse = |s: &str| -> Vec<u32> {
        s.split('.').map(|p| p.parse().unwrap_or(0)).collect()
    };
    parse(a) < parse(b)
}