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