use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::LazyLock;
use serde::Deserialize;
use serde_json::Value;
use crate::js::{js_number, js_space, js_trim, truthy, utf16_cmp};
use crate::types::{Diagnostic, Object, Severity};
pub const WORKFLOW_DIALECT: &str = "instruction/workflow";
pub const WORKFLOW_REGISTRY_JSON: &str = include_str!("workflow-registry.json");
#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorkflowKind {
#[serde(default)]
pub fields: Vec<String>,
#[serde(default)]
pub required: Vec<String>,
#[serde(default)]
pub start: bool,
#[serde(default)]
pub summary: String,
}
#[derive(Clone, Copy, Debug, Default, Deserialize)]
pub struct WorkflowLimits {
pub steps: usize,
pub body_depth: usize,
pub retry_max: f64,
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorkflowRegistry {
pub format: String,
pub dialect: String,
pub revision: String,
pub kinds: BTreeMap<String, WorkflowKind>,
pub common_fields: Vec<String>,
pub limits: WorkflowLimits,
}
static REGISTRY: LazyLock<WorkflowRegistry> = LazyLock::new(|| serde_json::from_str(WORKFLOW_REGISTRY_JSON).unwrap_or_default());
pub fn workflow_registry() -> &'static WorkflowRegistry {
®ISTRY
}
const DEFINITION_FIELDS: &[&str] = &[
"name",
"steps",
"description",
"armed",
"inputs",
"outputs",
"concurrency",
"key",
"limits",
"priority",
"durable",
"state",
"unload",
"tool",
"act_for",
"$schema",
];
const P: &str = ":::workflow";
pub const WORKFLOW_SCOPES: &[(&str, &str)] =
&[("batch", "body"), ("foreach", "body"), ("iterate", "body"), ("parallel", "branches"), ("race", "branches"), ("subgraph", "body")];
pub fn workflow_scope(kind: &str) -> Option<&'static str> {
WORKFLOW_SCOPES.iter().find(|(k, _)| *k == kind).map(|(_, f)| *f)
}
fn is_name(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 64
&& (b[0].is_ascii_alphabetic() || b[0] == b'_')
&& b[1..].iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
}
fn is_extension_field(s: &str) -> bool {
s.strip_prefix("x-")
.is_some_and(|r| !r.is_empty() && r.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c)))
}
fn is_custom_kind(s: &str) -> bool {
let part = |p: &str| {
let b = p.as_bytes();
!b.is_empty() && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
};
s.split_once(':').is_some_and(|(a, k)| part(a) && part(k))
}
fn is_on_error(s: &str) -> bool {
s == "fail" || s == "continue" || s.strip_prefix("goto:").is_some_and(is_name)
}
fn integer(v: &Value) -> Option<f64> {
v.as_f64().filter(|f| f.is_finite() && f.fract() == 0.0)
}
fn quote(s: &str) -> String {
format!("\"{s}\"")
}
fn keys(o: &Object) -> Vec<&str> {
let mut k: Vec<&str> = o.keys().map(String::as_str).collect();
k.sort_by(|a, b| utf16_cmp(a, b));
k
}
fn join<'a>(a: &[&'a str], b: &[&'a str]) -> Vec<&'a str> {
a.iter().chain(b).copied().collect()
}
fn steps_of(v: Option<&Value>) -> Option<&Object> {
v.and_then(|b| b.get("steps")).and_then(Value::as_object)
}
fn is_body(v: Option<&Value>) -> bool {
v.and_then(Value::as_object).is_some_and(|o| o.len() == 1 && o.get("steps").is_some_and(Value::is_object))
}
pub fn workflow_diagnostics(definition: &Value, extensions: Option<&Object>) -> Vec<Diagnostic> {
check(definition, &[], 0, extensions)
}
pub(crate) fn check(definition: &Value, lines: &[(u32, &str)], at: u32, extensions: Option<&Object>) -> Vec<Diagnostic> {
let mut c = Checker { out: Vec::new(), lines, at, extensions, reg: workflow_registry() };
let Some(def) = definition.as_object() else { return c.out }; if !def.get("name").and_then(Value::as_str).is_some_and(is_name) {
c.diag(
"invalid-workflow",
format!("{P}: its name is required: 1 to 64 letters, digits, \"_\" and \"-\", starting with a letter or \"_\""),
&["name"],
);
}
for k in keys(def) {
if !DEFINITION_FIELDS.contains(&k) && !is_extension_field(k) {
c.diag("invalid-workflow", format!("{P}: \"{k}\" is not a field of a workflow definition"), &[k]);
}
}
if let Some(concurrency) = def.get("concurrency").and_then(Value::as_object)
&& concurrency.get("scope").and_then(Value::as_str) == Some("key")
&& !def.contains_key("key")
{
c.diag("invalid-workflow", format!("{P}: key-scoped concurrency needs the workflow's key"), &["concurrency"]);
}
match def.get("steps").and_then(Value::as_object) {
Some(steps) if !steps.is_empty() => c.scope(steps, &[], &["steps"], 0),
_ => c.diag("invalid-workflow", format!("{P}: its steps are a nonempty mapping of step names to steps"), &["steps"]),
}
let line = |d: &Diagnostic| d.range.map_or(0, |r| r.start);
c.out.sort_by(|a, b| line(a).cmp(&line(b)).then_with(|| a.code.cmp(b.code)).then_with(|| utf16_cmp(&a.message, &b.message)));
c.out
}
struct Checker<'a> {
out: Vec<Diagnostic>,
lines: &'a [(u32, &'a str)],
at: u32,
extensions: Option<&'a Object>,
reg: &'static WorkflowRegistry,
}
impl Checker<'_> {
fn diag(&mut self, code: &'static str, message: String, path: &[&str]) {
let line = if self.lines.is_empty() { 0 } else { locate(self.lines, path).unwrap_or(self.at) };
self.out.push(Diagnostic::new(code, Severity::Error, message, line));
}
fn kind(&self, k: &str) -> Option<&'static WorkflowKind> {
self.reg.kinds.get(k)
}
fn scope<'a>(&mut self, steps: &'a Object, prefix: &[&'a str], at: &[&'a str], depth: usize) {
let names = keys(steps);
let limits = self.reg.limits;
if names.len() > limits.steps {
self.diag("limit-exceeded", format!("{P}: {} steps in one scope; the limit is {}", names.len(), limits.steps), at);
}
let path = |id: &'a str| join(at, &[id]);
let label = |id: &str| quote(&prefix.iter().copied().chain([id]).collect::<Vec<_>>().join("."));
let kind_of =
|id: &str| -> Option<&str> { steps.get(id).and_then(Value::as_object).and_then(|s| s.get("kind")).and_then(Value::as_str) };
let reg = self.reg;
let is_trigger = |id: &str| kind_of(id).and_then(|k| reg.kinds.get(k)).is_some_and(|k| k.start);
let deps_of = |id: &str| -> Vec<&str> {
match steps.get(id).and_then(Value::as_object).and_then(|s| s.get("depends_on")) {
Some(Value::Array(d)) => d.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
}
};
let mut routes: HashMap<&str, Vec<&str>> = HashMap::new();
let mut missing_dep: Vec<&str> = Vec::new();
for &id in &names {
let where_ = label(id);
let here = path(id);
let with = |k: &'a str| join(&here, &[k]);
if !is_name(id) {
self.diag(
"invalid-workflow",
format!(
"{P}: {where_} is not a valid step name: 1 to 64 letters, digits, \"_\" and \"-\", starting with a letter or \"_\""
),
&here,
);
}
let Some(s) = steps.get(id).and_then(Value::as_object) else {
self.diag("invalid-workflow", format!("{P}: step {where_} is a mapping with a kind"), &here);
continue;
};
let Some(kind) = s.get("kind").and_then(Value::as_str) else {
self.diag("invalid-workflow", format!("{P}: step {where_} has no kind"), &here);
continue;
};
let spec = self.kind(kind);
match spec {
None => {
if is_custom_kind(kind) {
let alias = kind.split(':').next().unwrap_or("");
if !truthy(self.extensions.and_then(|e| e.get(alias))) {
self.diag(
"extension-unavailable",
format!(
"{P}: step {where_}: the extension alias \"{alias}\" is not declared in the front matter's extensions"
),
&with("kind"),
);
}
} else {
self.diag("invalid-workflow", format!("{P}: step {where_}: \"{kind}\" is not a workflow step kind"), &with("kind"));
}
}
Some(spec) => {
for f in &spec.required {
if !s.contains_key(f) {
self.diag("invalid-workflow", format!("{P}: step {where_} ({kind}) needs {f}"), &here);
}
}
for f in keys(s) {
if !spec.fields.iter().any(|x| x == f) && !self.reg.common_fields.iter().any(|x| x == f) && !is_extension_field(f) {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} ({kind}): \"{f}\" is not a field of {kind} or a common step field"),
&with(f),
);
}
}
if spec.start && depth > 0 {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} ({kind}) is a trigger, which only the top-level steps can hold"),
&here,
);
}
if spec.start && !deps_of(id).is_empty() {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} ({kind}) is a trigger, which depends on nothing"),
&with("depends_on"),
);
}
if kind == "finish" && depth > 0 {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} is a finish, which only the top-level steps can hold"),
&here,
);
}
if kind == "schedule" && ["cron", "every", "at"].iter().filter(|f| s.contains_key(**f)).count() != 1 {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} (schedule) sets exactly one of cron, every and at"),
&here,
);
}
if kind == "correlate" && !s.contains_key("window") {
self.diag("invalid-workflow", format!("{P}: step {where_} (correlate) needs a window"), &here);
}
}
}
if let Some(d) = s.get("depends_on") {
let distinct = |list: &[Value]| {
let mut seen = HashSet::new();
list.iter().all(|x| x.as_str().is_some_and(|x| seen.insert(x)))
};
if !d.as_array().is_some_and(|list| distinct(list)) {
self.diag(
"invalid-workflow",
format!("{P}: step {where_}: depends_on is a list of distinct step names"),
&with("depends_on"),
);
}
for dep in deps_of(id) {
if !steps.contains_key(dep) {
if !missing_dep.contains(&id) {
missing_dep.push(id);
}
self.diag(
"invalid-workflow",
format!("{P}: step {where_} depends on \"{dep}\", which is not a step in its scope"),
&with("depends_on"),
);
}
}
}
if let Some(max) = s.get("retry").and_then(Value::as_object).and_then(|r| r.get("max")) {
match integer(max) {
Some(n) if n > limits.retry_max => self.diag(
"limit-exceeded",
format!("{P}: step {where_} retries {} times; the limit is {}", js_number(n), js_number(limits.retry_max)),
&with("retry"),
),
Some(n) if n >= 0.0 => {}
_ => self.diag(
"invalid-workflow",
format!("{P}: step {where_}: retry.max is a whole number of retries, at most {}", js_number(limits.retry_max)),
&with("retry"),
),
}
}
let mut targets: Vec<&str> = Vec::new();
if let Some(on_error) = s.get("on_error") {
match on_error.as_str() {
Some(e) if is_on_error(e) => {
if let Some(t) = e.strip_prefix("goto:") {
targets.push(t);
}
}
_ => self.diag(
"invalid-workflow",
format!("{P}: step {where_}: on_error is fail, continue or goto:<step>"),
&with("on_error"),
),
}
}
if kind == "switch" {
if let Some(cases) = s.get("cases").and_then(Value::as_object) {
for case in keys(cases) {
match cases.get(case) {
Some(Value::String(t)) => targets.push(t),
_ => self.diag(
"invalid-workflow",
format!("{P}: step {where_} (switch): case \"{case}\" names one step, as a string"),
&with("cases"),
),
}
}
}
if let Some(Value::String(t)) = s.get("default") {
targets.push(t);
}
}
if let Some(Value::String(t)) = s.get("on_timeout") {
targets.push(t);
}
for &t in &targets {
if !steps.contains_key(t) {
self.diag("invalid-workflow", format!("{P}: step {where_} routes to \"{t}\", which is not a step in its scope"), &here);
} else if is_trigger(t) {
self.diag(
"invalid-workflow",
format!("{P}: step {where_} routes to \"{t}\", a trigger: a route can't start a run"),
&here,
);
}
}
routes.insert(id, targets.into_iter().filter(|t| steps.contains_key(*t)).collect());
let mut nested: Vec<(Vec<&'a str>, Vec<&'a str>, &'a Object)> = Vec::new();
let takes = |f: &str| spec.is_some() && workflow_scope(kind) == Some(f);
let inner = steps_of;
if takes("body") && s.contains_key("body") {
match inner(s.get("body")).filter(|_| is_body(s.get("body"))) {
Some(st) => nested.push((prefix.iter().copied().chain([id]).collect(), [with("body"), vec!["steps"]].concat(), st)),
None => self.diag(
"invalid-workflow",
format!("{P}: step {where_}: its body is {{steps: …}}, a mapping of steps"),
&with("body"),
),
}
}
if takes("branches") && s.contains_key("branches") {
match s.get("branches").and_then(Value::as_object) {
Some(b) if !b.is_empty() && b.values().all(|v| is_body(Some(v))) => {
for n in keys(b) {
if let Some(st) = inner(b.get(n)) {
nested.push((
prefix.iter().copied().chain([id, n]).collect(),
[with("branches"), vec![n, "steps"]].concat(),
st,
));
}
}
}
_ => self.diag(
"invalid-workflow",
format!("{P}: step {where_}: its branches are a mapping of names to {{steps: …}}"),
&with("branches"),
),
}
}
for (p, a, st) in nested {
if depth + 1 > limits.body_depth {
self.diag("limit-exceeded", format!("{P}: step {where_} nests bodies deeper than {} levels", limits.body_depth), &here);
break;
}
self.scope(st, &p, &a, depth + 1);
}
}
let mut cyclic: Vec<&str> = Vec::new();
let mut state: HashMap<&str, bool> = HashMap::new(); for &root in &names {
if state.contains_key(root) {
continue;
}
let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, deps_of(root), 0)];
state.insert(root, false);
while let Some(top) = stack.last_mut() {
let Some(&dep) = top.1.get(top.2) else {
let (id, _, _) = stack.pop().unwrap_or((root, Vec::new(), 0));
state.insert(id, true);
continue;
};
top.2 += 1;
if !steps.contains_key(dep) {
continue;
}
match state.get(dep) {
Some(false) => {
let from = stack.iter().position(|f| f.0 == dep).unwrap_or(0);
let cycle: Vec<&str> = stack[from..].iter().map(|f| f.0).collect();
for &c in &cycle {
if !cyclic.contains(&c) {
cyclic.push(c);
}
}
let shown: Vec<String> = cycle.iter().copied().chain([dep]).map(label).collect();
self.diag(
"invalid-workflow",
format!("{P}: the steps {} depend on each other in a cycle", shown.join(" → ")),
&path(dep),
);
}
Some(true) => {}
None => {
state.insert(dep, false);
stack.push((dep, deps_of(dep), 0));
}
}
}
}
if depth > 0 {
return;
}
let routed: HashSet<&str> = routes.values().flatten().copied().collect();
let triggers: Vec<&str> = names.iter().copied().filter(|id| is_trigger(id)).collect();
let unknown: Vec<&str> =
names.iter().copied().filter(|id| kind_of(id).is_some_and(|k| !reg.kinds.contains_key(k)) && deps_of(id).is_empty()).collect();
let roots: Vec<&str> = names
.iter()
.copied()
.filter(|id| {
kind_of(id).and_then(|k| reg.kinds.get(k)).is_some_and(|k| !k.start) && deps_of(id).is_empty() && !routed.contains(id)
})
.collect();
let mut all_triggers: Vec<&str> = reg.kinds.iter().filter(|(_, k)| k.start).map(|(n, _)| n.as_str()).collect();
all_triggers.sort_by(|a, b| utf16_cmp(a, b));
let all_triggers = all_triggers.join(", ");
for &id in &roots {
self.diag(
"invalid-workflow",
format!(
"{P}: step {} depends on nothing, so it starts the workflow, but {} is not a trigger: start with one of {all_triggers} and depend on it",
label(id),
kind_of(id).unwrap_or("")
),
&path(id),
);
}
if triggers.is_empty() && roots.is_empty() && unknown.is_empty() {
self.diag("invalid-workflow", format!("{P}: the workflow has no trigger: one of {all_triggers} starts it"), &["steps"]);
}
if !names.iter().any(|id| kind_of(id) == Some("finish")) {
self.diag("invalid-workflow", format!("{P}: the workflow has no finish step, which ends a run"), &["steps"]);
}
let mut next: HashMap<&str, Vec<&str>> = names.iter().map(|&id| (id, routes.get(id).cloned().unwrap_or_default())).collect();
for &id in &names {
for dep in deps_of(id) {
if let Some(n) = next.get_mut(dep) {
n.push(id);
}
}
}
let mut reached: HashSet<&str> = HashSet::new();
let mut pending: Vec<&str> = [triggers, roots, unknown, missing_dep, cyclic].concat();
while let Some(id) = pending.pop() {
if !reached.insert(id) {
continue;
}
if let Some(n) = next.get(id) {
pending.extend(n.iter().copied().filter(|x| !reached.contains(x)));
}
}
for &id in &names {
if !reached.contains(id) && kind_of(id).is_some() {
self.diag("invalid-workflow", format!("{P}: step {} can't be reached from a trigger", label(id)), &path(id));
}
}
}
}
fn locate(lines: &[(u32, &str)], path: &[&str]) -> Option<u32> {
let mut start = 0;
let mut parent: isize = -1;
let mut found = None;
for key in path {
let mut child: isize = -1;
let mut hit = None;
for (i, &(_, text)) in lines.iter().enumerate().skip(start) {
if js_trim(text).is_empty() || text.trim_start_matches(js_space).starts_with('#') {
continue;
}
let rest = text.trim_start_matches(js_space);
let indent = text[..text.len() - rest.len()].chars().count() as isize;
if indent <= parent {
break;
}
if child < 0 {
child = indent;
}
if indent != child {
continue;
}
if key_at(rest, key) {
hit = Some(i);
break;
}
}
let Some(i) = hit else { return found };
found = Some(lines[i].0);
start = i + 1;
parent = child;
}
found
}
fn key_at(s: &str, key: &str) -> bool {
["", "\"", "'"].iter().any(|q| {
let p = format!("{q}{key}{q}:");
s.strip_prefix(p.as_str()).is_some_and(|after| after.is_empty() || after.starts_with([' ', '\t']))
})
}