use std::{
collections::{HashMap, HashSet},
path::PathBuf,
time::{Duration, Instant},
};
use super::wasm_cache::{
SharedIncrementalTargetMaintenanceConfig, SharedIncrementalTargetMaintenanceOutcome,
SharedIncrementalTargetPrunePolicy, WasmBuildBatchInputMetrics, WasmBuildBatchInputResolver,
WasmBuildCacheMode, WasmBuildError, WasmBuildOutcome, WasmBuildProgressConfig,
WasmBuildProgressEvent, WasmBuildSpec, WasmBuildTimings, build_wasm_canisters_cached_in_batch,
build_wasm_canisters_cached_in_batch_with_progress,
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildBatchConfig {
shared_incremental_maintenance: Option<SharedIncrementalTargetMaintenanceConfig>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LabeledWasmBuildSpec {
label: String,
spec: WasmBuildSpec,
}
#[derive(Debug)]
pub struct WasmBuildBatchReport {
entries: Vec<WasmBuildBatchEntry>,
input_resolution: WasmBuildBatchInputMetrics,
total: Duration,
}
#[derive(Debug)]
pub struct WasmBuildBatchEntry {
index: usize,
label: String,
result: Result<WasmBuildOutcome, WasmBuildError>,
entry_elapsed: Duration,
}
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchOutcomeEntry<'a> {
index: usize,
label: &'a str,
outcome: &'a WasmBuildOutcome,
entry_elapsed: Duration,
}
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchFailure<'a> {
index: usize,
label: &'a str,
error: &'a WasmBuildError,
entry_elapsed: Duration,
}
#[derive(Clone, Copy, Debug)]
pub struct WasmBuildBatchMaintenanceEntry<'a> {
index: usize,
label: &'a str,
outcome: &'a SharedIncrementalTargetMaintenanceOutcome,
}
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WasmBuildBatchContractError {
EmptyLabel {
index: usize,
},
DuplicateLabel {
label: String,
first_index: usize,
duplicate_index: usize,
},
}
impl LabeledWasmBuildSpec {
#[must_use]
pub fn new(label: impl Into<String>, spec: WasmBuildSpec) -> Self {
Self {
label: label.into(),
spec,
}
}
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
#[must_use]
pub const fn spec(&self) -> &WasmBuildSpec {
&self.spec
}
#[must_use]
pub fn into_parts(self) -> (String, WasmBuildSpec) {
(self.label, self.spec)
}
}
impl WasmBuildBatchEntry {
#[must_use]
pub const fn index(&self) -> usize {
self.index
}
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
pub const fn result(&self) -> Result<&WasmBuildOutcome, &WasmBuildError> {
self.result.as_ref()
}
#[must_use]
pub fn outcome(&self) -> Option<&WasmBuildOutcome> {
self.result.as_ref().ok()
}
#[must_use]
pub fn error(&self) -> Option<&WasmBuildError> {
self.result.as_ref().err()
}
#[must_use]
pub const fn entry_elapsed(&self) -> Duration {
self.entry_elapsed
}
#[must_use]
pub const fn is_success(&self) -> bool {
self.result.is_ok()
}
pub fn into_parts(
self,
) -> (
usize,
String,
Result<WasmBuildOutcome, WasmBuildError>,
Duration,
) {
(self.index, self.label, self.result, self.entry_elapsed)
}
}
impl<'a> WasmBuildBatchOutcomeEntry<'a> {
#[must_use]
pub const fn index(self) -> usize {
self.index
}
#[must_use]
pub const fn label(self) -> &'a str {
self.label
}
#[must_use]
pub const fn outcome(self) -> &'a WasmBuildOutcome {
self.outcome
}
#[must_use]
pub const fn entry_elapsed(self) -> Duration {
self.entry_elapsed
}
}
impl<'a> WasmBuildBatchFailure<'a> {
#[must_use]
pub const fn index(self) -> usize {
self.index
}
#[must_use]
pub const fn label(self) -> &'a str {
self.label
}
#[must_use]
pub const fn error(self) -> &'a WasmBuildError {
self.error
}
#[must_use]
pub const fn entry_elapsed(self) -> Duration {
self.entry_elapsed
}
}
impl<'a> WasmBuildBatchMaintenanceEntry<'a> {
#[must_use]
pub const fn index(self) -> usize {
self.index
}
#[must_use]
pub const fn label(self) -> &'a str {
self.label
}
#[must_use]
pub const fn outcome(self) -> &'a SharedIncrementalTargetMaintenanceOutcome {
self.outcome
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildBatchMetrics {
specifications: usize,
succeeded: usize,
failed: usize,
built: usize,
reused: usize,
input_resolution_runs: usize,
input_resolution_reuses: usize,
successful_timings: WasmBuildTimings,
total: Duration,
}
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WasmBuildBatchProgressEvent {
BuildStarted {
index: usize,
label: String,
total: usize,
},
BuildProgress {
index: usize,
label: String,
event: WasmBuildProgressEvent,
},
BuildFinished {
index: usize,
label: String,
},
BuildFailed {
index: usize,
label: String,
},
}
impl WasmBuildBatchReport {
#[must_use]
pub fn entries(&self) -> &[WasmBuildBatchEntry] {
&self.entries
}
#[must_use]
pub fn into_entries(self) -> Vec<WasmBuildBatchEntry> {
self.entries
}
pub fn outcomes(&self) -> impl Iterator<Item = WasmBuildBatchOutcomeEntry<'_>> {
self.entries.iter().filter_map(|entry| {
entry.outcome().map(|outcome| WasmBuildBatchOutcomeEntry {
index: entry.index,
label: &entry.label,
outcome,
entry_elapsed: entry.entry_elapsed,
})
})
}
pub fn failures(&self) -> impl Iterator<Item = WasmBuildBatchFailure<'_>> {
self.entries.iter().filter_map(|entry| {
entry.error().map(|error| WasmBuildBatchFailure {
index: entry.index,
label: &entry.label,
error,
entry_elapsed: entry.entry_elapsed,
})
})
}
pub fn shared_incremental_maintenance_outcomes(
&self,
) -> impl Iterator<Item = WasmBuildBatchMaintenanceEntry<'_>> {
self.outcomes().filter_map(|entry| {
entry
.outcome
.record()
.shared_incremental_maintenance()
.map(|outcome| WasmBuildBatchMaintenanceEntry {
index: entry.index,
label: entry.label,
outcome,
})
})
}
#[must_use]
pub const fn total(&self) -> Duration {
self.total
}
#[must_use]
pub fn is_success(&self) -> bool {
self.entries.iter().all(WasmBuildBatchEntry::is_success)
}
#[must_use]
pub fn metrics(&self) -> WasmBuildBatchMetrics {
let mut metrics = WasmBuildBatchMetrics {
specifications: self.entries.len(),
input_resolution_runs: self.input_resolution.runs,
input_resolution_reuses: self.input_resolution.reuses,
total: self.total,
..WasmBuildBatchMetrics::default()
};
for entry in &self.entries {
match &entry.result {
Ok(outcome) => {
metrics.succeeded += 1;
if outcome.is_reused() {
metrics.reused += 1;
} else {
metrics.built += 1;
}
metrics.successful_timings = metrics
.successful_timings
.saturating_add(outcome.record().timings());
}
Err(_) => metrics.failed += 1,
}
}
metrics
}
}
impl WasmBuildBatchMetrics {
#[must_use]
pub const fn specifications(self) -> usize {
self.specifications
}
#[must_use]
pub const fn succeeded(self) -> usize {
self.succeeded
}
#[must_use]
pub const fn failed(self) -> usize {
self.failed
}
#[must_use]
pub const fn built(self) -> usize {
self.built
}
#[must_use]
pub const fn reused(self) -> usize {
self.reused
}
#[must_use]
pub const fn input_resolution_runs(self) -> usize {
self.input_resolution_runs
}
#[must_use]
pub const fn input_resolution_reuses(self) -> usize {
self.input_resolution_reuses
}
#[must_use]
pub const fn successful_timings(self) -> WasmBuildTimings {
self.successful_timings
}
#[must_use]
pub const fn total(self) -> Duration {
self.total
}
}
impl WasmBuildBatchConfig {
#[must_use]
pub const fn new() -> Self {
Self {
shared_incremental_maintenance: None,
}
}
#[must_use]
pub const fn with_shared_incremental_target_maintenance(
mut self,
config: SharedIncrementalTargetMaintenanceConfig,
) -> Self {
self.shared_incremental_maintenance = Some(config);
self
}
#[must_use]
pub const fn with_shared_incremental_target_maintenance_at_most_every(
self,
policy: SharedIncrementalTargetPrunePolicy,
minimum_interval: Duration,
) -> Self {
self.with_shared_incremental_target_maintenance(
SharedIncrementalTargetMaintenanceConfig::new(policy, minimum_interval),
)
}
#[must_use]
pub const fn shared_incremental_target_maintenance(
self,
) -> Option<SharedIncrementalTargetMaintenanceConfig> {
self.shared_incremental_maintenance
}
}
impl std::fmt::Display for WasmBuildBatchReport {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let metrics = self.metrics();
write!(
formatter,
"builds={} succeeded={} failed={} built={} reused={} input_resolution_runs={} input_resolution_reuses={} successful_timings=({}) total={:?}",
metrics.specifications(),
metrics.succeeded(),
metrics.failed(),
metrics.built(),
metrics.reused(),
metrics.input_resolution_runs(),
metrics.input_resolution_reuses(),
metrics.successful_timings(),
metrics.total(),
)
}
}
pub fn build_wasm_canisters_cached_batch(
specs: &[LabeledWasmBuildSpec],
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
build_wasm_canisters_cached_batch_with_config(specs, WasmBuildBatchConfig::new())
}
pub fn build_wasm_canisters_cached_batch_with_config(
specs: &[LabeledWasmBuildSpec],
config: WasmBuildBatchConfig,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
validate_batch_labels(specs)?;
let build_specs = specs
.iter()
.map(|labeled| labeled.spec.clone())
.collect::<Vec<_>>();
let mut resolver = WasmBuildBatchInputResolver::new(&build_specs);
let mut report = build_wasm_batch(specs, config, |spec, index| {
build_wasm_canisters_cached_in_batch(spec, index, &mut resolver)
});
report.input_resolution = resolver.metrics();
Ok(report)
}
pub fn build_wasm_canisters_cached_batch_with_progress<F>(
specs: &[LabeledWasmBuildSpec],
config: WasmBuildProgressConfig,
observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
build_wasm_canisters_cached_batch_with_config_and_progress(
specs,
WasmBuildBatchConfig::new(),
config,
observer,
)
}
pub fn build_wasm_canisters_cached_batch_with_config_and_progress<F>(
specs: &[LabeledWasmBuildSpec],
batch_config: WasmBuildBatchConfig,
progress_config: WasmBuildProgressConfig,
mut observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
validate_batch_labels(specs)?;
let count = specs.len();
let build_specs = specs
.iter()
.map(|labeled| labeled.spec.clone())
.collect::<Vec<_>>();
let mut resolver = WasmBuildBatchInputResolver::new(&build_specs);
let mut report = build_wasm_batch(specs, batch_config, |spec, index| {
let label = specs[index].label.clone();
observer(WasmBuildBatchProgressEvent::BuildStarted {
index,
label: label.clone(),
total: count,
});
let result = build_wasm_canisters_cached_in_batch_with_progress(
spec,
index,
&mut resolver,
progress_config,
|event| {
observer(WasmBuildBatchProgressEvent::BuildProgress {
index,
label: label.clone(),
event,
});
},
);
observer(match result {
Ok(_) => WasmBuildBatchProgressEvent::BuildFinished { index, label },
Err(_) => WasmBuildBatchProgressEvent::BuildFailed { index, label },
});
result
});
report.input_resolution = resolver.metrics();
Ok(report)
}
fn build_wasm_batch<F>(
specs: &[LabeledWasmBuildSpec],
config: WasmBuildBatchConfig,
mut build: F,
) -> WasmBuildBatchReport
where
F: FnMut(&WasmBuildSpec, usize) -> Result<WasmBuildOutcome, WasmBuildError>,
{
let started = Instant::now();
let mut entries = Vec::with_capacity(specs.len());
let mut maintenance = BatchMaintenanceTracker::new(config.shared_incremental_maintenance);
for (index, labeled) in specs.iter().enumerate() {
let entry_started = Instant::now();
let spec = &labeled.spec;
if config.shared_incremental_maintenance.is_some()
&& spec.shared_incremental_target_maintenance().is_some()
{
entries.push(WasmBuildBatchEntry {
index,
label: labeled.label.clone(),
result: Err(batch_maintenance_ownership_error()),
entry_elapsed: entry_started.elapsed(),
});
continue;
}
let configured = maintenance.prepare_spec(spec);
let result = build(configured.as_ref().unwrap_or(spec), index);
entries.push(WasmBuildBatchEntry {
index,
label: labeled.label.clone(),
result,
entry_elapsed: entry_started.elapsed(),
});
}
WasmBuildBatchReport {
entries,
input_resolution: WasmBuildBatchInputMetrics::default(),
total: started.elapsed(),
}
}
fn validate_batch_labels(
specs: &[LabeledWasmBuildSpec],
) -> Result<(), WasmBuildBatchContractError> {
let mut labels = HashMap::with_capacity(specs.len());
for (index, labeled) in specs.iter().enumerate() {
if labeled.label.is_empty() {
return Err(WasmBuildBatchContractError::EmptyLabel { index });
}
if let Some(first_index) = labels.get(labeled.label.as_str()) {
return Err(WasmBuildBatchContractError::DuplicateLabel {
label: labeled.label.clone(),
first_index: *first_index,
duplicate_index: index,
});
}
labels.insert(labeled.label.as_str(), index);
}
Ok(())
}
struct BatchMaintenanceTracker {
config: Option<SharedIncrementalTargetMaintenanceConfig>,
configured_targets: HashSet<PathBuf>,
}
impl BatchMaintenanceTracker {
fn new(config: Option<SharedIncrementalTargetMaintenanceConfig>) -> Self {
Self {
config,
configured_targets: HashSet::new(),
}
}
fn prepare_spec(&mut self, spec: &WasmBuildSpec) -> Option<WasmBuildSpec> {
let config = self.config?;
debug_assert!(spec.shared_incremental_target_maintenance().is_none());
let WasmBuildCacheMode::SharedIncremental { target_dir } = spec.cache_mode() else {
return None;
};
if !self.configured_targets.insert(target_dir.clone()) {
return None;
}
Some(
spec.clone()
.with_shared_incremental_target_maintenance(config),
)
}
}
fn batch_maintenance_ownership_error() -> WasmBuildError {
WasmBuildError::InvalidSpec {
message:
"batch-owned shared-target maintenance cannot be combined with per-spec maintenance"
.to_owned(),
}
}
impl std::fmt::Display for WasmBuildBatchContractError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyLabel { index } => {
write!(formatter, "Wasm batch label at index {index} is empty")
}
Self::DuplicateLabel {
label,
first_index,
duplicate_index,
} => write!(
formatter,
"Wasm batch label {label:?} at index {duplicate_index} duplicates index {first_index}",
),
}
}
}
impl std::error::Error for WasmBuildBatchContractError {}
#[cfg(test)]
mod tests;