Docker Compose Validator — Rust source
Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! compose-validator — structural checks for a Docker Compose file. Rust port
//! (canonical TS: `src/lib/compose-validator.ts`; Go twin: `cli/compose-validator`).
//! Checks: root/services mappings, per-service image or build, port syntax
//! ("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"), environment shape
//! (mapping or KEY=value list), volumes lists, depends_on references and
//! acyclicity — same rules, paths and message texts as the TS contract. No
//! external crates: the canonical lib parses with the npm `yaml` package; here,
//! as in every port of this set, a minimal hand-rolled parser covers the
//! compose subset — block mappings/sequences, single-line flow collections,
//! quoted and plain scalars, comments. Anchors/aliases/merge keys, block
//! scalars (| >), multi-line plain scalars and multi-document streams are
//! outside the subset. Never panics on malformed input; parse errors travel in
//! `ComposeValidateResult.error` (`None` mirrors TS `null` on success).
//! The tree keeps key order with `YNode::Map(Vec<(String, YNode)>)`.
use std::collections::HashMap;
/// One parsed YAML value in document order (maps keep key order).
#[derive(Clone, Debug)]
pub enum YNode {
Null,
Bool(bool),
Int(i64),
Float(f64),
Str(String),
Seq(Vec<YNode>),
Map(Vec<(String, YNode)>),
}
/// One structural finding at one YAML path. Mirrors ComposeIssue.
#[derive(Debug)]
pub struct ComposeIssue {
pub path: String,
pub message: String,
}
/// Mirrors ComposeValidateResult: `error` is `None` unless parsing failed.
#[derive(Debug)]
pub struct ComposeValidateResult {
pub valid: bool,
pub issues: Vec<ComposeIssue>,
pub error: Option<String>,
}
fn is_digits(p: &str) -> bool { !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) }
/// /^[-+]?[0-9]+$/ by hand (no std regex).
fn int_re(t: &str) -> bool {
let b = t.as_bytes();
let mut k = 0;
if k < b.len() && (b[k] == b'-' || b[k] == b'+') { k += 1; }
k < b.len() && b[k..].iter().all(|c| c.is_ascii_digit())
}
/// /^[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?$/ by hand.
fn float_re(t: &str) -> bool {
let b = t.as_bytes();
let mut k = 0;
if k < b.len() && (b[k] == b'-' || b[k] == b'+') { k += 1; }
let mut digits = 0;
while k < b.len() && b[k].is_ascii_digit() { k += 1; digits += 1; }
if k < b.len() && b[k] == b'.' {
k += 1;
while k < b.len() && b[k].is_ascii_digit() { k += 1; digits += 1; }
}
if digits == 0 { return false; }
if k < b.len() && (b[k] == b'e' || b[k] == b'E') {
k += 1;
if k < b.len() && (b[k] == b'-' || b[k] == b'+') { k += 1; }
let mut ed = 0;
while k < b.len() && b[k].is_ascii_digit() { k += 1; ed += 1; }
if ed == 0 { return false; }
}
k == b.len()
}
/// Core-schema resolution of a plain scalar: Null/Bool/Int/Float/Str.
fn plain_scalar(t: &str) -> YNode {
match t {
"" | "~" | "null" | "Null" | "NULL" => return YNode::Null,
"true" | "True" | "TRUE" => return YNode::Bool(true),
"false" | "False" | "FALSE" => return YNode::Bool(false),
_ => {}
}
if int_re(t) {
return match t.parse::<i64>() {
Ok(n) => YNode::Int(n),
Err(_) => YNode::Float(t.parse::<f64>().unwrap_or(0.0)),
};
}
if float_re(t) {
return YNode::Float(t.parse::<f64>().unwrap_or(0.0));
}
YNode::Str(t.to_string())
}
/// Quoted scalar at s[i]; returns (value, next index). "..." honors escapes,
/// '...' doubles the quote.
fn quoted_at(s: &str, i0: usize) -> Result<(String, usize), String> {
let b = s.as_bytes();
let q = b[i0];
let mut i = i0 + 1;
let mut out = String::new();
while i < s.len() {
let ch = b[i];
if q == b'"' && ch == b'\\' {
let nxt = if i + 1 < s.len() { b[i + 1] } else { 0 };
match nxt {
b'n' => out.push('\n'),
b't' => out.push('\t'),
b'r' => out.push('\r'),
_ => out.push(nxt as char),
}
i += 2;
} else if ch == q {
if q == b'\'' && i + 1 < s.len() && b[i + 1] == b'\'' {
out.push('\'');
i += 2;
} else {
return Ok((out, i + 1));
}
} else {
let c = s[i..].chars().next().unwrap();
out.push(c);
i += c.len_utf8();
}
}
Err("Invalid YAML: unterminated quoted scalar".to_string())
}
/// One flow node at s[i]; returns (value, next index).
fn flow_at(s: &str, i0: usize) -> Result<(YNode, usize), String> {
let b = s.as_bytes();
let mut i = i0;
while i < s.len() && b[i] == b' ' { i += 1; }
if i < s.len() && b[i] == b'[' {
let mut out: Vec<YNode> = vec![];
i += 1;
loop {
while i < s.len() && b[i] == b' ' { i += 1; }
if i >= s.len() { return Err("Invalid YAML: unterminated flow sequence".to_string()); }
if b[i] == b']' { return Ok((YNode::Seq(out), i + 1)); }
let (v, ni) = flow_at(s, i)?;
out.push(v);
i = ni;
while i < s.len() && (b[i] == b' ' || b[i] == b',') { i += 1; }
}
}
if i < s.len() && b[i] == b'{' {
let mut out: Vec<(String, YNode)> = vec![];
i += 1;
loop {
while i < s.len() && b[i] == b' ' { i += 1; }
if i >= s.len() { return Err("Invalid YAML: unterminated flow mapping".to_string()); }
if b[i] == b'}' { return Ok((YNode::Map(out), i + 1)); }
let k;
if b[i] == b'"' || b[i] == b'\'' {
let (kk, ni) = quoted_at(s, i)?;
k = kk;
i = ni;
} else {
let mut j = i;
while j < s.len() && b[j] != b':' && b[j] != b',' && b[j] != b'}' { j += 1; }
if j >= s.len() || b[j] != b':' {
return Err("Invalid YAML: flow mapping entry without a colon".to_string());
}
k = s[i..j].trim().to_string();
i = j + 1;
}
while i < s.len() && b[i] == b' ' { i += 1; }
let v;
if i < s.len() && b[i] != b',' && b[i] != b'}' {
let (vv, ni) = flow_at(s, i)?;
v = vv;
i = ni;
} else {
v = YNode::Null;
}
out.push((k, v));
while i < s.len() && (b[i] == b' ' || b[i] == b',') { i += 1; }
}
}
if i < s.len() && (b[i] == b'"' || b[i] == b'\'') {
return quoted_at(s, i).map(|(v, n)| (YNode::Str(v), n));
}
let mut j = i;
while j < s.len() && b[j] != b',' && b[j] != b']' && b[j] != b'}' { j += 1; }
Ok((plain_scalar(s[i..j].trim()), j))
}
/// `key: rest` split; None when the line is not a mapping entry. The first
/// colon followed by a space (or ending the line) wins; quoted keys first.
fn key_split(s: &str) -> Result<Option<(String, String)>, String> {
if s.starts_with('"') || s.starts_with('\'') {
let (key, j) = match quoted_at(s, 0) {
Ok(x) => x,
Err(_) => return Ok(None),
};
let rest = s[j..].trim_start_matches(' ');
return Ok(if rest.starts_with(':') { Some((key, rest[1..].to_string())) } else { None });
}
let b = s.as_bytes();
for j in 0..s.len() {
if b[j] == b':' && (j + 1 == s.len() || b[j + 1] == b' ') {
return Ok(Some((s[..j].trim_end_matches(' ').to_string(), s[j + 1..].to_string())));
}
}
Ok(None)
}
/// Content lines as (indent, body): blanks, comments, %directives and a ---
/// marker dropped; tab indentation rejected.
fn content_lines(text: &str) -> Result<Vec<(usize, String)>, String> {
let mut out = vec![];
for raw in text.split('\n') {
let crlf = raw.strip_suffix('\r').unwrap_or(raw);
let indented = crlf.trim_start_matches(' ');
let indent = crlf.len() - indented.len();
let body = indented.trim_end_matches(' ');
if body.is_empty() || body.starts_with('#') || body.starts_with('%') || body == "---" {
continue;
}
if crlf.as_bytes()[..indent].contains(&b'\t') {
return Err("Invalid YAML: tab in indentation".to_string());
}
out.push((indent, body.to_string()));
}
Ok(out)
}
fn is_item(s: &str) -> bool { s == "-" || s.starts_with("- ") }
/// The node whose first line is ls[i] at the given indent; (value, next).
fn block_at(ls: &mut Vec<(usize, String)>, i0: usize, indent: usize) -> Result<(YNode, usize), String> {
let mut i = i0;
if is_item(&ls[i].1) {
let mut out: Vec<YNode> = vec![];
while i < ls.len() && ls[i].0 == indent && is_item(&ls[i].1) {
let content = if ls[i].1.len() > 2 { ls[i].1[2..].to_string() } else { String::new() };
let v;
if content.trim().is_empty() || content.trim_start().starts_with('#') {
i += 1;
if i < ls.len() && ls[i].0 > indent {
let (vv, ni) = block_at(ls, i, ls[i].0)?;
v = vv;
i = ni;
} else {
v = YNode::Null;
}
} else {
ls[i] = (indent + 2, content);
let (vv, ni) = block_at(ls, i, indent + 2)?;
v = vv;
i = ni;
}
out.push(v);
}
return Ok((YNode::Seq(out), i));
}
if key_split(&ls[i].1)?.is_none() {
let v = inline_value(&ls[i].1)?;
return Ok((v, i + 1));
}
let mut out: Vec<(String, YNode)> = vec![];
while i < ls.len() && ls[i].0 == indent && !is_item(&ls[i].1) {
let (key, rest0) = match key_split(&ls[i].1)? {
Some(kv) => kv,
None => break,
};
let rest = rest0.trim().to_string();
i += 1;
if !rest.is_empty() {
let v = inline_value(&rest)?;
out.push((key, v));
} else if i < ls.len() && ls[i].0 > indent {
let (v, ni) = block_at(ls, i, ls[i].0)?;
out.push((key, v));
i = ni;
} else if i < ls.len() && ls[i].0 == indent && is_item(&ls[i].1) {
let (v, ni) = block_at(ls, i, indent)?;
out.push((key, v));
i = ni;
} else {
out.push((key, YNode::Null));
}
}
Ok((YNode::Map(out), i))
}
/// The value part of `key: value` — flow, quoted, or plain (comment cut).
fn inline_value(rest: &str) -> Result<YNode, String> {
let c0 = *rest.as_bytes().get(0).unwrap_or(&0);
if c0 == b'[' || c0 == b'{' {
let (v, j) = flow_at(rest, 0)?;
if rest[j..].chars().any(|c| c != ' ' && c != '#') {
return Err("Invalid YAML: trailing content after flow value".to_string());
}
return Ok(v);
}
if c0 == b'"' || c0 == b'\'' {
let (v, j) = quoted_at(rest, 0)?;
if rest[j..].chars().any(|c| c != ' ' && c != '#') {
return Err("Invalid YAML: trailing content after quoted value".to_string());
}
return Ok(v);
}
let t = match rest.find(" #") {
Some(c) => &rest[..c],
None => rest,
};
Ok(plain_scalar(t.trim()))
}
/// The minimal parser: text → tree (Map variants keep document order).
fn parse_yaml(text: &str) -> Result<YNode, String> {
let mut ls = content_lines(text)?;
if ls.is_empty() {
return Ok(YNode::Null);
}
let start = ls[0].0;
let (v, i) = block_at(&mut ls, 0, start)?;
if i != ls.len() {
return Err("Invalid YAML: inconsistent indentation".to_string());
}
Ok(v)
}
fn is_map(v: &YNode) -> bool { matches!(v, YNode::Map(_)) }
/// Presence check independent of value (TS `in` semantics).
fn map_get<'a>(v: &'a YNode, key: &str) -> Option<&'a YNode> {
match v {
YNode::Map(m) => m.iter().find(|(k, _)| k == key).map(|(_, x)| x),
_ => None,
}
}
/// JavaScript String(number) for the values the messages can hit.
fn num_text(f: f64) -> String {
if !f.is_finite() {
return "null".to_string();
}
if f.trunc() == f && f.abs() < 1e21 {
format!("{}", f as i64)
} else {
format!("{}", f)
}
}
/// TS String(value) form for depends_on coercion and messages.
fn ts_str(v: &YNode) -> String {
match v {
YNode::Null => "null".to_string(),
YNode::Bool(true) => "true".to_string(),
YNode::Bool(false) => "false".to_string(),
YNode::Int(n) => n.to_string(),
YNode::Float(f) => num_text(*f),
YNode::Str(s) => s.clone(),
YNode::Seq(items) => items.iter().map(ts_str).collect::<Vec<_>>().join(","),
YNode::Map(_) => "[object Object]".to_string(),
}
}
/// /^[^=]+=./s — at least one non-'=' char, then '=', then anything.
fn env_kv_ok(s: &str) -> bool {
match s.find('=') {
Some(p) => p >= 1,
None => false,
}
}
/// One ports entry; an issue string or None. "8080", "80:8080",
/// "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass.
fn port_issue(entry: &YNode) -> Option<String> {
match entry {
YNode::Int(n) => {
if *n < 0 || *n > 65535 {
Some(format!("port {} out of range 0-65535", n))
} else {
None
}
}
YNode::Float(f) => {
if !f.is_finite() || f.trunc() != *f {
return Some("port must be a string or integer".to_string());
}
if *f < 0.0 || *f > 65535.0 {
Some(format!("port {} out of range 0-65535", num_text(*f)))
} else {
None
}
}
YNode::Str(s) => {
let slash = s.find('/');
let proto = match slash {
Some(i) => &s[i + 1..],
None => "",
};
if !proto.is_empty() && proto != "tcp" && proto != "udp" {
return Some(format!("unknown protocol \"{}\" (use tcp or udp)", proto));
}
let body = if proto.is_empty() { s.as_str() } else { &s[..slash.unwrap()] };
let parts: Vec<&str> = body.split(':').collect();
// Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
if parts.iter().any(|p| !is_digits(p)) {
return None;
}
if parts.len() > 3 {
return Some("port must have 1-3 colon-separated parts".to_string());
}
for p in &parts {
let n: f64 = p.parse().unwrap_or(0.0); // digits only
if n < 0.0 || n > 65535.0 {
return Some(format!("port {} out of range 0-65535", p));
}
}
None
}
_ => Some("port must be a string or integer".to_string()), // bool, null, maps, lists
}
}
fn push(out: &mut Vec<ComposeIssue>, path: &str, message: &str) {
out.push(ComposeIssue { path: path.to_string(), message: message.to_string() });
}
/// Walk the document; append issues in TS order (root, services, per-service
/// in document order, then depends_on cycle detection).
fn check(root: &YNode, out: &mut Vec<ComposeIssue>) {
if !is_map(root) {
push(out, "$", "compose root must be a mapping");
return;
}
let services = match map_get(root, "services") {
Some(s) if is_map(s) => s,
_ => {
push(out, "$.services", "missing or invalid \"services\" mapping");
return;
}
};
let svc_map: &[(String, YNode)] = match services {
YNode::Map(m) => m,
_ => unreachable!(),
};
let ids: Vec<String> = svc_map.iter().map(|(k, _)| k.clone()).collect();
let get = |id: &str| -> Option<&YNode> {
svc_map.iter().find(|(k, _)| k == id).map(|(_, v)| v)
};
if ids.is_empty() {
push(out, "$.services", "services must not be empty");
}
for id in &ids {
let svc = match get(id) {
Some(s) => s,
None => continue,
};
let at = format!("$.services.{}", id);
if !is_map(svc) {
push(out, &at, "service must be a mapping");
continue;
}
if map_get(svc, "image").is_none() && map_get(svc, "build").is_none() {
push(out, &at, "service needs image or build");
}
if let Some(ports) = map_get(svc, "ports") {
match ports {
YNode::Seq(items) => {
for (i, p) in items.iter().enumerate() {
if let Some(msg) = port_issue(p) {
push(out, &format!("{}.ports[{}]", at, i), &msg);
}
}
}
_ => push(out, &format!("{}.ports", at), "ports must be a list"),
}
}
if let Some(env) = map_get(svc, "environment") {
match env {
YNode::Map(m) => {
for (k, v) in m {
let scalar = matches!(
v,
YNode::Null | YNode::Bool(_) | YNode::Int(_) | YNode::Float(_) | YNode::Str(_)
);
if !scalar {
push(out, &format!("{}.environment.{}", at, k), "environment values must be scalars");
}
}
}
YNode::Seq(items) => {
for (i, e) in items.iter().enumerate() {
let ok = match e {
YNode::Str(s) => env_kv_ok(s),
_ => false,
};
if !ok {
push(
out,
&format!("{}.environment[{}]", at, i),
"list environment entries must look like KEY=value",
);
}
}
}
_ => push(out, &format!("{}.environment", at), "environment must be a mapping or a list"),
}
}
if let Some(vols) = map_get(svc, "volumes") {
if !matches!(vols, YNode::Seq(_)) {
push(out, &format!("{}.volumes", at), "volumes must be a list");
}
}
if let Some(dep) = map_get(svc, "depends_on") {
if !matches!(dep, YNode::Seq(_) | YNode::Str(_) | YNode::Map(_)) {
push(out, &format!("{}.depends_on", at), "depends_on must be a string, list or mapping");
} else {
let names: Vec<String> = match dep {
YNode::Map(m) => m.iter().map(|(k, _)| k.clone()).collect(),
YNode::Seq(items) => items.iter().map(ts_str).collect(),
YNode::Str(s) => vec![s.clone()],
_ => vec![],
};
for (i, n) in names.iter().enumerate() {
if get(n).is_none() {
push(out, &format!("{}.depends_on[{}]", at, i), &format!("unknown service \"{}\"", n));
}
}
}
}
}
// depends_on cycle detection (map-form conditions do not affect the graph).
let mut color: HashMap<String, u8> = HashMap::new();
for id in &ids {
visit(svc_map, id, &[], &mut color, out);
}
}
fn visit(svc_map: &[(String, YNode)], sid: &str, stack: &[String],
color: &mut HashMap<String, u8>, out: &mut Vec<ComposeIssue>) {
match color.get(sid) {
Some(2) => return,
Some(1) => {
let from = stack.iter().position(|s| s == sid).unwrap_or(0);
let mut chain: Vec<String> = stack[from..].to_vec();
chain.push(sid.to_string());
push(out, "$.services", &format!("depends_on cycle: {}", chain.join(" -> ")));
return;
}
_ => {}
}
color.insert(sid.to_string(), 1);
let svc = svc_map.iter().find(|(k, _)| k == sid).map(|(_, v)| v);
if let Some(s) = svc {
if is_map(s) {
if let Some(raw) = map_get(s, "depends_on") {
let names: Vec<String> = match raw {
YNode::Str(s2) => vec![s2.clone()],
YNode::Seq(items) => items
.iter()
.filter_map(|e| match e {
YNode::Str(s2) => Some(s2.clone()),
_ => None,
})
.collect(),
YNode::Map(m) => m.iter().map(|(k, _)| k.clone()).collect(),
_ => vec![],
};
for n in &names {
if svc_map.iter().any(|(k, _)| k == n) {
let mut next = stack.to_vec();
next.push(sid.to_string());
visit(svc_map, n, &next, color, out);
}
}
}
}
}
color.insert(sid.to_string(), 2);
}
/// Validate a Docker Compose file.
pub fn validate_compose(raw: &str) -> ComposeValidateResult {
if raw.trim().is_empty() {
return ComposeValidateResult {
valid: false,
issues: vec![],
error: Some("A compose document is required".to_string()),
};
}
let root = match parse_yaml(raw) {
Ok(r) => r,
Err(e) => {
return ComposeValidateResult { valid: false, issues: vec![], error: Some(e) };
}
};
let mut issues: Vec<ComposeIssue> = vec![];
check(&root, &mut issues);
if issues.is_empty() {
ComposeValidateResult { valid: true, issues: vec![], error: None }
} else {
ComposeValidateResult { valid: false, issues, error: None }
}
}
// Example:
// let r = validate_compose("services:\n web:\n image: nginx:1.25\n ports:\n - \"8080:80\"\n db:\n image: postgres:16\n depends_on: web");
// assert!(r.valid);
// let bad = validate_compose("services:\n web:\n image: nginx\n ports: [\"99999\"]");
// assert_eq!(bad.issues[0].path, "$.services.web.ports[0]");
// assert_eq!(bad.issues[0].message, "port 99999 out of range 0-65535");
// let cyc = validate_compose("services:\n a:\n image: x\n depends_on: b\n b:\n image: y\n depends_on: a");
// assert_eq!(cyc.issues[0].message, "depends_on cycle: a -> b -> a");
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →