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, SchemaVersion, 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        schema_version: SchemaVersion::V1,
253        name: mesh_name.clone(),
254        image,
255        tier: TierTag(tier_str.into()),
256        tenant: TenantId::singleton(),
257        namespace: NamespaceId::singleton(),
258        replicas: 1,
259        command,
260        entrypoint,
261        workdir,
262        user: svc.user.clone(),
263        env,
264        secrets: vec![],
265        volumes,
266        resources: ResourceLimits {
267            memory_mb: 256,
268            cpu_millis: 512,
269            ephemeral_storage_mb: 512,
270        },
271        depends_on,
272        healthcheck: None,
273        restart_policy,
274        archetype: None,
275        stop_policy: StopPolicy {
276            signal: 15,
277            grace_period: Millis::from_secs(10),
278        },
279        expose: ExposeSpec {
280            mesh: MeshExpose {
281                identity: MeshIdent(mesh_name),
282                // docker-compose has no port-name concept, so an import can
283                // only ever produce unnamed numbers (R844-F17).
284                ports: MeshExpose::anonymous_ports(mesh_ports),
285                allow_from: vec![],
286            },
287            public: None,
288            operator: None,
289        },
290        labels: HashMap::new(),
291        annotations: HashMap::new(),
292    };
293
294    Ok(spec)
295}
296
297/// Sanitize a compose service name into a DNS-friendly mesh ident.
298///
299/// Returns `(sanitized, warning)`. The warning is `Some` when the input had
300/// to be modified — operators see it on stderr and in the JSON output.
301fn sanitize_mesh_ident(name: &str) -> (String, Option<String>) {
302    let lowered = name.to_ascii_lowercase();
303    let sanitized: String = lowered
304        .chars()
305        .map(|c| if c == '_' { '-' } else { c })
306        .collect();
307    if sanitized != name {
308        let msg = format!(
309            "compose service name {name:?} rewritten to {sanitized:?} \
310             (mesh idents must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$)"
311        );
312        (sanitized, Some(msg))
313    } else {
314        (sanitized, None)
315    }
316}
317
318/// Parse a compose image reference into an [`ImageRef`]. The reference must
319/// be digest-pinned — bare-tag references like `nginx:1.25` are rejected per
320/// R438-T3. The accepted shape is `[registry/]repo[:tag]@sha256:<hex>`.
321///
322/// Examples (accepted):
323/// - `nginx:1.25@sha256:<hex>` → `docker.io / library/nginx : 1.25 @ sha256:<hex>`
324/// - `ghcr.io/foo/bar:v1@sha256:<hex>` → `ghcr.io / foo/bar : v1 @ sha256:<hex>`
325/// - `repo@sha256:<hex>` → defaults `tag = "latest"`
326///
327/// Examples (rejected):
328/// - `nginx`, `nginx:1.25`, `ghcr.io/foo/bar:v1` — no digest pin
329pub(crate) fn parse_image_ref(s: &str) -> Result<ImageRef, String> {
330    parse_pinned_image_ref(s)
331}
332
333/// Parse an image reference and **require** an `@sha256:<hex>` digest pin.
334/// Bare-tag references (e.g. `node:20`) are rejected — the digest is the only
335/// thing that survives an upstream tag retag and is what W164's reproducibility
336/// rule and W165's CI-fidelity rule both depend on.
337///
338/// Used by the string-form deserializer for [`ImageRef`]; the struct-form
339/// deserializer is unchanged (legacy `WorkloadSpec` configs keep working).
340pub(crate) fn parse_pinned_image_ref(s: &str) -> Result<ImageRef, String> {
341    let (head, dig_str) = s.split_once('@').ok_or_else(|| {
342        format!(
343            "image reference {s:?} must be digest-pinned (e.g. `repo:tag@sha256:<hex>`); \
344             bare-tag images are rejected — pin with @sha256:<digest>"
345        )
346    })?;
347
348    let hex = dig_str.strip_prefix("sha256:").ok_or_else(|| {
349        format!("image digest must start with `sha256:`, got {dig_str:?}")
350    })?;
351    if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
352        return Err(format!("sha256 digest must be non-empty hex, got {hex:?}"));
353    }
354
355    let (head2, tag_opt) = split_repo_and_tag(head);
356    let tag = tag_opt.unwrap_or_else(|| "latest".into());
357    let (registry, repository) = split_registry_and_repo(head2);
358
359    Ok(ImageRef {
360        registry,
361        repository,
362        tag,
363        digest: format!("sha256:{hex}"),
364    })
365}
366
367/// Split a `repo:tag` or `repo` reference. Careful with `localhost:5000/foo` —
368/// the colon there is part of the registry, not a tag. We identify a tag as
369/// the colon AFTER the last slash.
370fn split_repo_and_tag(s: &str) -> (&str, Option<String>) {
371    let last_slash = s.rfind('/');
372    let search_from = last_slash.map(|i| i + 1).unwrap_or(0);
373    if let Some(colon) = s[search_from..].find(':') {
374        let abs = search_from + colon;
375        let head = &s[..abs];
376        let tag = &s[abs + 1..];
377        (head, Some(tag.to_string()))
378    } else {
379        (s, None)
380    }
381}
382
383/// Split a `registry/repo` head into `(registry, repo)`. A first segment is
384/// treated as a registry hostname when it contains `.` or `:`, or equals
385/// `localhost`. Otherwise we default to docker.io and prepend `library/` for
386/// official images (compose `nginx` ⇒ docker.io/library/nginx, mirrors the
387/// docker CLI default).
388fn split_registry_and_repo(head: &str) -> (String, String) {
389    if let Some((first, rest)) = head.split_once('/') {
390        if first == "localhost" || first.contains('.') || first.contains(':') {
391            return (first.to_string(), rest.to_string());
392        }
393    }
394    let repo = if head.contains('/') {
395        head.to_string()
396    } else {
397        format!("library/{head}")
398    };
399    ("docker.io".into(), repo)
400}
401
402fn translate_env(
403    service: &str,
404    environment: &Option<EnvList>,
405    warnings: &mut Vec<ImportWarning>,
406) -> Vec<EnvVar> {
407    let Some(env) = environment else {
408        return Vec::new();
409    };
410    let mut out = Vec::new();
411    match env {
412        EnvList::List(items) => {
413            for (i, item) in items.iter().enumerate() {
414                if let Some((k, v)) = item.split_once('=') {
415                    out.push(EnvVar {
416                        name: k.into(),
417                        value: EnvValue::Literal { value: v.into() },
418                    });
419                } else {
420                    warnings.push(ImportWarning {
421                        path: format!("services.{service}.environment[{i}]"),
422                        message: format!(
423                            "{item:?} omits a value (compose pulls it from the host shell). \
424                             Provide a literal value or use EnvValue::FromSecret"
425                        ),
426                    });
427                }
428            }
429        }
430        EnvList::Map(map) => {
431            let mut keys: Vec<&String> = map.keys().collect();
432            keys.sort();
433            for k in keys {
434                let v = &map[k];
435                let value = yaml_scalar_to_string(v);
436                out.push(EnvVar {
437                    name: k.clone(),
438                    value: EnvValue::Literal { value },
439                });
440            }
441        }
442    }
443    out
444}
445
446fn yaml_scalar_to_string(v: &serde_yaml::Value) -> String {
447    match v {
448        serde_yaml::Value::String(s) => s.clone(),
449        serde_yaml::Value::Number(n) => n.to_string(),
450        serde_yaml::Value::Bool(b) => b.to_string(),
451        serde_yaml::Value::Null => String::new(),
452        other => serde_yaml::to_string(other).unwrap_or_default().trim().to_string(),
453    }
454}
455
456fn translate_ports(
457    service: &str,
458    ports: &[PortSpec],
459    warnings: &mut Vec<ImportWarning>,
460) -> Vec<u16> {
461    let mut out = Vec::new();
462    for (i, p) in ports.iter().enumerate() {
463        match p.parse_container_port() {
464            Ok(port) => {
465                if !out.contains(&port) {
466                    out.push(port);
467                }
468            }
469            Err(msg) => {
470                warnings.push(ImportWarning {
471                    path: format!("services.{service}.ports[{i}]"),
472                    message: msg,
473                });
474            }
475        }
476    }
477    out
478}
479
480fn translate_volumes(
481    service: &str,
482    items: &[String],
483    warnings: &mut Vec<ImportWarning>,
484) -> (Vec<VolumeMount>, bool) {
485    let mut out = Vec::new();
486    let mut has_bind = false;
487    for (i, raw) in items.iter().enumerate() {
488        let parts: Vec<&str> = raw.split(':').collect();
489        let (source, target, read_only) = match parts.as_slice() {
490            [target] => (None, *target, false),
491            [src, tgt] => (Some(*src), *tgt, false),
492            [src, tgt, mode] => (Some(*src), *tgt, mode.contains("ro")),
493            _ => {
494                warnings.push(ImportWarning {
495                    path: format!("services.{service}.volumes[{i}]"),
496                    message: format!("volume spec {raw:?} could not be parsed; skipped"),
497                });
498                continue;
499            }
500        };
501
502        let target = PathBuf::from(target);
503        let source = if let Some(src) = source {
504            if src.starts_with('/') || src.starts_with('.') || src.starts_with('~') {
505                has_bind = true;
506                VolumeSource::Bind {
507                    host_path: PathBuf::from(src),
508                }
509            } else {
510                VolumeSource::Named { name: src.into() }
511            }
512        } else {
513            VolumeSource::Named {
514                name: format!("anon-{}-{}", service, i),
515            }
516        };
517
518        out.push(VolumeMount {
519            source,
520            target,
521            read_only,
522        });
523    }
524    (out, has_bind)
525}
526
527fn translate_restart(
528    service: &str,
529    restart: Option<&str>,
530    warnings: &mut Vec<ImportWarning>,
531) -> RestartPolicy {
532    match restart {
533        None => RestartPolicy::Always,
534        Some("always") => RestartPolicy::Always,
535        Some("no") => RestartPolicy::Never,
536        Some("unless-stopped") => {
537            warnings.push(ImportWarning {
538                path: format!("services.{service}.restart"),
539                message: "restart=unless-stopped translated to RestartPolicy::Always — \
540                          yubaba has no manual-stop concept the policy can opt out of"
541                    .into(),
542            });
543            RestartPolicy::Always
544        }
545        Some(other) if other.starts_with("on-failure") => RestartPolicy::OnFailure {
546            max_attempts: 5,
547            backoff: crate::BackoffPolicy {
548                initial_ms: 1000,
549                max_ms: 30_000,
550                multiplier: 2.0,
551            },
552        },
553        Some(other) => {
554            warnings.push(ImportWarning {
555                path: format!("services.{service}.restart"),
556                message: format!(
557                    "unknown restart policy {other:?}; defaulted to RestartPolicy::Always"
558                ),
559            });
560            RestartPolicy::Always
561        }
562    }
563}
564
565// ── Compose parse types ───────────────────────────────────────────────────────
566
567#[derive(Debug, Deserialize)]
568struct ComposeFile {
569    #[serde(default)]
570    #[allow(dead_code)]
571    version: Option<String>,
572    #[serde(default)]
573    services: HashMap<String, ComposeService>,
574    #[serde(default)]
575    networks: HashMap<String, serde_yaml::Value>,
576    #[serde(default)]
577    #[allow(dead_code)]
578    volumes: HashMap<String, serde_yaml::Value>,
579}
580
581#[derive(Debug, Deserialize, Default)]
582struct ComposeService {
583    #[serde(default)]
584    image: Option<String>,
585    #[serde(default)]
586    build: Option<serde_yaml::Value>,
587    #[serde(default)]
588    command: Option<StringOrList>,
589    #[serde(default)]
590    entrypoint: Option<StringOrList>,
591    #[serde(default)]
592    environment: Option<EnvList>,
593    #[serde(default)]
594    ports: Vec<PortSpec>,
595    #[serde(default)]
596    depends_on: Option<DependsOn>,
597    #[serde(default)]
598    volumes: Vec<String>,
599    #[serde(default)]
600    network_mode: Option<String>,
601    #[serde(default)]
602    networks: Vec<String>,
603    #[serde(default)]
604    user: Option<String>,
605    #[serde(default)]
606    working_dir: Option<String>,
607    #[serde(default)]
608    restart: Option<String>,
609    #[serde(default)]
610    healthcheck: Option<serde_yaml::Value>,
611}
612
613#[derive(Debug, Deserialize)]
614#[serde(untagged)]
615enum StringOrList {
616    String(String),
617    List(Vec<String>),
618}
619
620impl StringOrList {
621    fn into_argv(&self) -> Vec<String> {
622        match self {
623            StringOrList::String(s) => shell_split(s),
624            StringOrList::List(v) => v.clone(),
625        }
626    }
627}
628
629/// Minimal whitespace tokeniser for compose's string-form `command:` / `entrypoint:`.
630/// Compose uses `/bin/sh -c` style strings; we don't honor quoting, just split on
631/// whitespace (the rare quoted-arg case stays a hand-edit).
632fn shell_split(s: &str) -> Vec<String> {
633    s.split_whitespace().map(str::to_string).collect()
634}
635
636#[derive(Debug, Deserialize)]
637#[serde(untagged)]
638enum EnvList {
639    List(Vec<String>),
640    Map(HashMap<String, serde_yaml::Value>),
641}
642
643#[derive(Debug, Deserialize)]
644#[serde(untagged)]
645enum DependsOn {
646    List(Vec<String>),
647    Map(HashMap<String, serde_yaml::Value>),
648}
649
650impl DependsOn {
651    fn iter_names(&self) -> Box<dyn Iterator<Item = &str> + '_> {
652        match self {
653            DependsOn::List(v) => Box::new(v.iter().map(String::as_str)),
654            DependsOn::Map(m) => {
655                let mut keys: Vec<&String> = m.keys().collect();
656                keys.sort();
657                Box::new(keys.into_iter().map(String::as_str))
658            }
659        }
660    }
661}
662
663/// Compose's `ports:` list is heterogeneous: short strings ("8080:80"), bare
664/// numbers (8080), or long-form maps. We only need the container-side port.
665#[derive(Debug, Deserialize)]
666#[serde(untagged)]
667enum PortSpec {
668    Short(String),
669    Number(u16),
670    Long(LongPort),
671}
672
673#[derive(Debug, Deserialize)]
674struct LongPort {
675    target: u16,
676    #[serde(default)]
677    #[allow(dead_code)]
678    published: Option<serde_yaml::Value>,
679    #[serde(default)]
680    #[allow(dead_code)]
681    protocol: Option<String>,
682    #[serde(default)]
683    #[allow(dead_code)]
684    mode: Option<String>,
685}
686
687impl PortSpec {
688    fn parse_container_port(&self) -> Result<u16, String> {
689        match self {
690            PortSpec::Number(n) => Ok(*n),
691            PortSpec::Long(l) => Ok(l.target),
692            PortSpec::Short(s) => parse_short_port(s),
693        }
694    }
695}
696
697/// Compose short-form port shapes: `"80"`, `"8080:80"`, `"127.0.0.1:8080:80"`,
698/// `"8080:80/udp"`. We extract the container-side port and ignore host-side
699/// binding (yubaba's mesh handles that).
700fn parse_short_port(s: &str) -> Result<u16, String> {
701    let no_proto = s.split('/').next().unwrap_or(s);
702    let segments: Vec<&str> = no_proto.split(':').collect();
703    let container = segments
704        .last()
705        .ok_or_else(|| format!("port spec {s:?} is empty"))?;
706    container
707        .parse::<u16>()
708        .map_err(|e| format!("port spec {s:?}: container-side port {container:?} not a u16 ({e})"))
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714
715    const PINNED_NGINX: &str =
716        "nginx:1.25@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
717    const PINNED_GHCR: &str =
718        "ghcr.io/foo/bar:v1@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
719    const PINNED_LOCALHOST: &str =
720        "localhost:5000/svc:dev@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
721
722    #[test]
723    fn parse_image_ref_rejects_bare_tag() {
724        for bare in ["nginx", "nginx:1.25", "ghcr.io/foo/bar:v1"] {
725            let res = parse_image_ref(bare);
726            assert!(res.is_err(), "bare tag {bare:?} must reject");
727        }
728    }
729
730    #[test]
731    fn parse_image_ref_with_tag_and_digest() {
732        let r = parse_image_ref(PINNED_NGINX).expect("pinned parses");
733        assert_eq!(r.registry, "docker.io");
734        assert_eq!(r.repository, "library/nginx");
735        assert_eq!(r.tag, "1.25");
736        assert!(r.digest.starts_with("sha256:"));
737    }
738
739    #[test]
740    fn parse_image_ref_ghcr_pinned() {
741        let r = parse_image_ref(PINNED_GHCR).expect("pinned parses");
742        assert_eq!(r.registry, "ghcr.io");
743        assert_eq!(r.repository, "foo/bar");
744        assert_eq!(r.tag, "v1");
745    }
746
747    #[test]
748    fn parse_image_ref_localhost_port_pinned() {
749        let r = parse_image_ref(PINNED_LOCALHOST).expect("pinned parses");
750        assert_eq!(r.registry, "localhost:5000");
751        assert_eq!(r.repository, "svc");
752        assert_eq!(r.tag, "dev");
753    }
754
755    #[test]
756    fn parse_short_port_ok() {
757        assert_eq!(parse_short_port("80").unwrap(), 80);
758        assert_eq!(parse_short_port("8080:80").unwrap(), 80);
759        assert_eq!(parse_short_port("127.0.0.1:8080:80").unwrap(), 80);
760        assert_eq!(parse_short_port("8080:80/udp").unwrap(), 80);
761    }
762
763    #[test]
764    fn sanitize_mesh_ident_underscore_to_dash() {
765        let (n, w) = sanitize_mesh_ident("web_app");
766        assert_eq!(n, "web-app");
767        assert!(w.is_some());
768    }
769
770    #[test]
771    fn sanitize_mesh_ident_passthrough() {
772        let (n, w) = sanitize_mesh_ident("web-app");
773        assert_eq!(n, "web-app");
774        assert!(w.is_none());
775    }
776}