arcbox-docker 0.4.9

Docker REST API compatibility layer for ArcBox
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
use super::{
    extract_container_id, proxy_to_role, proxy_upgrade_to_role, require_amd64_runtime,
    resolve_container_role,
};
use crate::api::AppState;
use crate::error::{DockerError, Result};
use crate::proxy::{parse_port_bindings, proxy_to_guest_for_role};
use crate::routing::{UtilityVmRole, query_param, route_container_create};
use axum::body::Body;
use axum::extract::{OriginalUri, State};
use axum::http::{HeaderMap, Method, Request, Uri};
use axum::response::Response;
use bytes::Bytes;
use std::net::IpAddr;

crate::handlers::proxy_handler!(list_containers);
crate::handlers::proxy_handler!(prune_containers);
crate::handlers::container_proxy_handler!(inspect_container);
crate::handlers::container_proxy_handler!(container_logs);
crate::handlers::container_proxy_handler!(wait_container);
crate::handlers::container_proxy_handler!(pause_container);
crate::handlers::container_proxy_handler!(unpause_container);
crate::handlers::container_proxy_handler!(container_top);
crate::handlers::container_proxy_handler!(container_stats);
crate::handlers::container_proxy_handler!(container_changes);

/// Create a container, resolving macOS symlinks in bind-mount source paths.
///
/// On macOS, `/tmp` → `/private/tmp` and `/var` → `/private/var`. The guest
/// mounts host `/private` via VirtioFS while its `/tmp` and `/var` are
/// isolated tmpfs. This handler resolves the top-level symlink so
/// bind-mount paths land on the VirtioFS share.
///
/// ABX-375: every runtime container runs in the single HV utility VM.
/// `linux/amd64` is executed via FEX inside that VM; if FEX is not
/// provisioned in the guest, the request fails closed with a clear error
/// rather than silently routing to VZ/Rosetta or QEMU. Compose projects need
/// no cross-VM scheduling — all services share the one HV VM.
///
/// On a successful response the canonical container ID (and any `--name`) is
/// recorded so follow-up lifecycle calls resolve to the same VM.
pub async fn create_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let (parts, body) = req.into_parts();
    let body_bytes = http_body_util::BodyExt::collect(body)
        .await
        .map_err(|e| DockerError::Server(format!("failed to read body: {e}")))?
        .to_bytes();

    let body_bytes = crate::host_path::rewrite_create_body(body_bytes);
    let route = route_container_create(&uri, &body_bytes);
    let requested_name = query_param(&uri, "name").map(str::to_string);

    // Fail closed: amd64 runtime requires FEX in the HV guest. Never fall
    // back to a VZ/Rosetta runtime VM for a default amd64 container.
    require_amd64_runtime(&state, route).await?;

    // Runtime is single-VM; the workload always lands on the native HV VM.
    let role = route.utility_vm();
    tracing::debug!(
        backend = "hv",
        translator = route.translator.as_str(),
        platform = ?route.platform,
        name = requested_name.as_deref().unwrap_or(""),
        "routing Docker container create request"
    );
    let mut req = Request::from_parts(parts, Body::from(body_bytes));
    // Body may have changed size; remove Content-Length so the proxy
    // recomputes framing from the actual body.
    req.headers_mut().remove(axum::http::header::CONTENT_LENGTH);

    let response = proxy_to_role(&state, role, &uri, req).await?;
    if !response.status().is_success() {
        return Ok(response);
    }

    // Buffer the create response so the canonical container ID can be
    // recorded. Create responses are small JSON (just `Id` + `Warnings`),
    // so this does not affect streaming or memory behavior.
    let (parts, body) = response.into_parts();
    let body_bytes = http_body_util::BodyExt::collect(body)
        .await
        .map_err(|e| DockerError::Server(format!("failed to read create response: {e}")))?
        .to_bytes();

    if let Some(id) = parse_create_response_id(&body_bytes) {
        tracing::debug!(
            translator = route.translator.as_str(),
            container_id = %id,
            name = requested_name.as_deref().unwrap_or(""),
            "recorded container binding",
        );
        state.workload_roles.record(id.clone(), role).await;
        if let Some(name) = requested_name {
            state.workload_roles.add_alias(&id, name).await;
        }
    } else {
        tracing::warn!("create response missing container ID; lifecycle ops fall back to HV");
    }

    Ok(Response::from_parts(parts, Body::from(body_bytes)))
}

/// Start a container, then set up host-side port forwarding and DNS.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn start_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let container_id = extract_container_id(&uri);
    let role = resolve_container_role(&state, &uri).await?;

    // Proxy start request to guest.
    let response = proxy_to_role(&state, role, &uri, req).await?;

    // On success, inspect the container and set up port forwarding + DNS
    // against the role's utility VM so host ports land on the right bridge.
    if response.status().is_success() {
        if let Some(ref id) = container_id {
            setup_container_networking(&state, role, id).await;
        }
    }

    Ok(response)
}

/// Stop a container and tear down its port forwarding + DNS.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn stop_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    // Resolve canonical ID before proxy — the name/short-id is still valid now
    // but may become stale after stop (e.g. --rm containers).
    let canonical = resolve_or_raw_for_teardown(&state, role, &uri).await;

    let response = proxy_to_role(&state, role, &uri, req).await?;

    // Tear down networking after a terminal stop response.
    // Docker returns 204 on success and 304 when already stopped.
    let status = response.status().as_u16();
    if status == 204 || status == 304 {
        if let Some(canonical) = canonical {
            state.runtime.stop_port_forwarding_by_id(&canonical).await;
            state.runtime.deregister_dns_by_id(&canonical).await;
        }
    }

    Ok(response)
}

/// Kill a container and tear down its port forwarding + DNS.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn kill_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    // Resolve canonical ID before proxy — kill with --rm triggers auto-remove.
    let canonical = resolve_or_raw_for_teardown(&state, role, &uri).await;

    let response = proxy_to_role(&state, role, &uri, req).await?;

    // Docker kill returns 204 on success.
    if response.status().as_u16() == 204 {
        if let Some(canonical) = canonical {
            state.runtime.stop_port_forwarding_by_id(&canonical).await;
            state.runtime.deregister_dns_by_id(&canonical).await;
        }
    }

    Ok(response)
}

/// Restart a container and refresh its DNS entry.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn restart_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    let response = proxy_to_role(&state, role, &uri, req).await?;

    // Docker restart returns 204 on success. Refresh DNS (container may get
    // a new IP) with a single inspect call for both canonical ID and DNS info.
    // Port forwarding targets the guest VM and survives container restarts.
    if response.status().as_u16() == 204 {
        if let Some(id) = extract_container_id(&uri) {
            let _ = state.runtime.ensure_vm_ready().await;
            if let Some(body_bytes) = inspect_container_body(&state, role, &id).await {
                let canonical = canonical_id_or_fallback(&id, &body_bytes);
                if let Some((aliases, ip)) = extract_container_dns_info(&body_bytes) {
                    state.runtime.register_dns(&canonical, &aliases, ip).await;
                }
            }
        }
    }

    Ok(response)
}

/// Remove a container and tear down its port forwarding + DNS.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn remove_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    // Resolve canonical ID before proxy — the name/short-id is still valid now.
    let canonical = resolve_or_raw_for_teardown(&state, role, &uri).await;

    let response = proxy_to_role(&state, role, &uri, req).await?;

    // Only tear down networking after a successful remove.
    if response.status().is_success() {
        if let Some(canonical) = canonical {
            state.runtime.stop_port_forwarding_by_id(&canonical).await;
            state.runtime.deregister_dns_by_id(&canonical).await;
            // Drop the workload→role binding once the container is gone.
            state.workload_roles.forget(&canonical).await;
        }
    }

    Ok(response)
}

/// Inspect a started container and configure port forwarding + DNS registration.
///
/// Shares a single inspect call for both port forwarding and DNS setup. The
/// `role` selects which utility VM hosts the container so the inspect lands
/// on the right guest dockerd.
async fn setup_container_networking(state: &AppState, role: UtilityVmRole, container_id: &str) {
    let Some(body_bytes) = inspect_container_body(state, role, container_id).await else {
        tracing::warn!(
            container_id,
            "Failed to inspect container for networking setup; \
             port forwarding and DNS will not be configured"
        );
        return;
    };

    // Use the canonical full container ID from inspect (not the URI token which
    // may be a name or short ID) so that stop/remove can reliably match the key.
    let canonical_id = canonical_id_or_fallback(container_id, &body_bytes);

    // Port forwarding (against this role's utility VM).
    setup_port_forwarding_from_inspect(state, role, &canonical_id, &body_bytes).await;

    // DNS registration.
    if let Some((aliases, ip)) = extract_container_dns_info(&body_bytes) {
        state
            .runtime
            .register_dns(&canonical_id, &aliases, ip)
            .await;
    }
}

/// Fetches the inspect JSON body for a container from the selected role's
/// guest dockerd.
async fn inspect_container_body(
    state: &AppState,
    role: UtilityVmRole,
    container_id: &str,
) -> Option<Bytes> {
    let inspect_path = format!("/containers/{container_id}/json");
    let inspect_resp = match proxy_to_guest_for_role(
        state.connector.as_ref(),
        role,
        Method::GET,
        &inspect_path,
        &HeaderMap::new(),
        Bytes::new(),
    )
    .await
    {
        Ok(resp) if resp.status().is_success() => resp,
        Ok(resp) => {
            tracing::debug!(
                "Inspect container {} returned status {}",
                container_id,
                resp.status()
            );
            return None;
        }
        Err(e) => {
            tracing::debug!("Failed to inspect container {}: {}", container_id, e);
            return None;
        }
    };

    match http_body_util::BodyExt::collect(inspect_resp.into_body()).await {
        Ok(collected) => Some(collected.to_bytes()),
        Err(e) => {
            tracing::debug!("Failed to read inspect body for {}: {}", container_id, e);
            None
        }
    }
}

/// Configures port forwarding from pre-fetched inspect JSON. The `role`
/// selects which utility VM's bridge (and inbound listener manager) owns
/// the resulting host port bindings.
async fn setup_port_forwarding_from_inspect(
    state: &AppState,
    role: UtilityVmRole,
    canonical_id: &str,
    body_bytes: &[u8],
) {
    let bindings = parse_port_bindings(body_bytes);
    if bindings.is_empty() {
        tracing::debug!("No port bindings found for container {}", canonical_id);
        return;
    }

    tracing::info!(
        "Port forwarding: {} bindings for container {}",
        bindings.len(),
        canonical_id,
    );
    for b in &bindings {
        tracing::info!(
            "  bind {}:{} → container:{}/{}",
            b.host_ip,
            b.host_port,
            b.container_port,
            b.protocol,
        );
    }

    let rules: Vec<_> = bindings
        .iter()
        .map(|b| {
            (
                b.host_ip.clone(),
                b.host_port,
                b.container_port,
                b.protocol.clone(),
            )
        })
        .collect();

    let machine_name = state.runtime.machine_name_for_role(role);
    if let Err(e) = state
        .runtime
        .start_port_forwarding_for(machine_name, canonical_id, &rules)
        .await
    {
        tracing::warn!(
            utility_vm = role.as_str(),
            "Failed to start port forwarding for {}: {}",
            canonical_id,
            e,
        );
    }
}

/// Extracts DNS aliases and IP address from Docker inspect JSON.
///
/// For compose containers (with `com.docker.compose.project` and
/// `com.docker.compose.service` labels), returns:
/// `["service.project", "container_name"]` — a hierarchical service alias
/// plus the flat container name.
///
/// For plain containers, returns `["container_name"]`.
///
/// Falls back through `/NetworkSettings/IPAddress` → per-network IPs.
pub fn extract_container_dns_info(inspect_json: &[u8]) -> Option<(Vec<String>, IpAddr)> {
    let v: serde_json::Value = serde_json::from_slice(inspect_json).ok()?;
    let name = v.get("Name")?.as_str()?.trim_start_matches('/').to_string();

    if name.is_empty() {
        return None;
    }

    // Primary: top-level IPAddress.
    let ip_str = v
        .pointer("/NetworkSettings/IPAddress")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        // Fallback: first non-empty IP from Networks map.
        .or_else(|| {
            v.pointer("/NetworkSettings/Networks")?
                .as_object()?
                .values()
                .find_map(|net| net.get("IPAddress")?.as_str().filter(|s| !s.is_empty()))
        })?;

    // Build DNS aliases from compose labels when available.
    let aliases = match v.pointer("/Config/Labels").and_then(|l| l.as_object()) {
        Some(labels) => {
            let project = labels
                .get("com.docker.compose.project")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty());
            let service = labels
                .get("com.docker.compose.service")
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty());
            match (project, service) {
                // Compose: service-level hierarchical + flat container name.
                (Some(proj), Some(svc)) => {
                    vec![format!("{svc}.{proj}"), name]
                }
                _ => vec![name],
            }
        }
        None => vec![name],
    };

    Some((aliases, ip_str.parse().ok()?))
}

/// Rename a container and update its DNS entry.
///
/// # Errors
///
/// Returns an error if VM readiness fails or proxying to guest dockerd fails.
pub async fn rename_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    // Resolve canonical ID BEFORE proxy — the old name/short-id is still valid
    // now but will be invalid after a successful rename.
    let canonical = resolve_canonical_from_uri(&state, role, &uri).await;
    let new_name = query_param(&uri, "name").map(str::to_string);

    // Proxy rename to guest.
    let response = proxy_to_role(&state, role, &uri, req).await?;

    if response.status().is_success() {
        if let Some(ref canonical) = canonical {
            // 1. Remove old DNS entry.
            state.runtime.deregister_dns_by_id(canonical).await;

            // 2. Update the registry alias so future lookups by the new name
            //    keep landing on the same role.
            if let Some(ref new_name) = new_name {
                state
                    .workload_roles
                    .rename_alias(canonical, new_name.clone())
                    .await;
            }

            // 3. Inspect (using canonical ID which survives rename) to get
            //    new name + IP, then register.
            if let Some(body_bytes) = inspect_container_body(&state, role, canonical).await
                && let Some((aliases, ip)) = extract_container_dns_info(&body_bytes)
            {
                state.runtime.register_dns(canonical, &aliases, ip).await;
            }
        }
    }

    Ok(response)
}

/// Attach to a container.
///
/// # Errors
///
/// Returns an error if upgrade proxying to guest dockerd fails.
pub async fn attach_container(
    State(state): State<AppState>,
    OriginalUri(uri): OriginalUri,
    req: Request<Body>,
) -> Result<Response> {
    let role = resolve_container_role(&state, &uri).await?;
    proxy_upgrade_to_role(&state, role, &uri, req).await
}

/// Extracts the canonical full container ID from a Docker inspect JSON response.
fn extract_canonical_id_from_inspect(inspect_json: &[u8]) -> Option<String> {
    let value: serde_json::Value = serde_json::from_slice(inspect_json).ok()?;
    value.get("Id")?.as_str().map(String::from)
}

/// Returns the canonical container ID from inspect JSON, falling back to the
/// original request token when the inspect payload does not contain a usable ID.
fn canonical_id_or_fallback(container_id: &str, inspect_json: &[u8]) -> String {
    extract_canonical_id_from_inspect(inspect_json).unwrap_or_else(|| container_id.to_string())
}

/// Extracts a container identifier from the URI and resolves it to the
/// canonical full ID via an inspect against the selected utility VM.
/// Returns `None` (with a warning) when canonical resolution fails.
///
/// Teardown handlers (stop/kill/remove) layer a raw-ID fallback on top
/// of this via [`resolve_or_raw_for_teardown`] so transient inspect
/// failures don't leak port forwarding listeners and DNS entries.
/// Non-teardown callers (e.g. rename) must keep using the strict result:
/// a raw URI token that is a name becomes stale after a successful
/// rename, which would break DNS re-registration.
///
/// Best-effort wakes the VM before inspecting, since
/// [`resolve_canonical_id`] uses `proxy_to_guest_for_role` directly and
/// does not call `ensure_vm_ready` itself. Readiness failures are not
/// fatal — the subsequent inspect will surface them as a `None` resolution.
async fn resolve_canonical_from_uri(
    state: &AppState,
    role: UtilityVmRole,
    uri: &Uri,
) -> Option<String> {
    let id = extract_container_id(uri)?;
    // Best-effort wake; if it fails, the inspect call below will too.
    let _ = state.runtime.ensure_vm_ready().await;
    match resolve_canonical_id(state, role, &id).await {
        Some(canonical) => Some(canonical),
        None => {
            tracing::warn!(
                container_id = %id,
                utility_vm = role.as_str(),
                "Failed to resolve canonical container ID"
            );
            None
        }
    }
}

/// Variant of [`resolve_canonical_from_uri`] for teardown handlers
/// (stop/kill/remove): on canonical-resolution failure, falls back to
/// the raw URI-extracted ID so cleanup of port forwarding + DNS still
/// runs. A non-matching key is a no-op against the canonical-keyed maps
/// — strictly better than skipping teardown entirely.
async fn resolve_or_raw_for_teardown(
    state: &AppState,
    role: UtilityVmRole,
    uri: &Uri,
) -> Option<String> {
    if let Some(canonical) = resolve_canonical_from_uri(state, role, uri).await {
        return Some(canonical);
    }
    let raw = extract_container_id(uri)?;
    tracing::warn!(
        container_id = %raw,
        utility_vm = role.as_str(),
        "Using raw URI-extracted ID for networking teardown"
    );
    Some(raw)
}

/// Resolves a container name, short ID, or full ID to the canonical full ID
/// by inspecting the container on the selected utility VM.
async fn resolve_canonical_id(state: &AppState, role: UtilityVmRole, id: &str) -> Option<String> {
    let inspect_path = format!("/containers/{id}/json");
    let resp = proxy_to_guest_for_role(
        state.connector.as_ref(),
        role,
        Method::GET,
        &inspect_path,
        &HeaderMap::new(),
        Bytes::new(),
    )
    .await
    .ok()?;

    if !resp.status().is_success() {
        return None;
    }

    let body_bytes = http_body_util::BodyExt::collect(resp.into_body())
        .await
        .ok()?
        .to_bytes();

    extract_canonical_id_from_inspect(&body_bytes)
}

/// Parses the `Id` field from a `POST /containers/create` JSON response.
fn parse_create_response_id(body: &[u8]) -> Option<String> {
    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
    value.get("Id")?.as_str().map(String::from)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn uri(s: &str) -> Uri {
        s.parse().unwrap()
    }

    #[test]
    fn extract_id_from_start_path() {
        let u = uri("/containers/abc123/start");
        assert_eq!(extract_container_id(&u).as_deref(), Some("abc123"));
    }

    #[test]
    fn extract_id_from_versioned_path() {
        let u = uri("/v1.43/containers/def456/stop");
        assert_eq!(extract_container_id(&u).as_deref(), Some("def456"));
    }

    #[test]
    fn extract_id_from_delete_path() {
        let u = uri("/containers/xyz789");
        assert_eq!(extract_container_id(&u).as_deref(), Some("xyz789"));
    }

    #[test]
    fn extract_id_skips_collection_endpoints() {
        assert_eq!(extract_container_id(&uri("/containers/json")), None);
        assert_eq!(extract_container_id(&uri("/containers/create")), None);
        assert_eq!(extract_container_id(&uri("/containers/prune")), None);
    }

    #[test]
    fn extract_id_no_containers_segment() {
        assert_eq!(extract_container_id(&uri("/images/abc/json")), None);
    }

    #[test]
    fn extract_canonical_id_from_inspect_json() {
        let json = br#"{"Id":"abc123def456789","Name":"/my-nginx","State":{}}"#;
        assert_eq!(
            extract_canonical_id_from_inspect(json).as_deref(),
            Some("abc123def456789")
        );
    }

    #[test]
    fn extract_canonical_id_missing_field() {
        let json = br#"{"Name":"/my-nginx"}"#;
        assert_eq!(extract_canonical_id_from_inspect(json), None);
    }

    #[test]
    fn extract_canonical_id_invalid_json() {
        assert_eq!(extract_canonical_id_from_inspect(b"not json"), None);
    }

    #[test]
    fn parses_id_from_create_response() {
        let json = br#"{"Id":"abc123def456","Warnings":null}"#;
        assert_eq!(
            parse_create_response_id(json).as_deref(),
            Some("abc123def456"),
        );
    }

    #[test]
    fn returns_none_when_create_response_missing_id() {
        assert_eq!(parse_create_response_id(b"{}"), None);
        assert_eq!(parse_create_response_id(b"not json"), None);
    }

    #[test]
    fn canonical_id_or_fallback_uses_canonical() {
        let json = br#"{"Id":"canonical-abcdef","Name":"/my-nginx"}"#;
        assert_eq!(
            canonical_id_or_fallback("web", json),
            "canonical-abcdef".to_string()
        );
    }

    #[test]
    fn canonical_id_or_fallback_falls_back_when_missing() {
        let json = br#"{"Name":"/my-nginx"}"#;
        assert_eq!(canonical_id_or_fallback("web", json), "web".to_string());
    }

    #[test]
    fn canonical_id_or_fallback_falls_back_on_invalid_json() {
        assert_eq!(
            canonical_id_or_fallback("web", b"not json"),
            "web".to_string()
        );
    }

    #[test]
    fn test_extract_container_dns_info_plain() {
        let json = serde_json::json!({
            "Id": "abc123",
            "Name": "/my-nginx",
            "NetworkSettings": {
                "IPAddress": "172.17.0.2",
                "Networks": {}
            }
        });
        let bytes = serde_json::to_vec(&json).unwrap();
        let (aliases, ip) = extract_container_dns_info(&bytes).unwrap();
        assert_eq!(aliases, vec!["my-nginx"]);
        assert_eq!(ip, "172.17.0.2".parse::<IpAddr>().unwrap());
    }

    #[test]
    fn test_extract_container_dns_info_compose() {
        let json = serde_json::json!({
            "Id": "abc123",
            "Name": "/myproject-web-1",
            "Config": {
                "Labels": {
                    "com.docker.compose.project": "myproject",
                    "com.docker.compose.service": "web"
                }
            },
            "NetworkSettings": {
                "IPAddress": "172.17.0.2",
                "Networks": {}
            }
        });
        let bytes = serde_json::to_vec(&json).unwrap();
        let (aliases, ip) = extract_container_dns_info(&bytes).unwrap();
        assert_eq!(aliases, vec!["web.myproject", "myproject-web-1"]);
        assert_eq!(ip, "172.17.0.2".parse::<IpAddr>().unwrap());
    }

    #[test]
    fn test_extract_container_dns_info_network_fallback() {
        let json = serde_json::json!({
            "Id": "abc123",
            "Name": "/web-app",
            "NetworkSettings": {
                "IPAddress": "",
                "Networks": {
                    "bridge": {
                        "IPAddress": "172.18.0.3"
                    }
                }
            }
        });
        let bytes = serde_json::to_vec(&json).unwrap();
        let (aliases, ip) = extract_container_dns_info(&bytes).unwrap();
        assert_eq!(aliases, vec!["web-app"]);
        assert_eq!(ip, "172.18.0.3".parse::<IpAddr>().unwrap());
    }

    #[test]
    fn test_extract_container_dns_info_no_ip() {
        let json = serde_json::json!({
            "Id": "abc123",
            "Name": "/isolated",
            "NetworkSettings": {
                "IPAddress": "",
                "Networks": {}
            }
        });
        let bytes = serde_json::to_vec(&json).unwrap();
        assert!(extract_container_dns_info(&bytes).is_none());
    }

    #[test]
    fn test_extract_container_dns_info_invalid_json() {
        assert!(extract_container_dns_info(b"not json").is_none());
    }

    #[test]
    fn test_extract_container_dns_info_no_name() {
        let json = serde_json::json!({
            "Id": "abc123",
            "NetworkSettings": {
                "IPAddress": "172.17.0.2"
            }
        });
        let bytes = serde_json::to_vec(&json).unwrap();
        assert!(extract_container_dns_info(&bytes).is_none());
    }
}