use core::sync::atomic::{AtomicBool, Ordering};
use std::collections::{BTreeMap, VecDeque};
use crate::error::{Error, Result, UnsandboxedRemote};
use crate::execute::admission::admit;
use crate::execute::perform::{Gates, Performed, RemoteRun, Shared, Task, Told, Worked, perform};
use crate::execute::record::{
Progress, append, forget_contradicted, recorded, restore, shown, skipped,
};
use crate::execute::schedule::{Finish, Schedule};
use crate::execute::settle::{Settled, settle};
use crate::placement::expand::{Lists, expand, expand_description};
use crate::placement::layout::Layout;
use crate::ports::{Dispatcher, Manifest, PortSet, Ports, Reporter};
use crate::types::{
ActionOutcome, Captured, Ceiling, Command, EnvName, EnvValue, ExpandedDescription, Forcing,
Isolation, Label, LiveOutput, Node, NodeId, OutcomeEvent, OutputPath, OwnComponents, Plan,
PlannedKey, PlatformProperties, ReadyAction, RemoteExecution, RemotePolicy, RemoteSettings,
RemoteSwitch, RemoteUse, Rerun, RunChoices, Summary, TargetGraph, Turn, Verdict,
};
pub fn ensure_sandboxed_remote(remote: RemotePolicy, strategy: Isolation) -> Result<()> {
if strategy != Isolation::Bare {
return Ok(());
}
let which = match (remote.execution, remote.use_) {
(RemoteExecution::On { .. }, _) => UnsandboxedRemote::Execute,
(RemoteExecution::Off, RemoteUse::ReadWrite) => UnsandboxedRemote::Upload,
(RemoteExecution::Off, _) => return Ok(()),
};
Err(Error::UploadUnsandboxed { which })
}
pub fn execute<P: Ports>(
whole: &TargetGraph,
graph: &TargetGraph,
plan: &Plan,
choices: RunChoices,
remote_off: &RemoteSwitch,
ports: &mut PortSet<P>,
) -> Result<Vec<ActionOutcome>> {
let RunChoices {
on_failure,
live,
rerun,
remote,
} = choices;
if !made_from(plan, graph) {
return Err(Error::ForeignPlan);
}
let workspace = ports.manifest.workspace()?;
ensure_sandboxed_remote(remote, workspace.execution.strategy)?;
Layout::of(whole, &workspace.out)?;
let layout = Layout::of(graph, &workspace.out)?;
let targets = prepared(graph, plan, &layout, &workspace.ceiling)?;
let PortSet {
cache,
cas,
log,
strategy,
dispatcher,
clock,
reporter,
remote: remote_cache,
..
} = ports;
let (cas, strategy, clock) = (&*cas, &*strategy, &*clock);
let no_properties = PlatformProperties::default();
let remote = RemoteRun {
port: &*remote_cache,
policy: remote,
execution: &workspace.execution,
properties: workspace
.remote
.as_ref()
.map_or(&no_properties, RemoteSettings::properties),
down: remote_off,
gates: Gates::of(remote.execution),
};
let stop = AtomicBool::new(false);
let place = AtomicBool::new(false);
let shared = Shared {
stop: &stop,
live: match live {
LiveOutput::Off => None,
LiveOutput::OneAction => Some(&place),
},
};
let mut build = Build::<P> {
graph,
targets,
layout: &layout,
schedule: Schedule::new(graph, on_failure),
rerun,
outcomes: vec![None; graph.len()],
queue: VecDeque::new(),
fatal: None,
cache,
cas,
log,
clock,
reporter,
shared,
live: None,
held: Vec::new(),
};
build.reporter.begun(graph.len());
let dispatched = dispatcher.dispatch(
|task, tell| perform(task, strategy, cas, clock, Some(&remote), shared, tell),
|turn| build.step(turn),
);
build.outcomes(dispatched)
}
pub(crate) fn made_from(plan: &Plan, graph: &TargetGraph) -> bool {
plan.len() == graph.len()
&& graph
.nodes()
.iter()
.zip((0_u32..).map(NodeId::new))
.all(|(node, id)| plan.label(id) == Some(&node.label))
&& plan.settings().keys().eq(graph.settings().keys())
}
const fn own_of(verdict: &Verdict) -> &OwnComponents {
match verdict {
Verdict::Clean { key }
| Verdict::Dirty {
key: PlannedKey::Finished(key),
..
} => &key.components().own,
Verdict::Dirty {
key: PlannedKey::Unfinished(unfinished),
..
}
| Verdict::Conditional(unfinished) => &unfinished.own,
}
}
fn ready(
node: &Node,
own: &OwnComponents,
command: Command,
description: Option<ExpandedDescription>,
outputs: &[OutputPath],
deps: Vec<OutputPath>,
) -> ReadyAction {
let env: BTreeMap<EnvName, EnvValue> = own
.env
.iter()
.filter_map(|(name, value)| Some((name.clone(), value.clone()?)))
.collect();
ReadyAction {
label: node.label.clone(),
command,
description,
env,
inputs: node.inputs.clone(),
deps,
outputs: outputs.to_vec(),
network: node.network,
output_source: node.output_source,
}
}
pub(crate) struct Prepared<'a> {
pub(crate) node: &'a Node,
own: &'a OwnComponents,
pub(crate) deps: Vec<&'a Label>,
pub(crate) action: ReadyAction,
}
pub(crate) fn prepared<'a>(
graph: &'a TargetGraph,
plan: &'a Plan,
layout: &Layout,
ceiling: &Ceiling,
) -> Result<Vec<Prepared<'a>>> {
graph
.nodes()
.iter()
.zip(plan.verdicts())
.zip((0_u32..).map(NodeId::new))
.map(|((node, verdict), id)| {
let own = own_of(verdict);
let outputs = layout.outputs(id);
let dep_paths = layout.deps(graph, id);
let lists = Lists {
inputs: &node.inputs,
outputs,
deps: &dep_paths,
};
let command = admit(
expand(&node.run, &own.settings, &lists),
node,
ceiling,
&dep_paths,
)?;
let description = node
.description
.as_ref()
.map(|description| expand_description(description, plan.settings(), &lists));
let deps = graph
.deps(id)
.unwrap_or_default()
.iter()
.filter_map(|dep| graph.node(*dep))
.map(|dep| &dep.label)
.collect();
Ok(Prepared {
node,
own,
deps,
action: ready(node, own, command, description, outputs, dep_paths),
})
})
.collect()
}
fn without_outcome<T>(graph: &TargetGraph, slots: &[Option<T>]) -> Vec<Label> {
graph
.nodes()
.iter()
.zip(slots)
.filter(|(_, slot)| slot.is_none())
.map(|(node, _)| node.label.clone())
.collect()
}
struct Build<'a, P: Ports> {
graph: &'a TargetGraph,
targets: Vec<Prepared<'a>>,
layout: &'a Layout,
schedule: Schedule,
rerun: Rerun,
outcomes: Vec<Option<ActionOutcome>>,
queue: VecDeque<NodeId>,
fatal: Option<Error>,
cache: &'a mut P::Cache,
cas: &'a P::Cas,
log: &'a mut P::Log,
clock: &'a P::Clock,
reporter: &'a mut P::Reporter,
shared: Shared<'a>,
live: Option<NodeId>,
held: Vec<OutcomeEvent>,
}
impl<P: Ports> Build<'_, P> {
fn step(&mut self, turn: Turn<Told, Worked>) -> Vec<Task> {
if self.fatal.is_some() {
return Vec::new();
}
let mut tasks = Vec::new();
let stepped = match turn {
Turn::Begin => {
let started = self.schedule.start();
self.queue.extend(started);
self.drain(&mut tasks)
}
Turn::Told(told) => {
self.told(told);
Ok(())
}
Turn::Done(Worked::NotBegun(node)) => self.abandon(node),
Turn::Done(Worked::Performed(performed)) => self
.record(*performed)
.and_then(|()| self.drain(&mut tasks)),
};
match stepped {
Ok(()) => tasks,
Err(error) => {
self.fatal = Some(error);
self.shared.stop.store(true, Ordering::SeqCst);
Vec::new()
}
}
}
fn told(&mut self, told: Told) {
match told {
Told::Began(node) => {
if let Some(target) = self.targets.get(node.index()) {
self.reporter.started(&target.action);
}
}
Told::Printed {
node,
channel,
bytes,
} => {
if let Some(target) = self.targets.get(node.index()) {
self.live = Some(node);
self.reporter.printed(&target.node.label, channel, &bytes);
}
}
Told::Remote(notice) => self.reporter.remote(¬ice),
}
}
fn drain(&mut self, tasks: &mut Vec<Task>) -> Result<()> {
while let Some(node) = self.queue.pop_front() {
if self.schedule.stopped().is_some() {
self.abandon(node)?;
continue;
}
let Some(target) = self.targets.get(node.index()) else {
continue;
};
let settled = settle(
&target.node.label,
Forcing::of(target.node.freshness, target.node.role, self.rerun),
target.own,
&target.deps,
&*self.cache,
self.cas,
)?;
match settled {
Settled::Runs(key) => {
tasks.push(Task {
node,
role: target.node.role,
key,
action: target.action.clone(),
});
}
Settled::Cached { row, manifests } => {
let outcome = restore(
target.node.label.clone(),
target.node.role,
&row,
&manifests,
self.layout.outputs(node),
self.cas,
);
let progress = Progress::Keyed {
key: row.key().digest(),
};
self.finish(node, progress, outcome)?;
}
}
}
Ok(())
}
fn record(&mut self, performed: Performed) -> Result<()> {
let node = performed.node;
let Some(target) = self.targets.get(node.index()) else {
return Ok(());
};
let was_live = performed.live;
let progress = Progress::Began {
key: performed.key.digest(),
span: performed.span,
};
let key = performed.key.clone();
let outcome = recorded(
target.node,
performed.key,
performed.ended,
self.layout.outputs(node),
self.cas,
self.cache,
)?;
let outcome = forget_contradicted(outcome, &key, self.cache);
self.finish(node, progress, outcome)?;
if was_live && let Some(place) = self.shared.live {
place.store(false, Ordering::SeqCst);
}
Ok(())
}
fn finish(&mut self, node: NodeId, progress: Progress, outcome: ActionOutcome) -> Result<()> {
let finish = if outcome.class.succeeded() {
Finish::Succeeded
} else {
Finish::Failed
};
self.conclude(node, progress, outcome)?;
let effects = self.schedule.complete(self.graph, node, finish);
for skipped_node in effects.skipped {
self.skip(skipped_node, node)?;
}
if self.schedule.stopped().is_some() {
self.shared.stop.store(true, Ordering::SeqCst);
}
self.queue.extend(effects.started);
Ok(())
}
fn abandon(&mut self, node: NodeId) -> Result<()> {
let Some(failed) = self.schedule.stopped() else {
return Ok(());
};
self.schedule.abandon(node);
self.skip(node, failed)
}
fn skip(&mut self, node: NodeId, because: NodeId) -> Result<()> {
let (Some(target), Some(cause)) = (
self.targets.get(node.index()),
self.targets.get(because.index()),
) else {
return Ok(());
};
let outcome = skipped(
target.node.label.clone(),
target.node.role,
cause.node.label.clone(),
);
self.conclude(node, Progress::Skipped, outcome)
}
fn conclude(&mut self, node: NodeId, progress: Progress, outcome: ActionOutcome) -> Result<()> {
let (Some(target), Some(slot)) = (
self.targets.get(node.index()),
self.outcomes.get_mut(node.index()),
) else {
return Ok(());
};
*slot = Some(outcome.clone());
let event = append(
self.log,
self.clock,
&target.node.provenance,
&target.action.command,
progress,
outcome,
)?;
self.show(node, event)
}
fn show(&mut self, node: NodeId, event: OutcomeEvent) -> Result<()> {
match self.live {
Some(live) if live != node => {
self.held.push(event);
Ok(())
}
Some(_) => {
self.reporter.finished(&event, Captured::default());
self.live = None;
let held = core::mem::take(&mut self.held);
held.iter().try_for_each(|event| self.report(event))
}
None => self.report(&event),
}
}
fn report(&mut self, event: &OutcomeEvent) -> Result<()> {
let label = &event.outcome.label;
let stdout = shown(self.cas, label, event.outcome.stdout)?;
let stderr = shown(self.cas, label, event.outcome.stderr)?;
self.reporter.finished(
event,
Captured {
stdout: &stdout,
stderr: &stderr,
},
);
Ok(())
}
fn outcomes(self, dispatched: Result<()>) -> Result<Vec<ActionOutcome>> {
if let Some(error) = self.fatal {
return Err(error);
}
dispatched?;
let targets = without_outcome(self.graph, &self.outcomes);
if !targets.is_empty() {
return Err(Error::DispatcherFault { targets });
}
let outcomes: Vec<ActionOutcome> = self.outcomes.into_iter().flatten().collect();
self.reporter.summary(Summary::of(&outcomes));
Ok(outcomes)
}
}
#[cfg(test)]
mod tests {
#![expect(
clippy::unwrap_used,
reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
)]
use std::collections::{BTreeMap, BTreeSet};
use super::{made_from, own_of, ready, without_outcome};
use crate::execute::fixtures::{
command, graph, key, label, node, output_path, own, path, settings,
};
use crate::types::{
Attribution, DirtyReason, EnvName, EnvValue, ExpandedDescription, NetworkAccess, NodeId,
Plan, PlannedKey, TargetGraph, Unfinished, Verdict, WantedSet,
};
fn plan_with(labels: &[&str], values: &[(&str, &str)]) -> Plan {
let verdicts = labels
.iter()
.map(|_| Verdict::Clean { key: key(&["o"]) })
.collect();
let wanted = WantedSet {
programs: BTreeSet::new(),
env: BTreeSet::new(),
write: BTreeSet::new(),
network: BTreeSet::new(),
};
Plan::new(
labels.iter().map(|raw| label(raw)).collect(),
verdicts,
wanted,
Attribution::default(),
settings(values),
)
}
fn plan(labels: &[&str]) -> Plan {
plan_with(labels, &[])
}
#[test]
fn a_plan_is_made_from_a_graph_when_it_holds_its_targets_under_the_same_ids() {
let graph = graph(
vec![node("//:a", |_| {}), node("//:b", |_| {})],
&[&[], &[]],
);
assert!(made_from(&plan(&["//:a", "//:b"]), &graph));
assert!(!made_from(&plan(&["//:a"]), &graph), "a target short");
assert!(
!made_from(&plan(&["//:a", "//:b", "//:c"]), &graph),
"a target more"
);
assert!(
!made_from(&plan(&["//:a", "//:c"]), &graph),
"another target"
);
assert!(
!made_from(&plan(&["//:b", "//:a"]), &graph),
"the same targets under other ids"
);
}
#[test]
fn the_targets_without_an_outcome_are_named_in_label_order() {
let graph = graph(
vec![
node("//:a", |_| {}),
node("//:b", |_| {}),
node("//:c", |_| {}),
],
&[&[], &[], &[]],
);
assert_eq!(
without_outcome(&graph, &[Some(()), None, None]),
[label("//:b"), label("//:c")]
);
assert_eq!(
without_outcome(&graph, &[None, Some(()), Some(())]),
[label("//:a")]
);
assert_eq!(without_outcome(&graph, &[Some(()); 3]), []);
assert_eq!(without_outcome::<()>(&graph, &[]), [], "no slot, no target");
}
#[test]
fn a_plan_is_made_from_a_graph_when_it_holds_a_value_for_exactly_its_settings() {
let graph = TargetGraph::new(
Vec::new(),
Vec::new(),
BTreeMap::new(),
settings(&[("level", "1"), ("mode", "debug")]),
);
assert!(
made_from(
&plan_with(&[], &[("level", "1"), ("mode", "debug")]),
&graph
),
"the defaults"
);
assert!(
made_from(&plan_with(&[], &[("level", "1"), ("mode", "fast")]), &graph),
"an overridden value"
);
assert!(
!made_from(&plan_with(&[], &[("mode", "debug")]), &graph),
"a setting short"
);
assert!(
!made_from(
&plan_with(&[], &[("arch", "arm"), ("level", "1"), ("mode", "debug")]),
&graph
),
"a setting more"
);
assert!(
!made_from(&plan_with(&[], &[("level", "1"), ("tool", "cc")]), &graph),
"another setting"
);
}
#[test]
fn every_verdict_yields_the_components_of_its_target() {
let finished = key(&["app"]);
let unfinished = Unfinished {
own: own(&["lib"]),
awaiting: vec![NodeId::new(0)],
};
let clean = Verdict::Clean {
key: finished.clone(),
};
let dirty = Verdict::Dirty {
reason: DirtyReason::NeverBuilt,
key: PlannedKey::Finished(finished),
};
let waiting = Verdict::Dirty {
reason: DirtyReason::NeverBuilt,
key: PlannedKey::Unfinished(unfinished.clone()),
};
let conditional = Verdict::Conditional(unfinished);
assert_eq!(own_of(&clean), &own(&["app"]));
assert_eq!(own_of(&dirty), &own(&["app"]));
assert_eq!(own_of(&waiting), &own(&["lib"]));
assert_eq!(own_of(&conditional), &own(&["lib"]));
}
#[test]
fn an_action_is_handed_its_paths_in_written_order_and_only_the_variables_that_are_set() {
let node = node("//:app", |node| {
node.inputs = vec![path("z.c"), path("a.c")];
node.network = NetworkAccess::Declared;
});
let cc = EnvName::parse("CC").unwrap();
let unset = EnvName::parse("CFLAGS").unwrap();
let mut own = own(&["app"]);
own.env = BTreeMap::from([
(cc.clone(), Some(EnvValue::parse("clang").unwrap())),
(unset, None),
]);
let outputs = [output_path("//:app", "app")];
let deps = vec![output_path("//:z", "z"), output_path("//:a", "a")];
let action = ready(
&node,
&own,
command(&["cc", "-o", "out/app"]),
Some(ExpandedDescription::new("compile z.c a.c")),
&outputs,
deps.clone(),
);
assert_eq!(action.label, label("//:app"));
assert_eq!(action.command, command(&["cc", "-o", "out/app"]));
assert_eq!(
action.description,
Some(ExpandedDescription::new("compile z.c a.c"))
);
assert_eq!(
action.env,
BTreeMap::from([(cc, EnvValue::parse("clang").unwrap())])
);
assert_eq!(action.inputs, [path("z.c"), path("a.c")]);
assert_eq!(action.deps, deps);
assert_eq!(action.outputs, outputs);
assert_eq!(action.network, NetworkAccess::Declared);
}
}