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