1use 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct ImportResult {
45 pub specs: Vec<WorkloadSpec>,
48
49 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 pub warnings: Vec<ImportWarning>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct ImportWarning {
58 pub path: String,
60 pub message: String,
62}
63
64#[derive(Debug, Error, PartialEq)]
66pub enum ImportError {
67 #[error("compose YAML parse error: {0}")]
69 Parse(String),
70
71 #[error("compose file has no `services:` block")]
73 NoServices,
74
75 #[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 #[error("service {service:?}: no `image:` field — yubaba requires an image reference")]
88 MissingImage { service: String },
89
90 #[error("service {service:?}: image {image:?} is not digest-pinned ({reason})")]
95 UnpinnedImage {
96 service: String,
97 image: String,
98 reason: String,
99 },
100}
101
102pub 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 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
154fn 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 requires: vec![],
276 healthcheck: None,
277 restart_policy,
278 archetype: None,
279 stop_policy: StopPolicy {
280 signal: 15,
281 grace_period: Millis::from_secs(10),
282 },
283 expose: ExposeSpec {
284 mesh: MeshExpose {
285 identity: MeshIdent(mesh_name),
286 ports: MeshExpose::anonymous_ports(mesh_ports),
289 allow_from: vec![],
290 },
291 public: None,
292 operator: None,
293 },
294 labels: HashMap::new(),
295 annotations: HashMap::new(),
296 };
297
298 Ok(spec)
299}
300
301fn sanitize_mesh_ident(name: &str) -> (String, Option<String>) {
306 let lowered = name.to_ascii_lowercase();
307 let sanitized: String = lowered
308 .chars()
309 .map(|c| if c == '_' { '-' } else { c })
310 .collect();
311 if sanitized != name {
312 let msg = format!(
313 "compose service name {name:?} rewritten to {sanitized:?} \
314 (mesh idents must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$)"
315 );
316 (sanitized, Some(msg))
317 } else {
318 (sanitized, None)
319 }
320}
321
322pub(crate) fn parse_image_ref(s: &str) -> Result<ImageRef, String> {
334 parse_pinned_image_ref(s)
335}
336
337pub(crate) fn parse_pinned_image_ref(s: &str) -> Result<ImageRef, String> {
345 let (head, dig_str) = s.split_once('@').ok_or_else(|| {
346 format!(
347 "image reference {s:?} must be digest-pinned (e.g. `repo:tag@sha256:<hex>`); \
348 bare-tag images are rejected — pin with @sha256:<digest>"
349 )
350 })?;
351
352 let hex = dig_str.strip_prefix("sha256:").ok_or_else(|| {
353 format!("image digest must start with `sha256:`, got {dig_str:?}")
354 })?;
355 if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
356 return Err(format!("sha256 digest must be non-empty hex, got {hex:?}"));
357 }
358
359 let (head2, tag_opt) = split_repo_and_tag(head);
360 let tag = tag_opt.unwrap_or_else(|| "latest".into());
361 let (registry, repository) = split_registry_and_repo(head2);
362
363 Ok(ImageRef {
364 registry,
365 repository,
366 tag,
367 digest: format!("sha256:{hex}"),
368 })
369}
370
371fn split_repo_and_tag(s: &str) -> (&str, Option<String>) {
375 let last_slash = s.rfind('/');
376 let search_from = last_slash.map(|i| i + 1).unwrap_or(0);
377 if let Some(colon) = s[search_from..].find(':') {
378 let abs = search_from + colon;
379 let head = &s[..abs];
380 let tag = &s[abs + 1..];
381 (head, Some(tag.to_string()))
382 } else {
383 (s, None)
384 }
385}
386
387fn split_registry_and_repo(head: &str) -> (String, String) {
393 if let Some((first, rest)) = head.split_once('/') {
394 if first == "localhost" || first.contains('.') || first.contains(':') {
395 return (first.to_string(), rest.to_string());
396 }
397 }
398 let repo = if head.contains('/') {
399 head.to_string()
400 } else {
401 format!("library/{head}")
402 };
403 ("docker.io".into(), repo)
404}
405
406fn translate_env(
407 service: &str,
408 environment: &Option<EnvList>,
409 warnings: &mut Vec<ImportWarning>,
410) -> Vec<EnvVar> {
411 let Some(env) = environment else {
412 return Vec::new();
413 };
414 let mut out = Vec::new();
415 match env {
416 EnvList::List(items) => {
417 for (i, item) in items.iter().enumerate() {
418 if let Some((k, v)) = item.split_once('=') {
419 out.push(EnvVar {
420 name: k.into(),
421 value: EnvValue::Literal { value: v.into() },
422 });
423 } else {
424 warnings.push(ImportWarning {
425 path: format!("services.{service}.environment[{i}]"),
426 message: format!(
427 "{item:?} omits a value (compose pulls it from the host shell). \
428 Provide a literal value or use EnvValue::FromSecret"
429 ),
430 });
431 }
432 }
433 }
434 EnvList::Map(map) => {
435 let mut keys: Vec<&String> = map.keys().collect();
436 keys.sort();
437 for k in keys {
438 let v = &map[k];
439 let value = yaml_scalar_to_string(v);
440 out.push(EnvVar {
441 name: k.clone(),
442 value: EnvValue::Literal { value },
443 });
444 }
445 }
446 }
447 out
448}
449
450fn yaml_scalar_to_string(v: &serde_yaml::Value) -> String {
451 match v {
452 serde_yaml::Value::String(s) => s.clone(),
453 serde_yaml::Value::Number(n) => n.to_string(),
454 serde_yaml::Value::Bool(b) => b.to_string(),
455 serde_yaml::Value::Null => String::new(),
456 other => serde_yaml::to_string(other).unwrap_or_default().trim().to_string(),
457 }
458}
459
460fn translate_ports(
461 service: &str,
462 ports: &[PortSpec],
463 warnings: &mut Vec<ImportWarning>,
464) -> Vec<u16> {
465 let mut out = Vec::new();
466 for (i, p) in ports.iter().enumerate() {
467 match p.parse_container_port() {
468 Ok(port) => {
469 if !out.contains(&port) {
470 out.push(port);
471 }
472 }
473 Err(msg) => {
474 warnings.push(ImportWarning {
475 path: format!("services.{service}.ports[{i}]"),
476 message: msg,
477 });
478 }
479 }
480 }
481 out
482}
483
484fn translate_volumes(
485 service: &str,
486 items: &[String],
487 warnings: &mut Vec<ImportWarning>,
488) -> (Vec<VolumeMount>, bool) {
489 let mut out = Vec::new();
490 let mut has_bind = false;
491 for (i, raw) in items.iter().enumerate() {
492 let parts: Vec<&str> = raw.split(':').collect();
493 let (source, target, read_only) = match parts.as_slice() {
494 [target] => (None, *target, false),
495 [src, tgt] => (Some(*src), *tgt, false),
496 [src, tgt, mode] => (Some(*src), *tgt, mode.contains("ro")),
497 _ => {
498 warnings.push(ImportWarning {
499 path: format!("services.{service}.volumes[{i}]"),
500 message: format!("volume spec {raw:?} could not be parsed; skipped"),
501 });
502 continue;
503 }
504 };
505
506 let target = PathBuf::from(target);
507 let source = if let Some(src) = source {
508 if src.starts_with('/') || src.starts_with('.') || src.starts_with('~') {
509 has_bind = true;
510 VolumeSource::Bind {
511 host_path: PathBuf::from(src),
512 }
513 } else {
514 VolumeSource::Named { name: src.into() }
515 }
516 } else {
517 VolumeSource::Named {
518 name: format!("anon-{}-{}", service, i),
519 }
520 };
521
522 out.push(VolumeMount {
523 source,
524 target,
525 read_only,
526 });
527 }
528 (out, has_bind)
529}
530
531fn translate_restart(
532 service: &str,
533 restart: Option<&str>,
534 warnings: &mut Vec<ImportWarning>,
535) -> RestartPolicy {
536 match restart {
537 None => RestartPolicy::Always,
538 Some("always") => RestartPolicy::Always,
539 Some("no") => RestartPolicy::Never,
540 Some("unless-stopped") => {
541 warnings.push(ImportWarning {
542 path: format!("services.{service}.restart"),
543 message: "restart=unless-stopped translated to RestartPolicy::Always — \
544 yubaba has no manual-stop concept the policy can opt out of"
545 .into(),
546 });
547 RestartPolicy::Always
548 }
549 Some(other) if other.starts_with("on-failure") => RestartPolicy::OnFailure {
550 max_attempts: 5,
551 backoff: crate::BackoffPolicy {
552 initial_ms: 1000,
553 max_ms: 30_000,
554 multiplier: 2.0,
555 },
556 },
557 Some(other) => {
558 warnings.push(ImportWarning {
559 path: format!("services.{service}.restart"),
560 message: format!(
561 "unknown restart policy {other:?}; defaulted to RestartPolicy::Always"
562 ),
563 });
564 RestartPolicy::Always
565 }
566 }
567}
568
569#[derive(Debug, Deserialize)]
572struct ComposeFile {
573 #[serde(default)]
574 #[allow(dead_code)]
575 version: Option<String>,
576 #[serde(default)]
577 services: HashMap<String, ComposeService>,
578 #[serde(default)]
579 networks: HashMap<String, serde_yaml::Value>,
580 #[serde(default)]
581 #[allow(dead_code)]
582 volumes: HashMap<String, serde_yaml::Value>,
583}
584
585#[derive(Debug, Deserialize, Default)]
586struct ComposeService {
587 #[serde(default)]
588 image: Option<String>,
589 #[serde(default)]
590 build: Option<serde_yaml::Value>,
591 #[serde(default)]
592 command: Option<StringOrList>,
593 #[serde(default)]
594 entrypoint: Option<StringOrList>,
595 #[serde(default)]
596 environment: Option<EnvList>,
597 #[serde(default)]
598 ports: Vec<PortSpec>,
599 #[serde(default)]
600 depends_on: Option<DependsOn>,
601 #[serde(default)]
602 volumes: Vec<String>,
603 #[serde(default)]
604 network_mode: Option<String>,
605 #[serde(default)]
606 networks: Vec<String>,
607 #[serde(default)]
608 user: Option<String>,
609 #[serde(default)]
610 working_dir: Option<String>,
611 #[serde(default)]
612 restart: Option<String>,
613 #[serde(default)]
614 healthcheck: Option<serde_yaml::Value>,
615}
616
617#[derive(Debug, Deserialize)]
618#[serde(untagged)]
619enum StringOrList {
620 String(String),
621 List(Vec<String>),
622}
623
624impl StringOrList {
625 fn into_argv(&self) -> Vec<String> {
626 match self {
627 StringOrList::String(s) => shell_split(s),
628 StringOrList::List(v) => v.clone(),
629 }
630 }
631}
632
633fn shell_split(s: &str) -> Vec<String> {
637 s.split_whitespace().map(str::to_string).collect()
638}
639
640#[derive(Debug, Deserialize)]
641#[serde(untagged)]
642enum EnvList {
643 List(Vec<String>),
644 Map(HashMap<String, serde_yaml::Value>),
645}
646
647#[derive(Debug, Deserialize)]
648#[serde(untagged)]
649enum DependsOn {
650 List(Vec<String>),
651 Map(HashMap<String, serde_yaml::Value>),
652}
653
654impl DependsOn {
655 fn iter_names(&self) -> Box<dyn Iterator<Item = &str> + '_> {
656 match self {
657 DependsOn::List(v) => Box::new(v.iter().map(String::as_str)),
658 DependsOn::Map(m) => {
659 let mut keys: Vec<&String> = m.keys().collect();
660 keys.sort();
661 Box::new(keys.into_iter().map(String::as_str))
662 }
663 }
664 }
665}
666
667#[derive(Debug, Deserialize)]
670#[serde(untagged)]
671enum PortSpec {
672 Short(String),
673 Number(u16),
674 Long(LongPort),
675}
676
677#[derive(Debug, Deserialize)]
678struct LongPort {
679 target: u16,
680 #[serde(default)]
681 #[allow(dead_code)]
682 published: Option<serde_yaml::Value>,
683 #[serde(default)]
684 #[allow(dead_code)]
685 protocol: Option<String>,
686 #[serde(default)]
687 #[allow(dead_code)]
688 mode: Option<String>,
689}
690
691impl PortSpec {
692 fn parse_container_port(&self) -> Result<u16, String> {
693 match self {
694 PortSpec::Number(n) => Ok(*n),
695 PortSpec::Long(l) => Ok(l.target),
696 PortSpec::Short(s) => parse_short_port(s),
697 }
698 }
699}
700
701fn parse_short_port(s: &str) -> Result<u16, String> {
705 let no_proto = s.split('/').next().unwrap_or(s);
706 let segments: Vec<&str> = no_proto.split(':').collect();
707 let container = segments
708 .last()
709 .ok_or_else(|| format!("port spec {s:?} is empty"))?;
710 container
711 .parse::<u16>()
712 .map_err(|e| format!("port spec {s:?}: container-side port {container:?} not a u16 ({e})"))
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718
719 const PINNED_NGINX: &str =
720 "nginx:1.25@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
721 const PINNED_GHCR: &str =
722 "ghcr.io/foo/bar:v1@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
723 const PINNED_LOCALHOST: &str =
724 "localhost:5000/svc:dev@sha256:abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd";
725
726 #[test]
727 fn parse_image_ref_rejects_bare_tag() {
728 for bare in ["nginx", "nginx:1.25", "ghcr.io/foo/bar:v1"] {
729 let res = parse_image_ref(bare);
730 assert!(res.is_err(), "bare tag {bare:?} must reject");
731 }
732 }
733
734 #[test]
735 fn parse_image_ref_with_tag_and_digest() {
736 let r = parse_image_ref(PINNED_NGINX).expect("pinned parses");
737 assert_eq!(r.registry, "docker.io");
738 assert_eq!(r.repository, "library/nginx");
739 assert_eq!(r.tag, "1.25");
740 assert!(r.digest.starts_with("sha256:"));
741 }
742
743 #[test]
744 fn parse_image_ref_ghcr_pinned() {
745 let r = parse_image_ref(PINNED_GHCR).expect("pinned parses");
746 assert_eq!(r.registry, "ghcr.io");
747 assert_eq!(r.repository, "foo/bar");
748 assert_eq!(r.tag, "v1");
749 }
750
751 #[test]
752 fn parse_image_ref_localhost_port_pinned() {
753 let r = parse_image_ref(PINNED_LOCALHOST).expect("pinned parses");
754 assert_eq!(r.registry, "localhost:5000");
755 assert_eq!(r.repository, "svc");
756 assert_eq!(r.tag, "dev");
757 }
758
759 #[test]
760 fn parse_short_port_ok() {
761 assert_eq!(parse_short_port("80").unwrap(), 80);
762 assert_eq!(parse_short_port("8080:80").unwrap(), 80);
763 assert_eq!(parse_short_port("127.0.0.1:8080:80").unwrap(), 80);
764 assert_eq!(parse_short_port("8080:80/udp").unwrap(), 80);
765 }
766
767 #[test]
768 fn sanitize_mesh_ident_underscore_to_dash() {
769 let (n, w) = sanitize_mesh_ident("web_app");
770 assert_eq!(n, "web-app");
771 assert!(w.is_some());
772 }
773
774 #[test]
775 fn sanitize_mesh_ident_passthrough() {
776 let (n, w) = sanitize_mesh_ident("web-app");
777 assert_eq!(n, "web-app");
778 assert!(w.is_none());
779 }
780}