Skip to main content

workload_spec/
compose_import.rs

1//! One-way, lossy compose YAML → [`WorkloadSpec`] import shim.
2//!
3//! Best-effort translation of a docker-compose v3 file into a set of
4//! `WorkloadSpec` values, one per compose service. The output may need
5//! hand-editing — compose's expressiveness exceeds ours by design and we lose
6//! the parts we don't want. This shim is for one-time migration, not
7//! round-trip authoring.
8//!
9//! Lossy areas (each emits an [`ImportWarning`] keyed by compose path):
10//!
11//! - `network_mode: host` → rejected as [`ImportError::HostNetwork`].
12//! - `build:` blocks → ignored with warning ("build externally; provide an
13//!   `image:` reference").
14//! - Custom networks → flattened to the mesh; warns when topology can't be
15//!   preserved.
16//! - Bind volumes → echoed as warning that yubaba requires `tier = "infra"`
17//!   (the importer auto-promotes the spec's tier when bind mounts are
18//!   present so the result still passes shape validation).
19//! - Healthcheck blocks → noted as warning; not translated in V1 (compose's
20//!   syntax is rich enough to deserve its own pass).
21//!
22//! See `.yah/docs/architecture/A054-yah-workload-spec.md` §"Compose-import shim" for
23//! the design contract.
24
25use std::collections::HashMap;
26use std::path::PathBuf;
27
28use serde::{Deserialize, Serialize};
29use thiserror::Error;
30
31use crate::{
32    EnvValue, EnvVar, ExposeSpec, ImageRef, MeshExpose, MeshIdent, Millis, NamespaceId,
33    RestartPolicy, ResourceLimits, StopPolicy, TenantId, TierTag, VolumeMount,
34    VolumeSource, WorkloadSpec,
35};
36
37// ── Public types ──────────────────────────────────────────────────────────────
38
39/// Output of [`import_compose`].
40///
41/// Serializable so the CLI can emit it as JSON and tests can compare against
42/// fixture snapshots without a bespoke equality codec.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct ImportResult {
45    /// One spec per compose service. Order matches the `services:` map's
46    /// iteration order (sorted by service name for determinism).
47    pub specs: Vec<WorkloadSpec>,
48
49    /// Soft warnings for lossy translations. Each carries a compose path so
50    /// the operator can find the original block.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub warnings: Vec<ImportWarning>,
53}
54
55/// A non-fatal lossy translation noted during import.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct ImportWarning {
58    /// Compose path for the affected block, e.g. `"services.web.build"`.
59    pub path: String,
60    /// Operator-facing explanation.
61    pub message: String,
62}
63
64/// A hard rejection during import.
65#[derive(Debug, Error, PartialEq)]
66pub enum ImportError {
67    /// The YAML failed to parse as a compose file.
68    #[error("compose YAML parse error: {0}")]
69    Parse(String),
70
71    /// The compose file has no `services:` block to translate.
72    #[error("compose file has no `services:` block")]
73    NoServices,
74
75    /// A service uses `network_mode: host`. Yubaba has no host-networking
76    /// escape hatch — every workload runs on the mesh. See arch doc
77    /// §"What's deliberately not in the schema".
78    #[error(
79        "service {service:?}: network_mode=host is not supported on the yubaba mesh \
80         (every workload runs through the mesh; see \
81         .yah/docs/architecture/A054-yah-workload-spec.md §\"What's deliberately not in the schema\")"
82    )]
83    HostNetwork { service: String },
84
85    /// A service has neither `image:` nor a usable image fallback. Yubaba
86    /// can't deploy without an image reference.
87    #[error("service {service:?}: no `image:` field — yubaba requires an image reference")]
88    MissingImage { service: String },
89
90    /// A service's `image:` reference lacks an `@sha256:<hex>` digest pin.
91    /// R438-T3 made digest-pinning structurally required; bare-tag references
92    /// like `node:20` no longer construct an [`ImageRef`]. The operator should
93    /// pin the digest in the compose file (`image: node:20@sha256:<hex>`).
94    #[error("service {service:?}: image {image:?} is not digest-pinned ({reason})")]
95    UnpinnedImage {
96        service: String,
97        image: String,
98        reason: String,
99    },
100}
101
102// ── Entry point ───────────────────────────────────────────────────────────────
103
104/// Parse a compose v3 YAML string into a set of [`WorkloadSpec`] values.
105///
106/// Multi-service composes produce one spec per service. Compose service names
107/// become mesh idents (with `_` rewritten to `-` and a warning). `depends_on`
108/// translates by compose service name → mesh ident.
109///
110/// Returns the first hard rejection ([`ImportError`]) on rejection paths;
111/// otherwise returns [`ImportResult`] with one entry per service.
112pub fn import_compose(yaml: &str) -> Result<ImportResult, ImportError> {
113    let compose: ComposeFile =
114        serde_yaml::from_str(yaml).map_err(|e| ImportError::Parse(e.to_string()))?;
115
116    if compose.services.is_empty() {
117        return Err(ImportError::NoServices);
118    }
119
120    let mut warnings = Vec::new();
121
122    // Top-level networks: yubaba flattens to one mesh, so any custom networks
123    // are lossy.
124    if !compose.networks.is_empty() {
125        warnings.push(ImportWarning {
126            path: "networks".into(),
127            message: format!(
128                "compose declared {} custom network(s) ({}); yubaba flattens all workloads \
129                 onto one mesh — segmentation must be re-expressed via tier `allow_from`",
130                compose.networks.len(),
131                compose
132                    .networks
133                    .keys()
134                    .cloned()
135                    .collect::<Vec<_>>()
136                    .join(", ")
137            ),
138        });
139    }
140
141    let mut specs = Vec::with_capacity(compose.services.len());
142
143    let mut service_names: Vec<&String> = compose.services.keys().collect();
144    service_names.sort();
145    for service_name in service_names {
146        let svc = &compose.services[service_name];
147        let spec = translate_service(service_name, svc, &mut warnings)?;
148        specs.push(spec);
149    }
150
151    Ok(ImportResult { specs, warnings })
152}
153
154// ── Translation ───────────────────────────────────────────────────────────────
155
156fn translate_service(
157    name: &str,
158    svc: &ComposeService,
159    warnings: &mut Vec<ImportWarning>,
160) -> Result<WorkloadSpec, ImportError> {
161    if svc.network_mode.as_deref() == Some("host") {
162        return Err(ImportError::HostNetwork { service: name.into() });
163    }
164
165    if let Some(mode) = &svc.network_mode {
166        if mode != "host" && mode != "default" && mode != "bridge" {
167            warnings.push(ImportWarning {
168                path: format!("services.{name}.network_mode"),
169                message: format!(
170                    "network_mode={mode:?} ignored — yubaba runs every workload on the mesh"
171                ),
172            });
173        }
174    }
175
176    if svc.build.is_some() {
177        warnings.push(ImportWarning {
178            path: format!("services.{name}.build"),
179            message: "build: blocks are ignored. Build externally (CI) and provide an \
180                      image: reference; see arch doc §\"What's deliberately not in the schema\""
181                .into(),
182        });
183    }
184
185    if svc.healthcheck.is_some() {
186        warnings.push(ImportWarning {
187            path: format!("services.{name}.healthcheck"),
188            message: "compose healthcheck not translated in V1 — re-author against \
189                      WorkloadSpec.healthcheck (HttpGet / Exec / TcpConnect)"
190                .into(),
191        });
192    }
193
194    if !svc.networks.is_empty() {
195        warnings.push(ImportWarning {
196            path: format!("services.{name}.networks"),
197            message: format!(
198                "service-level network attachments ({}) flattened to the mesh — \
199                 segmentation must be re-expressed via tier `allow_from`",
200                svc.networks.join(", ")
201            ),
202        });
203    }
204
205    let (mesh_name, mesh_warning) = sanitize_mesh_ident(name);
206    if let Some(message) = mesh_warning {
207        warnings.push(ImportWarning {
208            path: format!("services.{name}"),
209            message,
210        });
211    }
212
213    let image = svc
214        .image
215        .as_deref()
216        .ok_or_else(|| ImportError::MissingImage { service: name.into() })?;
217    let image = parse_image_ref(image).map_err(|reason| ImportError::UnpinnedImage {
218        service: name.into(),
219        image: image.into(),
220        reason,
221    })?;
222
223    let env = translate_env(name, &svc.environment, warnings);
224
225    let mesh_ports = translate_ports(name, &svc.ports, warnings);
226
227    let depends_on = svc
228        .depends_on
229        .as_ref()
230        .map(|d| d.iter_names().map(|n| MeshIdent(sanitize_mesh_ident(n).0)).collect())
231        .unwrap_or_default();
232
233    let (volumes, has_bind) = translate_volumes(name, &svc.volumes, warnings);
234
235    let tier_str = if has_bind { "infra" } else { "private" };
236    if has_bind {
237        warnings.push(ImportWarning {
238            path: format!("services.{name}.volumes"),
239            message: "bind volume(s) detected; spec auto-promoted to tier=\"infra\" so it \
240                      passes shape validation. Hand-review whether infra is the right tier"
241                .into(),
242        });
243    }
244
245    let restart_policy = translate_restart(name, svc.restart.as_deref(), warnings);
246
247    let command = svc.command.as_ref().map(StringOrList::into_argv);
248    let entrypoint = svc.entrypoint.as_ref().map(StringOrList::into_argv);
249    let workdir = svc.working_dir.as_ref().map(PathBuf::from);
250
251    let spec = WorkloadSpec {
252        name: mesh_name.clone(),
253        image,
254        tier: TierTag(tier_str.into()),
255        tenant: TenantId::singleton(),
256        namespace: NamespaceId::singleton(),
257        replicas: 1,
258        command,
259        entrypoint,
260        workdir,
261        user: svc.user.clone(),
262        env,
263        secrets: vec![],
264        volumes,
265        resources: ResourceLimits {
266            memory_mb: 256,
267            cpu_millis: 512,
268            memory_request_mb: None,
269            cpu_limit_millis: None,
270            pids_max: None,
271            scratch_floor_mb: None,
272        },
273        depends_on,
274        // compose has no locality/supply concept, so an import can only ever
275        // produce the `anywhere` + `wait` edges `depends_on` already carries
276        // (R860-T1).
277        requires: vec![],
278        healthcheck: None,
279        restart_policy,
280        archetype: None,
281        stop_policy: StopPolicy {
282            signal: 15,
283            grace_period: Millis::from_secs(10),
284        },
285        expose: ExposeSpec {
286            mesh: MeshExpose {
287                identity: MeshIdent(mesh_name),
288                // docker-compose has no port-name concept, so an import can
289                // only ever produce unnamed numbers (R844-F17).
290                ports: MeshExpose::anonymous_ports(mesh_ports),
291                allow_from: vec![],
292            },
293            public: None,
294            operator: None,
295        },
296        labels: HashMap::new(),
297        durability: None,
298        annotations: HashMap::new(),
299        files: Vec::new(),
300    };
301
302    Ok(spec)
303}
304
305/// Sanitize a compose service name into a DNS-friendly mesh ident.
306///
307/// Returns `(sanitized, warning)`. The warning is `Some` when the input had
308/// to be modified — operators see it on stderr and in the JSON output.
309fn sanitize_mesh_ident(name: &str) -> (String, Option<String>) {
310    let lowered = name.to_ascii_lowercase();
311    let sanitized: String = lowered
312        .chars()
313        .map(|c| if c == '_' { '-' } else { c })
314        .collect();
315    if sanitized != name {
316        let msg = format!(
317            "compose service name {name:?} rewritten to {sanitized:?} \
318             (mesh idents must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$)"
319        );
320        (sanitized, Some(msg))
321    } else {
322        (sanitized, None)
323    }
324}
325
326/// Parse a compose image reference into an [`ImageRef`]. The reference must
327/// be digest-pinned — bare-tag references like `nginx:1.25` are rejected per
328/// R438-T3. The accepted shape is `[registry/]repo[:tag]@sha256:<hex>`.
329///
330/// Examples (accepted):
331/// - `nginx:1.25@sha256:<hex>` → `docker.io / library/nginx : 1.25 @ sha256:<hex>`
332/// - `ghcr.io/foo/bar:v1@sha256:<hex>` → `ghcr.io / foo/bar : v1 @ sha256:<hex>`
333/// - `repo@sha256:<hex>` → defaults `tag = "latest"`
334///
335/// Examples (rejected):
336/// - `nginx`, `nginx:1.25`, `ghcr.io/foo/bar:v1` — no digest pin
337pub(crate) fn parse_image_ref(s: &str) -> Result<ImageRef, String> {
338    parse_pinned_image_ref(s)
339}
340
341/// Parse an image reference and **require** an `@sha256:<hex>` digest pin.
342/// Bare-tag references (e.g. `node:20`) are rejected — the digest is the only
343/// thing that survives an upstream tag retag and is what W164's reproducibility
344/// rule and W165's CI-fidelity rule both depend on.
345///
346/// Used by the string-form deserializer for [`ImageRef`]; the struct-form
347/// deserializer is unchanged (legacy `WorkloadSpec` configs keep working).
348pub(crate) fn parse_pinned_image_ref(s: &str) -> Result<ImageRef, String> {
349    let (head, dig_str) = s.split_once('@').ok_or_else(|| {
350        format!(
351            "image reference {s:?} must be digest-pinned (e.g. `repo:tag@sha256:<hex>`); \
352             bare-tag images are rejected — pin with @sha256:<digest>"
353        )
354    })?;
355
356    let hex = dig_str.strip_prefix("sha256:").ok_or_else(|| {
357        format!("image digest must start with `sha256:`, got {dig_str:?}")
358    })?;
359    if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
360        return Err(format!("sha256 digest must be non-empty hex, got {hex:?}"));
361    }
362
363    let (head2, tag_opt) = split_repo_and_tag(head);
364    let tag = tag_opt.unwrap_or_else(|| "latest".into());
365    let (registry, repository) = split_registry_and_repo(head2);
366
367    Ok(ImageRef {
368        registry,
369        repository,
370        tag,
371        digest: format!("sha256:{hex}"),
372    })
373}
374
375/// Split a `repo:tag` or `repo` reference. Careful with `localhost:5000/foo` —
376/// the colon there is part of the registry, not a tag. We identify a tag as
377/// the colon AFTER the last slash.
378fn split_repo_and_tag(s: &str) -> (&str, Option<String>) {
379    let last_slash = s.rfind('/');
380    let search_from = last_slash.map(|i| i + 1).unwrap_or(0);
381    if let Some(colon) = s[search_from..].find(':') {
382        let abs = search_from + colon;
383        let head = &s[..abs];
384        let tag = &s[abs + 1..];
385        (head, Some(tag.to_string()))
386    } else {
387        (s, None)
388    }
389}
390
391/// Split a `registry/repo` head into `(registry, repo)`. A first segment is
392/// treated as a registry hostname when it contains `.` or `:`, or equals
393/// `localhost`. Otherwise we default to docker.io and prepend `library/` for
394/// official images (compose `nginx` ⇒ docker.io/library/nginx, mirrors the
395/// docker CLI default).
396fn split_registry_and_repo(head: &str) -> (String, String) {
397    if let Some((first, rest)) = head.split_once('/') {
398        if first == "localhost" || first.contains('.') || first.contains(':') {
399            return (first.to_string(), rest.to_string());
400        }
401    }
402    let repo = if head.contains('/') {
403        head.to_string()
404    } else {
405        format!("library/{head}")
406    };
407    ("docker.io".into(), repo)
408}
409
410fn translate_env(
411    service: &str,
412    environment: &Option<EnvList>,
413    warnings: &mut Vec<ImportWarning>,
414) -> Vec<EnvVar> {
415    let Some(env) = environment else {
416        return Vec::new();
417    };
418    let mut out = Vec::new();
419    match env {
420        EnvList::List(items) => {
421            for (i, item) in items.iter().enumerate() {
422                if let Some((k, v)) = item.split_once('=') {
423                    out.push(EnvVar {
424                        name: k.into(),
425                        value: EnvValue::Literal { value: v.into() },
426                    });
427                } else {
428                    warnings.push(ImportWarning {
429                        path: format!("services.{service}.environment[{i}]"),
430                        message: format!(
431                            "{item:?} omits a value (compose pulls it from the host shell). \
432                             Provide a literal value or use EnvValue::FromSecret"
433                        ),
434                    });
435                }
436            }
437        }
438        EnvList::Map(map) => {
439            let mut keys: Vec<&String> = map.keys().collect();
440            keys.sort();
441            for k in keys {
442                let v = &map[k];
443                let value = yaml_scalar_to_string(v);
444                out.push(EnvVar {
445                    name: k.clone(),
446                    value: EnvValue::Literal { value },
447                });
448            }
449        }
450    }
451    out
452}
453
454fn yaml_scalar_to_string(v: &serde_yaml::Value) -> String {
455    match v {
456        serde_yaml::Value::String(s) => s.clone(),
457        serde_yaml::Value::Number(n) => n.to_string(),
458        serde_yaml::Value::Bool(b) => b.to_string(),
459        serde_yaml::Value::Null => String::new(),
460        other => serde_yaml::to_string(other).unwrap_or_default().trim().to_string(),
461    }
462}
463
464fn translate_ports(
465    service: &str,
466    ports: &[PortSpec],
467    warnings: &mut Vec<ImportWarning>,
468) -> Vec<u16> {
469    let mut out = Vec::new();
470    for (i, p) in ports.iter().enumerate() {
471        match p.parse_container_port() {
472            Ok(port) => {
473                if !out.contains(&port) {
474                    out.push(port);
475                }
476            }
477            Err(msg) => {
478                warnings.push(ImportWarning {
479                    path: format!("services.{service}.ports[{i}]"),
480                    message: msg,
481                });
482            }
483        }
484    }
485    out
486}
487
488fn translate_volumes(
489    service: &str,
490    items: &[String],
491    warnings: &mut Vec<ImportWarning>,
492) -> (Vec<VolumeMount>, bool) {
493    let mut out = Vec::new();
494    let mut has_bind = false;
495    for (i, raw) in items.iter().enumerate() {
496        let parts: Vec<&str> = raw.split(':').collect();
497        let (source, target, read_only) = match parts.as_slice() {
498            [target] => (None, *target, false),
499            [src, tgt] => (Some(*src), *tgt, false),
500            [src, tgt, mode] => (Some(*src), *tgt, mode.contains("ro")),
501            _ => {
502                warnings.push(ImportWarning {
503                    path: format!("services.{service}.volumes[{i}]"),
504                    message: format!("volume spec {raw:?} could not be parsed; skipped"),
505                });
506                continue;
507            }
508        };
509
510        let target = PathBuf::from(target);
511        let source = if let Some(src) = source {
512            if src.starts_with('/') || src.starts_with('.') || src.starts_with('~') {
513                has_bind = true;
514                VolumeSource::Bind {
515                    host_path: PathBuf::from(src),
516                }
517            } else {
518                VolumeSource::Named { name: src.into() }
519            }
520        } else {
521            VolumeSource::Named {
522                name: format!("anon-{}-{}", service, i),
523            }
524        };
525
526        out.push(VolumeMount {
527            source,
528            target,
529            read_only,
530            from_secret_mount: false,
531        });
532    }
533    (out, has_bind)
534}
535
536fn translate_restart(
537    service: &str,
538    restart: Option<&str>,
539    warnings: &mut Vec<ImportWarning>,
540) -> RestartPolicy {
541    match restart {
542        None => RestartPolicy::Always,
543        Some("always") => RestartPolicy::Always,
544        Some("no") => RestartPolicy::Never,
545        Some("unless-stopped") => {
546            warnings.push(ImportWarning {
547                path: format!("services.{service}.restart"),
548                message: "restart=unless-stopped translated to RestartPolicy::Always — \
549                          yubaba has no manual-stop concept the policy can opt out of"
550                    .into(),
551            });
552            RestartPolicy::Always
553        }
554        Some(other) if other.starts_with("on-failure") => RestartPolicy::OnFailure {
555            max_attempts: 5,
556            backoff: crate::BackoffPolicy {
557                initial_ms: 1000,
558                max_ms: 30_000,
559                multiplier: 2.0,
560            },
561        },
562        Some(other) => {
563            warnings.push(ImportWarning {
564                path: format!("services.{service}.restart"),
565                message: format!(
566                    "unknown restart policy {other:?}; defaulted to RestartPolicy::Always"
567                ),
568            });
569            RestartPolicy::Always
570        }
571    }
572}
573
574// ── Compose parse types ───────────────────────────────────────────────────────
575
576#[derive(Debug, Deserialize)]
577struct ComposeFile {
578    #[serde(default)]
579    #[allow(dead_code)]
580    version: Option<String>,
581    #[serde(default)]
582    services: HashMap<String, ComposeService>,
583    #[serde(default)]
584    networks: HashMap<String, serde_yaml::Value>,
585    #[serde(default)]
586    #[allow(dead_code)]
587    volumes: HashMap<String, serde_yaml::Value>,
588}
589
590#[derive(Debug, Deserialize, Default)]
591struct ComposeService {
592    #[serde(default)]
593    image: Option<String>,
594    #[serde(default)]
595    build: Option<serde_yaml::Value>,
596    #[serde(default)]
597    command: Option<StringOrList>,
598    #[serde(default)]
599    entrypoint: Option<StringOrList>,
600    #[serde(default)]
601    environment: Option<EnvList>,
602    #[serde(default)]
603    ports: Vec<PortSpec>,
604    #[serde(default)]
605    depends_on: Option<DependsOn>,
606    #[serde(default)]
607    volumes: Vec<String>,
608    #[serde(default)]
609    network_mode: Option<String>,
610    #[serde(default)]
611    networks: Vec<String>,
612    #[serde(default)]
613    user: Option<String>,
614    #[serde(default)]
615    working_dir: Option<String>,
616    #[serde(default)]
617    restart: Option<String>,
618    #[serde(default)]
619    healthcheck: Option<serde_yaml::Value>,
620}
621
622#[derive(Debug, Deserialize)]
623#[serde(untagged)]
624enum StringOrList {
625    String(String),
626    List(Vec<String>),
627}
628
629impl StringOrList {
630    fn into_argv(&self) -> Vec<String> {
631        match self {
632            StringOrList::String(s) => shell_split(s),
633            StringOrList::List(v) => v.clone(),
634        }
635    }
636}
637
638/// Minimal whitespace tokeniser for compose's string-form `command:` / `entrypoint:`.
639/// Compose uses `/bin/sh -c` style strings; we don't honor quoting, just split on
640/// whitespace (the rare quoted-arg case stays a hand-edit).
641fn shell_split(s: &str) -> Vec<String> {
642    s.split_whitespace().map(str::to_string).collect()
643}
644
645#[derive(Debug, Deserialize)]
646#[serde(untagged)]
647enum EnvList {
648    List(Vec<String>),
649    Map(HashMap<String, serde_yaml::Value>),
650}
651
652#[derive(Debug, Deserialize)]
653#[serde(untagged)]
654enum DependsOn {
655    List(Vec<String>),
656    Map(HashMap<String, serde_yaml::Value>),
657}
658
659impl DependsOn {
660    fn iter_names(&self) -> Box<dyn Iterator<Item = &str> + '_> {
661        match self {
662            DependsOn::List(v) => Box::new(v.iter().map(String::as_str)),
663            DependsOn::Map(m) => {
664                let mut keys: Vec<&String> = m.keys().collect();
665                keys.sort();
666                Box::new(keys.into_iter().map(String::as_str))
667            }
668        }
669    }
670}
671
672/// Compose's `ports:` list is heterogeneous: short strings ("8080:80"), bare
673/// numbers (8080), or long-form maps. We only need the container-side port.
674#[derive(Debug, Deserialize)]
675#[serde(untagged)]
676enum PortSpec {
677    Short(String),
678    Number(u16),
679    Long(LongPort),
680}
681
682#[derive(Debug, Deserialize)]
683struct LongPort {
684    target: u16,
685    #[serde(default)]
686    #[allow(dead_code)]
687    published: Option<serde_yaml::Value>,
688    #[serde(default)]
689    #[allow(dead_code)]
690    protocol: Option<String>,
691    #[serde(default)]
692    #[allow(dead_code)]
693    mode: Option<String>,
694}
695
696impl PortSpec {
697    fn parse_container_port(&self) -> Result<u16, String> {
698        match self {
699            PortSpec::Number(n) => Ok(*n),
700            PortSpec::Long(l) => Ok(l.target),
701            PortSpec::Short(s) => parse_short_port(s),
702        }
703    }
704}
705
706/// Compose short-form port shapes: `"80"`, `"8080:80"`, `"127.0.0.1:8080:80"`,
707/// `"8080:80/udp"`. We extract the container-side port and ignore host-side
708/// binding (yubaba's mesh handles that).
709fn parse_short_port(s: &str) -> Result<u16, String> {
710    let no_proto = s.split('/').next().unwrap_or(s);
711    let segments: Vec<&str> = no_proto.split(':').collect();
712    let container = segments
713        .last()
714        .ok_or_else(|| format!("port spec {s:?} is empty"))?;
715    container
716        .parse::<u16>()
717        .map_err(|e| format!("port spec {s:?}: container-side port {container:?} not a u16 ({e})"))
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723
724    const PINNED_NGINX: &str =
725        "nginx:1.25@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
726    const PINNED_GHCR: &str =
727        "ghcr.io/foo/bar:v1@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
728    const PINNED_LOCALHOST: &str =
729        "localhost:5000/svc:dev@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
730
731    #[test]
732    fn parse_image_ref_rejects_bare_tag() {
733        for bare in ["nginx", "nginx:1.25", "ghcr.io/foo/bar:v1"] {
734            let res = parse_image_ref(bare);
735            assert!(res.is_err(), "bare tag {bare:?} must reject");
736        }
737    }
738
739    #[test]
740    fn parse_image_ref_with_tag_and_digest() {
741        let r = parse_image_ref(PINNED_NGINX).expect("pinned parses");
742        assert_eq!(r.registry, "docker.io");
743        assert_eq!(r.repository, "library/nginx");
744        assert_eq!(r.tag, "1.25");
745        assert!(r.digest.starts_with("sha256:"));
746    }
747
748    #[test]
749    fn parse_image_ref_ghcr_pinned() {
750        let r = parse_image_ref(PINNED_GHCR).expect("pinned parses");
751        assert_eq!(r.registry, "ghcr.io");
752        assert_eq!(r.repository, "foo/bar");
753        assert_eq!(r.tag, "v1");
754    }
755
756    #[test]
757    fn parse_image_ref_localhost_port_pinned() {
758        let r = parse_image_ref(PINNED_LOCALHOST).expect("pinned parses");
759        assert_eq!(r.registry, "localhost:5000");
760        assert_eq!(r.repository, "svc");
761        assert_eq!(r.tag, "dev");
762    }
763
764    #[test]
765    fn parse_short_port_ok() {
766        assert_eq!(parse_short_port("80").unwrap(), 80);
767        assert_eq!(parse_short_port("8080:80").unwrap(), 80);
768        assert_eq!(parse_short_port("127.0.0.1:8080:80").unwrap(), 80);
769        assert_eq!(parse_short_port("8080:80/udp").unwrap(), 80);
770    }
771
772    #[test]
773    fn sanitize_mesh_ident_underscore_to_dash() {
774        let (n, w) = sanitize_mesh_ident("web_app");
775        assert_eq!(n, "web-app");
776        assert!(w.is_some());
777    }
778
779    #[test]
780    fn sanitize_mesh_ident_passthrough() {
781        let (n, w) = sanitize_mesh_ident("web-app");
782        assert_eq!(n, "web-app");
783        assert!(w.is_none());
784    }
785}