Skip to main content

zlayer_types/api/
containers.rs

1//! Raw container lifecycle API DTOs.
2//!
3//! Wire-format types shared between the daemon's `/api/v1/containers`
4//! endpoints and SDK clients. Moved out of `zlayer-api` so SDK crates can
5//! depend on them without pulling in the full server stack.
6
7use std::collections::HashMap;
8
9use serde::{Deserialize, Serialize};
10use utoipa::{IntoParams, ToSchema};
11
12/// Inline serde shim for `Option<Duration>` ↔ humantime strings.
13///
14/// Mirrors the `duration::option` module in `spec/types.rs` so the request
15/// types here can accept the same wire format (e.g. `"30s"`, `"500ms"`,
16/// `"1m"`) as the spec's [`crate::spec::ServiceSpec::stop_grace_period`]
17/// without taking on a `humantime_serde` dependency.
18mod duration_opt {
19    use humantime::format_duration;
20    use serde::{Deserialize, Deserializer, Serializer};
21    use std::time::Duration;
22
23    #[allow(clippy::ref_option)]
24    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
25    where
26        S: Serializer,
27    {
28        match duration {
29            Some(d) => serializer.serialize_str(&format_duration(*d).to_string()),
30            None => serializer.serialize_none(),
31        }
32    }
33
34    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
35    where
36        D: Deserializer<'de>,
37    {
38        use serde::de::Error;
39        let s: Option<String> = Option::deserialize(deserializer)?;
40        match s {
41            Some(s) => humantime::parse_duration(&s)
42                .map(Some)
43                .map_err(|e| D::Error::custom(format!("invalid duration: {e}"))),
44            None => Ok(None),
45        }
46    }
47}
48
49/// Resource limits for a container
50#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
51pub struct ContainerResourceLimits {
52    /// CPU limit in cores (e.g., 0.5, 1.0, 2.0)
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub cpu: Option<f64>,
55    /// Memory limit (e.g., "256Mi", "1Gi")
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub memory: Option<String>,
58}
59
60/// Volume mount kind discriminator.
61///
62/// Selects which [`zlayer_spec::StorageSpec`] variant [`VolumeMount`] is
63/// translated into by [`build_service_spec`]. When omitted on the wire,
64/// defaults to [`VolumeMountType::Bind`] (legacy behavior).
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
66#[serde(rename_all = "snake_case")]
67pub enum VolumeMountType {
68    /// Host-path bind mount. `source` is an absolute host path.
69    Bind,
70    /// Named persistent volume. `source` is the volume name (managed by
71    /// `/api/v1/volumes`), not a host path.
72    Volume,
73    /// Memory-backed tmpfs mount. `source` must be empty/omitted.
74    Tmpfs,
75}
76
77/// Volume mount specification.
78///
79/// The `type` field (a Docker-compatible discriminator) selects how `source`
80/// is interpreted:
81/// - `"bind"` (default): `source` is an absolute host path.
82/// - `"volume"`: `source` is a named-volume identifier.
83/// - `"tmpfs"`: no `source`; a memory-backed mount is provisioned.
84#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
85pub struct VolumeMount {
86    /// Mount kind. Omit (or `"bind"`) for legacy host-path binds.
87    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
88    pub mount_type: Option<VolumeMountType>,
89    /// Host path (bind), volume name (volume), or unused (tmpfs).
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub source: Option<String>,
92    /// Container mount path
93    pub target: String,
94    /// Mount as read-only
95    #[serde(default)]
96    pub readonly: bool,
97}
98
99/// Container health check request.
100///
101/// Mirrors the on-disk `HealthCheck` enum (see `zlayer_spec::HealthCheck`) as a
102/// discriminated union keyed on `type`. Translated to `zlayer_spec::HealthSpec`
103/// by `HealthCheckRequest::to_health_spec`. Durations are humantime strings
104/// (for example `"10s"`, `"500ms"`, `"1m"`).
105///
106/// ## Variants
107/// - `type: "tcp"` — requires `port` (1-65535).
108/// - `type: "http"` — requires `url`; `expect_status` defaults to 200.
109/// - `type: "command"` — requires `command` (array of argv tokens; joined with
110///   spaces and passed to `sh -c` by the health monitor, matching the existing
111///   compose-to-ZLayer conversion in `zlayer-docker`).
112#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
113pub struct HealthCheckRequest {
114    /// Check variant: `"tcp"`, `"http"`, or `"command"`.
115    #[serde(rename = "type")]
116    pub check_type: String,
117    /// TCP port (required when `type == "tcp"`).
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub port: Option<u16>,
120    /// HTTP URL (required when `type == "http"`).
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub url: Option<String>,
123    /// HTTP status code expected from `url` (defaults to 200).
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub expect_status: Option<u16>,
126    /// Command argv (required when `type == "command"`). Joined with spaces
127    /// and passed to `sh -c`.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub command: Option<Vec<String>>,
130    /// Interval between checks, humantime format (e.g. `"30s"`). Defaults to 30s.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub interval: Option<String>,
133    /// Timeout per individual check, humantime format.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub timeout: Option<String>,
136    /// Number of consecutive failures before marking unhealthy. Defaults to 3.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub retries: Option<u32>,
139    /// Grace period before the first check runs, humantime format. Maps to
140    /// `HealthSpec::start_grace`.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub start_period: Option<String>,
143}
144
145/// Request to create and start a container
146#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
147pub struct CreateContainerRequest {
148    /// OCI image reference (e.g., "nginx:latest", "ubuntu:22.04")
149    pub image: String,
150    /// Optional human-readable name
151    #[serde(default)]
152    pub name: Option<String>,
153    /// Image pull policy: "always", "`if_not_present`", or "never"
154    #[serde(default)]
155    pub pull_policy: Option<String>,
156    /// Environment variables
157    #[serde(default)]
158    pub env: HashMap<String, String>,
159    /// Command to run (overrides image entrypoint)
160    #[serde(default)]
161    pub command: Option<Vec<String>>,
162    /// Labels for filtering and grouping
163    #[serde(default)]
164    pub labels: HashMap<String, String>,
165    /// Resource limits (CPU, memory)
166    #[serde(default)]
167    pub resources: Option<ContainerResourceLimits>,
168    /// Volume mounts
169    #[serde(default)]
170    pub volumes: Vec<VolumeMount>,
171    /// Published ports (Docker's `-p host:container/proto`). When omitted,
172    /// the container is created without any host port publishing.
173    #[serde(default, skip_serializing_if = "Vec::is_empty")]
174    pub ports: Vec<crate::spec::PortMapping>,
175    /// Working directory inside the container
176    #[serde(default)]
177    pub work_dir: Option<String>,
178    /// Optional health check. When omitted, the daemon installs a no-op
179    /// placeholder (`HealthCheck::Tcp { port: 0 }`) matching the current
180    /// default; the health monitor treats `port == 0` as "skip".
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub health_check: Option<HealthCheckRequest>,
183    /// Optional container hostname (maps to Docker's `--hostname`).
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub hostname: Option<String>,
186    /// Additional DNS servers (maps to Docker's `--dns`). Each entry must be
187    /// a plausible IPv4 or IPv6 address.
188    #[serde(default, skip_serializing_if = "Vec::is_empty")]
189    pub dns: Vec<String>,
190    /// Extra `hostname:ip` entries appended to `/etc/hosts` (maps to Docker's
191    /// `--add-host`). The special literal `host-gateway` is accepted as the
192    /// `ip` half.
193    #[serde(default, skip_serializing_if = "Vec::is_empty")]
194    pub extra_hosts: Vec<String>,
195    /// Container restart policy (Docker-style). When omitted, the runtime
196    /// applies no explicit restart policy (Docker default: `"no"`).
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub restart_policy: Option<crate::spec::ContainerRestartPolicy>,
199    /// User-defined bridge/overlay networks to attach the newly-created
200    /// container to. Each entry references a network by id or name and is
201    /// attached after the container is successfully started. If any
202    /// attachment fails, the partially-started container is rolled back
203    /// (stopped + removed) and the request is failed.
204    #[serde(default, skip_serializing_if = "Vec::is_empty")]
205    pub networks: Vec<NetworkAttachmentRequest>,
206    // -- §3.10: registry auth ------------------------------------------------
207    /// Id of a persisted registry credential (from
208    /// `POST /api/v1/credentials/registry`) to use when pulling the image.
209    /// Ignored when [`Self::registry_auth`] is also supplied (inline auth
210    /// wins). Requires the daemon to be configured with a credential store
211    /// — otherwise the request is rejected with `400`.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub registry_credential_id: Option<String>,
214    /// Inline Docker/OCI registry credentials used for this pull only. Not
215    /// persisted, never logged, never echoed back on a response. When both
216    /// `registry_credential_id` and `registry_auth` are set, this field
217    /// takes precedence.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub registry_auth: Option<crate::spec::RegistryAuth>,
220
221    // -- Docker lifecycle / security ----------------------------------------
222    /// Run the container in privileged mode (Docker `--privileged`). When
223    /// omitted, defaults to `false`.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub privileged: Option<bool>,
226    /// Linux capabilities to add (Docker `--cap-add`). Maps to
227    /// `ServiceSpec::capabilities`.
228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
229    pub cap_add: Vec<String>,
230    /// Linux capabilities to drop (Docker `--cap-drop`).
231    #[serde(default, skip_serializing_if = "Vec::is_empty")]
232    pub cap_drop: Vec<String>,
233    /// Host devices to expose to the container (Docker `--device`).
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub devices: Vec<crate::spec::DeviceSpec>,
236    /// Network mode (Docker `--network`). Accepts `"default"`, `"host"`,
237    /// `"none"`, `"bridge"`, `"bridge:<name>"`, or `"container:<id>"`. When
238    /// omitted, defaults to [`crate::spec::NetworkMode::Default`].
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub network_mode: Option<crate::spec::NetworkMode>,
241    /// Security options such as `apparmor=...`, `seccomp=...`,
242    /// `no-new-privileges:true` (Docker `--security-opt`).
243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
244    pub security_opt: Vec<String>,
245    /// PID namespace mode (Docker `--pid`). Accepts e.g. `"host"` or
246    /// `"container:<id>"`.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub pid_mode: Option<String>,
249    /// IPC namespace mode (Docker `--ipc`). Accepts e.g. `"host"`,
250    /// `"shareable"`, `"private"`, or `"container:<id>"`.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub ipc_mode: Option<String>,
253    /// Mount the container's root filesystem read-only (Docker `--read-only`).
254    #[serde(default)]
255    pub read_only_root_fs: bool,
256    /// Run a Docker-supplied init process (PID 1) inside the container
257    /// (Docker `--init`). Distinct from `ZLayer`'s pre-start init actions.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub init_container: Option<bool>,
260
261    // -- Docker metadata ----------------------------------------------------
262    /// User and group override for the container's main process
263    /// (Docker `--user uid:gid`).
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub user: Option<String>,
266    /// Signal sent to the container's main process to request a graceful
267    /// shutdown (Docker `--stop-signal`). Accepts e.g. `"SIGTERM"` or `"15"`.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub stop_signal: Option<String>,
270    /// Grace period to wait between the stop signal and a forced kill
271    /// (Docker `--stop-timeout`). Wire format is a humantime string
272    /// (e.g. `"30s"`, `"500ms"`, `"1m"`).
273    #[serde(
274        default,
275        with = "duration_opt",
276        skip_serializing_if = "Option::is_none"
277    )]
278    #[schema(value_type = Option<String>, example = "30s")]
279    pub stop_grace_period: Option<std::time::Duration>,
280    /// Kernel sysctl overrides (Docker `--sysctl`).
281    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
282    pub sysctls: HashMap<String, String>,
283    /// Per-process ulimits (Docker `--ulimit`).
284    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
285    pub ulimits: HashMap<String, crate::spec::UlimitSpec>,
286    /// Additional groups to add to the container process
287    /// (Docker `--group-add`).
288    #[serde(default, skip_serializing_if = "Vec::is_empty")]
289    pub extra_groups: Vec<String>,
290
291    // -- Docker resource knobs (folded into `ServiceSpec::resources`) -------
292    /// Maximum number of processes the container may spawn
293    /// (Docker `--pids-limit`).
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub pids_limit: Option<i64>,
296    /// CPUs that the container is allowed to execute on
297    /// (Docker `--cpuset-cpus`).
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub cpuset: Option<String>,
300    /// Relative CPU shares (Docker `--cpu-shares`). Default weight is 1024.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub cpu_shares: Option<u32>,
303    /// Total memory limit including swap (Docker `--memory-swap`).
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub memory_swap: Option<String>,
306    /// Soft memory limit (Docker `--memory-reservation`).
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub memory_reservation: Option<String>,
309    /// Container memory swappiness, 0-100 (Docker `--memory-swappiness`).
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub memory_swappiness: Option<u8>,
312    /// OOM-killer score adjustment (Docker `--oom-score-adj`).
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub oom_score_adj: Option<i32>,
315    /// Disable the OOM killer for the container (Docker `--oom-kill-disable`).
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub oom_kill_disable: Option<bool>,
318    /// Block IO weight, 10-1000 (Docker `--blkio-weight`).
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub blkio_weight: Option<u16>,
321
322    // -- Lifecycle ----------------------------------------------------------
323    /// Container lifecycle policy. Carries the `delete_on_exit` knob (Docker
324    /// `--rm` / `HostConfig.AutoRemove`) so the daemon can remove terminated
325    /// container records and bundles once they exit. Defaults to
326    /// [`crate::spec::LifecycleSpec::default()`] (i.e. retain on exit), which
327    /// matches the historical behavior for callers that omit the field.
328    #[serde(default)]
329    pub lifecycle: crate::spec::LifecycleSpec,
330}
331
332/// A request to attach a freshly-created container to a user-defined bridge
333/// or overlay network, mirroring the wire-shape used by `POST
334/// /api/v1/container-networks/{id_or_name}/connect`.
335///
336/// Included on [`CreateContainerRequest::networks`] so callers can wire up
337/// every attachment in a single call instead of issuing a separate connect
338/// request per network after container create.
339#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
340pub struct NetworkAttachmentRequest {
341    /// Bridge-network id or name to attach to.
342    pub network: String,
343    /// Optional DNS aliases for this container on the network.
344    #[serde(default, skip_serializing_if = "Vec::is_empty")]
345    pub aliases: Vec<String>,
346    /// Optional static IPv4 to pin this container to. Validated as
347    /// [`std::net::Ipv4Addr`] before the runtime is called.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub ipv4_address: Option<String>,
350}
351
352/// Container information returned by the API
353#[derive(Debug, Serialize, Deserialize, ToSchema)]
354pub struct ContainerInfo {
355    /// Container identifier
356    pub id: String,
357    /// Human-readable name (if set)
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub name: Option<String>,
360    /// OCI image reference
361    pub image: String,
362    /// Container state (pending, running, exited, failed)
363    pub state: String,
364    /// Labels
365    pub labels: HashMap<String, String>,
366    /// Creation timestamp (ISO 8601)
367    pub created_at: String,
368    /// Process ID (if running)
369    #[serde(skip_serializing_if = "Option::is_none")]
370    pub pid: Option<u32>,
371    // -- §3.15: rich inspect fields -----------------------------------------
372    /// Published port mappings (container → host). Populated from the
373    /// runtime's inspect response; empty when the runtime doesn't expose
374    /// port-level detail or the container has no published ports.
375    #[serde(default, skip_serializing_if = "Vec::is_empty")]
376    pub ports: Vec<crate::spec::PortMapping>,
377    /// Networks this container is attached to, with per-network aliases
378    /// and IPv4. Empty when the runtime doesn't surface network detail.
379    #[serde(default, skip_serializing_if = "Vec::is_empty")]
380    pub networks: Vec<NetworkAttachmentInfo>,
381    /// Primary IPv4 address (first non-empty IP across attached networks).
382    /// Docker's `bridge` network is preferred when present.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub ipv4: Option<String>,
385    /// Runtime-native health status, when the container image declares a
386    /// `HEALTHCHECK` (or equivalent). `None` when the runtime doesn't track
387    /// health for this container.
388    #[serde(default, skip_serializing_if = "Option::is_none")]
389    pub health: Option<ContainerHealthInfo>,
390    /// Most-recent exit code. `None` for containers still running and for
391    /// containers that have never exited.
392    #[serde(default, skip_serializing_if = "Option::is_none")]
393    pub exit_code: Option<i32>,
394}
395
396/// Per-network attachment entry on [`ContainerInfo::networks`].
397///
398/// Populated from the runtime's inspect response — mirrors the subset of
399/// bollard's `EndpointSettings` that API clients need to correlate a container
400/// with its `container_networks` entries.
401#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
402pub struct NetworkAttachmentInfo {
403    /// Network name as reported by the runtime. Matches the `name` field on
404    /// entries returned by `GET /api/v1/container-networks`.
405    pub network: String,
406    /// DNS aliases the container answers to on this network.
407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
408    pub aliases: Vec<String>,
409    /// Assigned IPv4 on this network, if any.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub ipv4: Option<String>,
412}
413
414/// Runtime-native health snapshot on [`ContainerInfo::health`].
415///
416/// Sourced from bollard's `ContainerState.health` for Docker-backed
417/// containers. The internal `HealthMonitor` in
418/// `crates/zlayer-agent/src/health.rs` drives service-level health events
419/// against user-configured health specs; for standalone containers the API
420/// reports the runtime-native status instead so images with a baked-in
421/// `HEALTHCHECK` still surface correctly.
422#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
423pub struct ContainerHealthInfo {
424    /// One of `"none"`, `"starting"`, `"healthy"`, `"unhealthy"` (Docker
425    /// `HealthStatusEnum`). Empty / missing upstream values normalise to
426    /// `"none"`.
427    pub status: String,
428    /// Consecutive failing probe count, when the runtime tracks it.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub failing_streak: Option<u32>,
431    /// Output from the most recent failing probe, when available.
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub last_output: Option<String>,
434}
435
436/// Query parameters for listing containers
437#[derive(Debug, Deserialize, IntoParams)]
438pub struct ListContainersQuery {
439    /// Filter by label (key=value format)
440    #[serde(default)]
441    pub label: Option<String>,
442}
443
444/// Query parameters for container logs.
445///
446/// Mirrors the Docker Engine API `GET /containers/{id}/logs` query string so
447/// the streaming handler can pass options through to
448/// [`zlayer_agent::runtime::Runtime::logs_stream`] with minimal translation.
449#[derive(Debug, Default, Deserialize, IntoParams)]
450pub struct ContainerLogQuery {
451    /// Number of tail lines to return. `0` and "all" map to "everything
452    /// available"; otherwise the runtime ships the last `tail` lines before
453    /// the live stream begins.
454    #[serde(default = "default_tail")]
455    pub tail: usize,
456    /// Follow logs after the current end-of-buffer marker.
457    #[serde(default)]
458    pub follow: bool,
459    /// Earliest log timestamp to include (Unix seconds). `None` means no
460    /// lower bound.
461    #[serde(default)]
462    pub since: Option<i64>,
463    /// Latest log timestamp to include (Unix seconds). `None` means no upper
464    /// bound.
465    #[serde(default)]
466    pub until: Option<i64>,
467    /// When `true`, the runtime is asked to populate per-chunk timestamps so
468    /// the wire-format includes them.
469    #[serde(default)]
470    pub timestamps: bool,
471    /// Include stdout chunks. When neither `stdout` nor `stderr` is set, the
472    /// handler defaults both to `true` (Docker parity).
473    #[serde(default)]
474    pub stdout: Option<bool>,
475    /// Include stderr chunks. See [`ContainerLogQuery::stdout`] for the
476    /// "neither set" default behavior.
477    #[serde(default)]
478    pub stderr: Option<bool>,
479    /// Wire format for the streamed body. `"json"` (the default) emits one
480    /// NDJSON `LogChunk` per line; `"raw"` emits Docker's multiplexed stdcopy
481    /// frames (`application/vnd.docker.raw-stream`).
482    #[serde(default)]
483    pub format: Option<ContainerLogFormat>,
484}
485
486/// Wire format for [`ContainerLogQuery::format`].
487#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
488#[serde(rename_all = "lowercase")]
489pub enum ContainerLogFormat {
490    /// Newline-delimited JSON, one `LogChunk` per line. The default.
491    #[default]
492    Json,
493    /// Docker multiplexed stdcopy framing.
494    Raw,
495}
496
497fn default_tail() -> usize {
498    100
499}
500
501/// Exec request for running a command in a container
502#[derive(Debug, Deserialize, ToSchema)]
503pub struct ContainerExecRequest {
504    /// Command and arguments to execute
505    pub command: Vec<String>,
506}
507
508/// Query parameters for the exec endpoint.
509///
510/// When `stream=true` the handler returns a Server-Sent Events stream with
511/// one `stdout` / `stderr` event per line of output and a final `exit` event
512/// carrying the exit code as JSON. When `stream=false` (the default) the
513/// handler buffers the whole output and returns a single JSON
514/// [`ContainerExecResponse`] body.
515#[derive(Debug, Default, Deserialize, IntoParams)]
516pub struct ExecQuery {
517    /// Stream exec events as SSE instead of returning a buffered JSON body.
518    #[serde(default)]
519    pub stream: bool,
520}
521
522/// Exec response with command output
523#[derive(Debug, Serialize, Deserialize, ToSchema)]
524pub struct ContainerExecResponse {
525    /// Exit code from the command
526    pub exit_code: i32,
527    /// Standard output
528    pub stdout: String,
529    /// Standard error
530    pub stderr: String,
531}
532
533/// Request body for stopping a container. Matches the Docker-compat
534/// `POST /containers/{id}/stop` shape.
535#[derive(Debug, Default, Deserialize, ToSchema)]
536pub struct StopContainerRequest {
537    /// Graceful shutdown timeout in seconds before the runtime force-kills
538    /// the container. Defaults to 30 seconds when omitted.
539    #[serde(default)]
540    pub timeout: Option<u64>,
541}
542
543/// Request body for restarting a container. Matches the Docker-compat
544/// `POST /containers/{id}/restart` shape.
545#[derive(Debug, Default, Deserialize, ToSchema)]
546pub struct RestartContainerRequest {
547    /// Graceful shutdown timeout in seconds before the runtime force-kills
548    /// the container. Defaults to 30 seconds when omitted.
549    #[serde(default)]
550    pub timeout: Option<u64>,
551}
552
553/// Request body for killing (sending a signal to) a container. Matches the
554/// Docker-compat `POST /containers/{id}/kill` shape.
555#[derive(Debug, Default, Deserialize, ToSchema)]
556pub struct KillContainerRequest {
557    /// Signal name to send (e.g. `"SIGTERM"`, `"SIGINT"`). Accepts both the
558    /// `SIG`-prefixed and bare forms. When omitted, defaults to `SIGKILL`.
559    #[serde(default)]
560    pub signal: Option<String>,
561}
562
563/// Restart policy entry for [`ContainerUpdateRequest`].
564///
565/// Mirrors Docker's `HostConfig.RestartPolicy` shape so the Docker compat
566/// layer can pass the wire payload through unchanged. `name` accepts the
567/// same set of strings as `docker run --restart`: `""`, `"no"`, `"always"`,
568/// `"unless-stopped"`, or `"on-failure"`. `maximum_retry_count` is only
569/// honoured when `name == "on-failure"`.
570#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, PartialEq, Eq)]
571pub struct ContainerUpdateRestartPolicy {
572    /// `"no"`, `"always"`, `"unless-stopped"`, or `"on-failure"`.
573    #[serde(rename = "Name", default, skip_serializing_if = "Option::is_none")]
574    pub name: Option<String>,
575    /// Maximum number of retries before giving up (only used with
576    /// `on-failure`). When `0` or omitted, retries are unbounded.
577    #[serde(
578        rename = "MaximumRetryCount",
579        default,
580        skip_serializing_if = "Option::is_none"
581    )]
582    pub maximum_retry_count: Option<i64>,
583}
584
585/// Request body for `POST /api/v1/containers/{id}/update`.
586///
587/// Mirrors Docker Engine's `POST /containers/{id}/update` body 1:1 so the
588/// `zlayer-docker` compatibility shim can pass the wire payload straight
589/// through. Every field is optional — only the fields present on the wire
590/// are applied; unset fields are left untouched on the running container.
591///
592/// Field naming uses Docker's `PascalCase` on the wire (`CpuShares`,
593/// `Memory`, ...) and `snake_case` on the Rust side. Subset of the full
594/// Docker schema: `ZLayer` supports the resource knobs (cpu, memory, pids,
595/// blkio) plus `RestartPolicy`. Windows-only fields (`CpuCount`,
596/// `IOMaximumIOps`) and ulimits/devices are accepted on the wire but
597/// silently ignored by the Linux runtimes.
598#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, PartialEq, Eq)]
599pub struct ContainerUpdateRequest {
600    /// Relative CPU weight (cgroup `cpu.weight` or `cpu.shares`). Range
601    /// 2-262144 on cgroup v2; 2-262144 mapped from 1-10000 on v1.
602    #[serde(rename = "CpuShares", default, skip_serializing_if = "Option::is_none")]
603    pub cpu_shares: Option<i64>,
604
605    /// Memory limit in bytes. Set `0` to remove the limit.
606    #[serde(rename = "Memory", default, skip_serializing_if = "Option::is_none")]
607    pub memory: Option<i64>,
608
609    /// CPU CFS period in microseconds.
610    #[serde(rename = "CpuPeriod", default, skip_serializing_if = "Option::is_none")]
611    pub cpu_period: Option<i64>,
612
613    /// CPU CFS quota in microseconds. Together with `cpu_period` defines
614    /// the fraction of a CPU the container may use.
615    #[serde(rename = "CpuQuota", default, skip_serializing_if = "Option::is_none")]
616    pub cpu_quota: Option<i64>,
617
618    /// CPU real-time period in microseconds.
619    #[serde(
620        rename = "CpuRealtimePeriod",
621        default,
622        skip_serializing_if = "Option::is_none"
623    )]
624    pub cpu_realtime_period: Option<i64>,
625
626    /// CPU real-time runtime in microseconds.
627    #[serde(
628        rename = "CpuRealtimeRuntime",
629        default,
630        skip_serializing_if = "Option::is_none"
631    )]
632    pub cpu_realtime_runtime: Option<i64>,
633
634    /// CPUs allowed for execution (e.g. `"0-3"`, `"0,1"`).
635    #[serde(
636        rename = "CpusetCpus",
637        default,
638        skip_serializing_if = "Option::is_none"
639    )]
640    pub cpuset_cpus: Option<String>,
641
642    /// Memory nodes (NUMA) allowed for execution (e.g. `"0-3"`).
643    #[serde(
644        rename = "CpusetMems",
645        default,
646        skip_serializing_if = "Option::is_none"
647    )]
648    pub cpuset_mems: Option<String>,
649
650    /// Soft memory limit in bytes. The kernel reclaims pages above this
651    /// reservation when the host comes under memory pressure.
652    #[serde(
653        rename = "MemoryReservation",
654        default,
655        skip_serializing_if = "Option::is_none"
656    )]
657    pub memory_reservation: Option<i64>,
658
659    /// Total memory limit (memory + swap) in bytes. `-1` removes the swap
660    /// limit, matching Docker semantics.
661    #[serde(
662        rename = "MemorySwap",
663        default,
664        skip_serializing_if = "Option::is_none"
665    )]
666    pub memory_swap: Option<i64>,
667
668    /// Kernel memory limit in bytes (deprecated upstream; accepted for
669    /// wire compatibility).
670    #[serde(
671        rename = "KernelMemory",
672        default,
673        skip_serializing_if = "Option::is_none"
674    )]
675    pub kernel_memory: Option<i64>,
676
677    /// Block IO weight (relative weight, range 10-1000).
678    #[serde(
679        rename = "BlkioWeight",
680        default,
681        skip_serializing_if = "Option::is_none"
682    )]
683    pub blkio_weight: Option<u16>,
684
685    /// PIDs limit. Set `0` or `-1` for unlimited.
686    #[serde(rename = "PidsLimit", default, skip_serializing_if = "Option::is_none")]
687    pub pids_limit: Option<i64>,
688
689    /// New restart policy. When present, replaces the container's stored
690    /// restart policy. Docker applies this asynchronously: the next time
691    /// the supervisor decides whether to restart, it consults the new
692    /// policy.
693    #[serde(
694        rename = "RestartPolicy",
695        default,
696        skip_serializing_if = "Option::is_none"
697    )]
698    pub restart_policy: Option<ContainerUpdateRestartPolicy>,
699}
700
701/// Response body for `POST /api/v1/containers/{id}/update`.
702///
703/// Mirrors Docker's `{"Warnings": [...]}` shape so the compat layer
704/// passes the body through verbatim. `Warnings` is always present (even
705/// if empty) for wire compatibility with clients that match the field
706/// presence, not just its contents.
707#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
708pub struct ContainerUpdateResponse {
709    /// Human-readable warnings emitted by the runtime while applying the
710    /// update — e.g. `"kernel memory limit is deprecated"`.
711    #[serde(rename = "Warnings", default)]
712    pub warnings: Vec<String>,
713}
714
715/// Wait response with container exit code plus optional classification
716/// fields (added in §3.12 of the SDK-fixes spec).
717///
718/// The three optional fields (`reason`, `signal`, `finished_at`) are
719/// additive — clients that only read `exit_code` keep working unchanged.
720#[derive(Debug, Serialize, Deserialize, ToSchema)]
721pub struct ContainerWaitResponse {
722    /// Container identifier
723    pub id: String,
724    /// Exit code (0 = success). When the container was killed by signal
725    /// `N`, this is typically `128 + N`.
726    pub exit_code: i32,
727    /// Classification of the exit. One of `"exited"`, `"signal"`,
728    /// `"oom_killed"`, or `"runtime_error"`. Absent when the runtime
729    /// didn't classify the exit.
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub reason: Option<String>,
732    /// Signal name when `reason == "signal"`, e.g. `"SIGKILL"`. Absent
733    /// when the runtime couldn't determine it (or the exit wasn't a
734    /// signal death).
735    #[serde(default, skip_serializing_if = "Option::is_none")]
736    pub signal: Option<String>,
737    /// RFC3339 timestamp of when the container exited, if reported by
738    /// the runtime.
739    #[serde(default, skip_serializing_if = "Option::is_none")]
740    pub finished_at: Option<String>,
741}
742
743/// Docker-shaped wait response returned by
744/// `POST /api/v1/containers/{id}/wait`.
745///
746/// Mirrors Docker Engine's `/containers/{id}/wait` body 1:1: a
747/// `StatusCode` field plus an optional `Error` envelope. Used by the
748/// `zlayer-docker` compatibility shim and any SDK callers that consume
749/// the Docker shape directly. The richer
750/// [`ContainerWaitResponse`] (returned by the legacy `GET` endpoint) is
751/// preserved for clients that need the `reason` / `signal` / `finished_at`
752/// classification fields.
753#[derive(Debug, Serialize, Deserialize, ToSchema)]
754pub struct ContainerWaitDockerResponse {
755    /// Container exit code (0 = success). When killed by signal `N`,
756    /// this is typically `128 + N`, matching Docker's convention.
757    #[serde(rename = "StatusCode")]
758    pub status_code: i64,
759    /// Optional error envelope surfaced when the wait itself failed
760    /// (e.g. the container was removed before reaching `not-running`
761    /// when `condition=not-running` was requested). Absent on a normal
762    /// exit.
763    #[serde(rename = "Error", default, skip_serializing_if = "Option::is_none")]
764    pub error: Option<ContainerWaitDockerError>,
765}
766
767/// Error envelope nested inside [`ContainerWaitDockerResponse`].
768#[derive(Debug, Serialize, Deserialize, ToSchema)]
769pub struct ContainerWaitDockerError {
770    /// Human-readable description of why the wait failed.
771    #[serde(rename = "Message")]
772    pub message: String,
773}
774
775/// Query parameters for `POST /api/v1/containers/{id}/wait` —
776/// Docker's `condition=` query string.
777#[derive(Debug, Default, Deserialize, IntoParams)]
778pub struct WaitContainerQuery {
779    /// One of `"not-running"` (default), `"next-exit"`, or `"removed"`.
780    /// Matches Docker's `/containers/{id}/wait` semantics. Omitted
781    /// values default to `"not-running"`.
782    #[serde(default)]
783    pub condition: Option<String>,
784}
785
786/// Query parameters for `POST /api/v1/containers/{id}/rename` —
787/// Docker's `name=<new-name>` query string.
788#[derive(Debug, Default, Deserialize, IntoParams)]
789pub struct RenameContainerQuery {
790    /// New human-readable name to assign to the container. Required.
791    #[serde(default)]
792    pub name: Option<String>,
793}
794
795/// Container resource statistics
796#[derive(Debug, Serialize, Deserialize, ToSchema)]
797pub struct ContainerStatsResponse {
798    /// Container identifier
799    pub id: String,
800    /// CPU usage in microseconds
801    pub cpu_usage_usec: u64,
802    /// Current memory usage in bytes
803    pub memory_bytes: u64,
804    /// Memory limit in bytes (`u64::MAX` if unlimited)
805    pub memory_limit: u64,
806    /// Memory usage as percentage of limit
807    pub memory_percent: f64,
808}
809
810/// Query parameters for container stats.
811///
812/// When `stream=false` (default), the handler returns a single JSON
813/// [`ContainerStatsResponse`]. When `stream=true`, the handler switches to
814/// Server-Sent Events and emits one `ContainerStatsResponse` sample per
815/// `interval` seconds until the container exits or the client disconnects.
816///
817/// `interval` is clamped to `[1, 60]` seconds. Default interval is `2`.
818#[derive(Debug, Default, Deserialize, IntoParams)]
819pub struct StatsQuery {
820    /// Stream periodic samples as SSE events instead of a one-shot JSON
821    /// response.
822    #[serde(default)]
823    pub stream: bool,
824    /// Sample cadence in seconds (only used when `stream=true`). Clamped to
825    /// `[1, 60]`. Defaults to `2` seconds.
826    #[serde(default, alias = "interval_seconds")]
827    pub interval: Option<u32>,
828}
829
830/// Query parameters for `GET /api/v1/containers/{id}/top` —
831/// Docker's `ps_args=<...>` query string. Defaults to the runtime's
832/// own column set when omitted or empty.
833#[derive(Debug, Default, Deserialize, IntoParams)]
834pub struct ContainerTopQuery {
835    /// `ps`-style argument string, e.g. `"aux"` or `"-eo pid,user,cmd"`.
836    /// Empty / omitted means "use the runtime's defaults".
837    #[serde(default)]
838    pub ps_args: Option<String>,
839}
840
841/// Response body for `GET /api/v1/containers/{id}/top` (Docker compat shape).
842///
843/// Wire field names use Docker's `Titles` / `Processes` casing so the
844/// shim can pass the body through untouched.
845#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
846pub struct ContainerTopResponse {
847    /// `ps` column titles — e.g. `["UID", "PID", "PPID", "C", "STIME",
848    /// "TTY", "TIME", "CMD"]`.
849    #[serde(rename = "Titles")]
850    pub titles: Vec<String>,
851    /// One row per process inside the container. Each row has the same
852    /// length as `titles`.
853    #[serde(rename = "Processes")]
854    pub processes: Vec<Vec<String>>,
855}
856
857/// One row of `GET /api/v1/containers/{id}/changes` (Docker compat shape).
858///
859/// Mirrors Docker's `{"Path": "/foo", "Kind": 0}` body:
860/// `Kind` is a numeric enum where `0 = Modified`, `1 = Added`, `2 = Deleted`.
861#[derive(Debug, Serialize, Deserialize, ToSchema)]
862pub struct ContainerChangeEntry {
863    /// Path inside the container that changed (absolute, e.g. `/etc/hosts`).
864    #[serde(rename = "Path")]
865    pub path: String,
866    /// `0` = Modified, `1` = Added, `2` = Deleted (Docker's wire integer).
867    #[serde(rename = "Kind")]
868    pub kind: u8,
869}
870
871/// Response body for `GET /api/v1/containers/{id}/port` (Docker compat shape).
872///
873/// Mirrors Docker's `{"Ports": {"80/tcp": [{"HostIp":"...","HostPort":"..."}]}}`
874/// body. Each key is `<container_port>/<protocol>` and the value is the list
875/// of host bindings for that port (or `null` when the port is exposed but not
876/// published).
877#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
878pub struct ContainerPortResponse {
879    /// Map of `"<port>/<protocol>"` to host bindings.
880    #[serde(rename = "Ports")]
881    pub ports: HashMap<String, Option<Vec<ContainerPortBinding>>>,
882}
883
884/// One host binding inside a [`ContainerPortResponse`] entry.
885#[derive(Debug, Serialize, Deserialize, ToSchema)]
886pub struct ContainerPortBinding {
887    /// Host IP that maps to the container port. Empty / `"0.0.0.0"` means
888    /// "any IPv4 address".
889    #[serde(rename = "HostIp", default, skip_serializing_if = "Option::is_none")]
890    pub host_ip: Option<String>,
891    /// Host port (always serialised as a string in Docker's wire format).
892    #[serde(rename = "HostPort", default, skip_serializing_if = "Option::is_none")]
893    pub host_port: Option<String>,
894}
895
896/// Response body for `POST /api/v1/containers/prune` (Docker compat shape).
897///
898/// Docker uses `ContainersDeleted` / `SpaceReclaimed` `PascalCase` fields, so
899/// SDK consumers (and the docker shim) can read the body verbatim.
900#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]
901pub struct ContainerPruneResponse {
902    /// Container IDs that were removed.
903    #[serde(rename = "ContainersDeleted")]
904    pub containers_deleted: Vec<String>,
905    /// Bytes reclaimed from the runtime's container storage.
906    #[serde(rename = "SpaceReclaimed")]
907    pub space_reclaimed: u64,
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913    use crate::spec::{DeviceSpec, NetworkMode, UlimitSpec};
914    use std::time::Duration;
915
916    /// Build a baseline request with only the required `image` field so each
917    /// round-trip test can override exactly the slice of fields it cares
918    /// about without listing the dozens of unrelated optional fields.
919    fn baseline_request() -> CreateContainerRequest {
920        CreateContainerRequest {
921            image: "nginx:latest".to_string(),
922            ..CreateContainerRequest::default()
923        }
924    }
925
926    #[test]
927    fn create_request_round_trips_security_fields() {
928        let mut req = baseline_request();
929        req.privileged = Some(true);
930        req.cap_add = vec!["NET_ADMIN".to_string(), "SYS_PTRACE".to_string()];
931        req.cap_drop = vec!["MKNOD".to_string()];
932        req.devices = vec![DeviceSpec {
933            path: "/dev/kvm".to_string(),
934            read: true,
935            write: true,
936            mknod: false,
937        }];
938        req.network_mode = Some(NetworkMode::Host);
939        req.security_opt = vec!["no-new-privileges:true".to_string()];
940        req.pid_mode = Some("host".to_string());
941        req.ipc_mode = Some("shareable".to_string());
942        req.read_only_root_fs = true;
943        req.init_container = Some(true);
944
945        let json = serde_json::to_string(&req).expect("serialize");
946        let back: CreateContainerRequest =
947            serde_json::from_str(&json).expect("deserialize round-trip");
948
949        assert_eq!(back.privileged, Some(true));
950        assert_eq!(back.cap_add, vec!["NET_ADMIN", "SYS_PTRACE"]);
951        assert_eq!(back.cap_drop, vec!["MKNOD"]);
952        assert_eq!(back.devices.len(), 1);
953        assert_eq!(back.devices[0].path, "/dev/kvm");
954        assert!(back.devices[0].read);
955        assert!(back.devices[0].write);
956        assert!(!back.devices[0].mknod);
957        assert_eq!(back.network_mode, Some(NetworkMode::Host));
958        assert_eq!(back.security_opt, vec!["no-new-privileges:true"]);
959        assert_eq!(back.pid_mode.as_deref(), Some("host"));
960        assert_eq!(back.ipc_mode.as_deref(), Some("shareable"));
961        assert!(back.read_only_root_fs);
962        assert_eq!(back.init_container, Some(true));
963    }
964
965    #[test]
966    fn create_request_round_trips_metadata_fields() {
967        let mut req = baseline_request();
968        req.labels.insert("env".to_string(), "prod".to_string());
969        req.labels.insert("team".to_string(), "core".to_string());
970        req.user = Some("1000:1000".to_string());
971        req.stop_signal = Some("SIGTERM".to_string());
972        req.stop_grace_period = Some(Duration::from_secs(45));
973        req.sysctls
974            .insert("net.core.somaxconn".to_string(), "1024".to_string());
975        req.ulimits.insert(
976            "nofile".to_string(),
977            UlimitSpec {
978                soft: 4096,
979                hard: 8192,
980            },
981        );
982        req.extra_groups = vec!["docker".to_string(), "audio".to_string()];
983
984        let json = serde_json::to_string(&req).expect("serialize");
985        // Confirm the humantime wire format is a string.
986        assert!(
987            json.contains("\"stop_grace_period\":\"45s\""),
988            "expected humantime stop_grace_period in JSON, got: {json}"
989        );
990
991        let back: CreateContainerRequest =
992            serde_json::from_str(&json).expect("deserialize round-trip");
993
994        assert_eq!(back.labels.get("env").map(String::as_str), Some("prod"));
995        assert_eq!(back.labels.get("team").map(String::as_str), Some("core"));
996        assert_eq!(back.user.as_deref(), Some("1000:1000"));
997        assert_eq!(back.stop_signal.as_deref(), Some("SIGTERM"));
998        assert_eq!(back.stop_grace_period, Some(Duration::from_secs(45)));
999        assert_eq!(
1000            back.sysctls.get("net.core.somaxconn").map(String::as_str),
1001            Some("1024")
1002        );
1003        let nofile = back.ulimits.get("nofile").expect("nofile ulimit present");
1004        assert_eq!(nofile.soft, 4096);
1005        assert_eq!(nofile.hard, 8192);
1006        assert_eq!(back.extra_groups, vec!["docker", "audio"]);
1007    }
1008
1009    #[test]
1010    fn create_request_round_trips_resource_knobs() {
1011        let mut req = baseline_request();
1012        req.pids_limit = Some(2048);
1013        req.cpuset = Some("0-3".to_string());
1014        req.cpu_shares = Some(1024);
1015        req.memory_swap = Some("2Gi".to_string());
1016        req.memory_reservation = Some("256Mi".to_string());
1017        req.memory_swappiness = Some(10);
1018        req.oom_score_adj = Some(-500);
1019        req.oom_kill_disable = Some(false);
1020        req.blkio_weight = Some(500);
1021
1022        let json = serde_json::to_string(&req).expect("serialize");
1023        let back: CreateContainerRequest =
1024            serde_json::from_str(&json).expect("deserialize round-trip");
1025
1026        assert_eq!(back.pids_limit, Some(2048));
1027        assert_eq!(back.cpuset.as_deref(), Some("0-3"));
1028        assert_eq!(back.cpu_shares, Some(1024));
1029        assert_eq!(back.memory_swap.as_deref(), Some("2Gi"));
1030        assert_eq!(back.memory_reservation.as_deref(), Some("256Mi"));
1031        assert_eq!(back.memory_swappiness, Some(10));
1032        assert_eq!(back.oom_score_adj, Some(-500));
1033        assert_eq!(back.oom_kill_disable, Some(false));
1034        assert_eq!(back.blkio_weight, Some(500));
1035    }
1036
1037    #[test]
1038    fn create_request_round_trips_network_mode_strings() {
1039        // The spec's `NetworkMode` deserialization happens via
1040        // `deserialize_network_mode`, but that helper is only attached to
1041        // `ServiceSpec.network_mode` — at the request layer we want the
1042        // derived `Deserialize` for `NetworkMode` (lowercase enum) to
1043        // accept the same wire shapes. Confirm each of the five Docker
1044        // forms round-trips through the request body.
1045        //
1046        // Note: at the request layer, `network_mode` accepts the
1047        // externally-tagged enum form (e.g. `{"bridge": {"name": "..."}}`),
1048        // matching what the derived `Serialize` for `NetworkMode` emits.
1049        let cases: &[(&str, NetworkMode)] = &[
1050            (r#""default""#, NetworkMode::Default),
1051            (r#""host""#, NetworkMode::Host),
1052            (r#""none""#, NetworkMode::None),
1053            (
1054                r#"{"bridge":{"name":null}}"#,
1055                NetworkMode::Bridge { name: None },
1056            ),
1057            (
1058                r#"{"bridge":{"name":"custom_net"}}"#,
1059                NetworkMode::Bridge {
1060                    name: Some("custom_net".to_string()),
1061                },
1062            ),
1063            (
1064                r#"{"container":{"id":"abc"}}"#,
1065                NetworkMode::Container {
1066                    id: "abc".to_string(),
1067                },
1068            ),
1069        ];
1070
1071        for (literal, expected) in cases {
1072            let body = format!(r#"{{"image":"nginx:latest","network_mode":{literal}}}"#);
1073            let req: CreateContainerRequest = serde_json::from_str(&body)
1074                .unwrap_or_else(|e| panic!("deserialize {literal}: {e}"));
1075            assert_eq!(
1076                req.network_mode.as_ref(),
1077                Some(expected),
1078                "wire form {literal} did not round-trip",
1079            );
1080
1081            // Re-serialize and parse again to confirm the emitted form
1082            // also round-trips back into the same variant.
1083            let reser = serde_json::to_string(&req).expect("re-serialize");
1084            let again: CreateContainerRequest =
1085                serde_json::from_str(&reser).expect("re-deserialize");
1086            assert_eq!(again.network_mode.as_ref(), Some(expected));
1087        }
1088    }
1089
1090    /// `ContainerUpdateRequest` must accept Docker Engine's `PascalCase`
1091    /// wire shape verbatim (`CpuShares`, `Memory`, `RestartPolicy`, ...)
1092    /// and round-trip every documented field. This pins the contract
1093    /// `zlayer-docker` relies on when forwarding `POST /containers/{id}/update`.
1094    #[test]
1095    fn container_update_request_round_trips_docker_wire_shape() {
1096        let body = serde_json::json!({
1097            "CpuShares": 512,
1098            "Memory": 314_572_800_i64,
1099            "CpuPeriod": 100_000,
1100            "CpuQuota": 50_000,
1101            "CpuRealtimePeriod": 1_000_000,
1102            "CpuRealtimeRuntime": 950_000,
1103            "CpusetCpus": "0-3",
1104            "CpusetMems": "0,1",
1105            "MemoryReservation": 268_435_456_i64,
1106            "MemorySwap": 629_145_600_i64,
1107            "KernelMemory": 67_108_864_i64,
1108            "BlkioWeight": 500,
1109            "PidsLimit": 2048,
1110            "RestartPolicy": {
1111                "Name": "on-failure",
1112                "MaximumRetryCount": 5
1113            }
1114        });
1115
1116        let req: ContainerUpdateRequest =
1117            serde_json::from_value(body.clone()).expect("deserialize update body");
1118
1119        assert_eq!(req.cpu_shares, Some(512));
1120        assert_eq!(req.memory, Some(314_572_800));
1121        assert_eq!(req.cpu_period, Some(100_000));
1122        assert_eq!(req.cpu_quota, Some(50_000));
1123        assert_eq!(req.cpu_realtime_period, Some(1_000_000));
1124        assert_eq!(req.cpu_realtime_runtime, Some(950_000));
1125        assert_eq!(req.cpuset_cpus.as_deref(), Some("0-3"));
1126        assert_eq!(req.cpuset_mems.as_deref(), Some("0,1"));
1127        assert_eq!(req.memory_reservation, Some(268_435_456));
1128        assert_eq!(req.memory_swap, Some(629_145_600));
1129        assert_eq!(req.kernel_memory, Some(67_108_864));
1130        assert_eq!(req.blkio_weight, Some(500));
1131        assert_eq!(req.pids_limit, Some(2048));
1132        let rp = req.restart_policy.as_ref().expect("restart_policy");
1133        assert_eq!(rp.name.as_deref(), Some("on-failure"));
1134        assert_eq!(rp.maximum_retry_count, Some(5));
1135
1136        // Round-trip through the wire shape unchanged: every field must
1137        // serialize back with its PascalCase Docker name.
1138        let reser = serde_json::to_value(&req).expect("re-serialize");
1139        assert_eq!(reser, body);
1140    }
1141
1142    /// An empty body must deserialize successfully — Docker accepts
1143    /// `POST /containers/{id}/update` with `{}` (a no-op update).
1144    #[test]
1145    fn container_update_request_empty_body_deserializes_to_default() {
1146        let req: ContainerUpdateRequest =
1147            serde_json::from_str("{}").expect("empty body must deserialize");
1148        assert_eq!(req, ContainerUpdateRequest::default());
1149        assert!(req.cpu_shares.is_none());
1150        assert!(req.memory.is_none());
1151        assert!(req.restart_policy.is_none());
1152    }
1153
1154    /// `ContainerUpdateResponse` must always emit `Warnings` (even empty)
1155    /// so clients that match on field presence don't break.
1156    #[test]
1157    fn container_update_response_always_emits_warnings_field() {
1158        let resp = ContainerUpdateResponse::default();
1159        let json = serde_json::to_value(&resp).expect("serialize");
1160        assert!(json.get("Warnings").is_some(), "Warnings must be present");
1161        assert_eq!(json["Warnings"], serde_json::json!([]));
1162    }
1163}