use std::{
collections::{HashMap, HashSet},
marker::PhantomData,
path::PathBuf,
time::{Duration, Instant},
};
use super::wasm_cache::{
SharedIncrementalTargetMaintenanceConfig, SharedIncrementalTargetMaintenanceOutcome,
SharedIncrementalTargetPrunePolicy, WasmBuildBatchAttempt, WasmBuildBatchInputMetrics,
WasmBuildBatchInputResolver, WasmBuildCacheMode, WasmBuildError, WasmBuildFailurePhase,
WasmBuildFailureTimings, WasmBuildOutcome, WasmBuildProgressConfig, WasmBuildProgressEvent,
WasmBuildSessionState, 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,
}
pub struct WasmBuildSession<'guard> {
state: WasmBuildSessionState,
_source_guard: PhantomData<&'guard ()>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WasmBuildSessionMetrics {
snapshots: usize,
snapshot_reuses: usize,
invalidated: bool,
}
#[derive(Debug)]
pub struct WasmBuildBatchEntry {
index: usize,
label: String,
result: Result<WasmBuildOutcome, WasmBuildError>,
failure: Option<WasmBuildFailureDetails>,
entry_elapsed: Duration,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WasmBuildFailureDetails {
phase: WasmBuildFailurePhase,
timings: WasmBuildFailureTimings,
}
#[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,
details: WasmBuildFailureDetails,
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,
},
SourceLeaseInvalidated,
}
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<'guard> WasmBuildSession<'guard> {
#[must_use]
pub fn assume_sources_immutable<Guard: ?Sized>(_source_write_guard: &'guard Guard) -> Self {
Self {
state: WasmBuildSessionState::new(),
_source_guard: PhantomData,
}
}
pub fn build_batch(
&mut self,
specs: &[LabeledWasmBuildSpec],
config: WasmBuildBatchConfig,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
build_wasm_canisters_cached_batch_with_session(specs, config, &mut self.state)
}
pub fn build_batch_with_progress<F>(
&mut self,
specs: &[LabeledWasmBuildSpec],
batch_config: WasmBuildBatchConfig,
progress_config: WasmBuildProgressConfig,
observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
build_wasm_canisters_cached_batch_with_session_and_progress(
specs,
batch_config,
progress_config,
&mut self.state,
observer,
)
}
#[must_use]
pub const fn metrics(&self) -> WasmBuildSessionMetrics {
WasmBuildSessionMetrics {
snapshots: self.state.snapshot_count(),
snapshot_reuses: self.state.snapshot_reuses(),
invalidated: self.state.is_invalidated(),
}
}
}
impl WasmBuildSessionMetrics {
#[must_use]
pub const fn snapshots(self) -> usize {
self.snapshots
}
#[must_use]
pub const fn snapshot_reuses(self) -> usize {
self.snapshot_reuses
}
#[must_use]
pub const fn is_invalidated(self) -> bool {
self.invalidated
}
}
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 failure_details(&self) -> Option<WasmBuildFailureDetails> {
self.failure
}
#[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>,
Option<WasmBuildFailureDetails>,
Duration,
) {
(
self.index,
self.label,
self.result,
self.failure,
self.entry_elapsed,
)
}
}
impl WasmBuildFailureDetails {
#[must_use]
pub const fn phase(self) -> WasmBuildFailurePhase {
self.phase
}
#[must_use]
pub const fn timings(self) -> WasmBuildFailureTimings {
self.timings
}
}
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 phase(self) -> WasmBuildFailurePhase {
self.details.phase
}
#[must_use]
pub const fn timings(self) -> WasmBuildFailureTimings {
self.details.timings
}
#[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,
input_resolution_session_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,
details: entry
.failure
.expect("failed Wasm batch entry must retain failure details"),
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,
input_resolution_session_reuses: self.input_resolution.session_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 input_resolution_session_reuses(self) -> usize {
self.input_resolution_session_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={} input_resolution_session_reuses={} successful_timings=({}) total={:?}",
metrics.specifications(),
metrics.succeeded(),
metrics.failed(),
metrics.built(),
metrics.reused(),
metrics.input_resolution_runs(),
metrics.input_resolution_reuses(),
metrics.input_resolution_session_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> {
build_wasm_canisters_cached_batch_internal(specs, config, None)
}
fn build_wasm_canisters_cached_batch_with_session(
specs: &[LabeledWasmBuildSpec],
config: WasmBuildBatchConfig,
session: &mut WasmBuildSessionState,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
build_wasm_canisters_cached_batch_internal(specs, config, Some(session))
}
fn build_wasm_canisters_cached_batch_internal(
specs: &[LabeledWasmBuildSpec],
config: WasmBuildBatchConfig,
session: Option<&mut WasmBuildSessionState>,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError> {
validate_batch_labels(specs)?;
if session
.as_deref()
.is_some_and(WasmBuildSessionState::is_invalidated)
{
return Err(WasmBuildBatchContractError::SourceLeaseInvalidated);
}
let build_specs = specs
.iter()
.map(|labeled| labeled.spec.clone())
.collect::<Vec<_>>();
let mut resolver = session.map_or_else(
|| WasmBuildBatchInputResolver::new(&build_specs),
|session| WasmBuildBatchInputResolver::with_session(&build_specs, session),
);
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,
observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
build_wasm_canisters_cached_batch_with_progress_internal(
specs,
batch_config,
progress_config,
None,
observer,
)
}
fn build_wasm_canisters_cached_batch_with_session_and_progress<F>(
specs: &[LabeledWasmBuildSpec],
batch_config: WasmBuildBatchConfig,
progress_config: WasmBuildProgressConfig,
session: &mut WasmBuildSessionState,
observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
build_wasm_canisters_cached_batch_with_progress_internal(
specs,
batch_config,
progress_config,
Some(session),
observer,
)
}
fn build_wasm_canisters_cached_batch_with_progress_internal<F>(
specs: &[LabeledWasmBuildSpec],
batch_config: WasmBuildBatchConfig,
progress_config: WasmBuildProgressConfig,
session: Option<&mut WasmBuildSessionState>,
mut observer: F,
) -> Result<WasmBuildBatchReport, WasmBuildBatchContractError>
where
F: FnMut(WasmBuildBatchProgressEvent),
{
validate_batch_labels(specs)?;
if session
.as_deref()
.is_some_and(WasmBuildSessionState::is_invalidated)
{
return Err(WasmBuildBatchContractError::SourceLeaseInvalidated);
}
let count = specs.len();
let build_specs = specs
.iter()
.map(|labeled| labeled.spec.clone())
.collect::<Vec<_>>();
let mut resolver = session.map_or_else(
|| WasmBuildBatchInputResolver::new(&build_specs),
|session| WasmBuildBatchInputResolver::with_session(&build_specs, session),
);
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 attempt = 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 &attempt.result {
Ok(_) => WasmBuildBatchProgressEvent::BuildFinished { index, label },
Err(_) => WasmBuildBatchProgressEvent::BuildFailed { index, label },
});
attempt
});
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) -> WasmBuildBatchAttempt,
{
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()
{
let elapsed = entry_started.elapsed();
let attempt =
WasmBuildBatchAttempt::invalid_spec(batch_maintenance_ownership_error(), elapsed);
entries.push(WasmBuildBatchEntry {
index,
label: labeled.label.clone(),
result: attempt.result,
failure: Some(WasmBuildFailureDetails {
phase: attempt
.failure_phase
.expect("invalid batch entry must retain its failure phase"),
timings: attempt
.failure_timings
.expect("invalid batch entry must retain its failure timings"),
}),
entry_elapsed: elapsed,
});
continue;
}
let configured = maintenance.prepare_spec(spec);
let attempt = build(configured.as_ref().unwrap_or(spec), index);
let failure = attempt
.failure_phase
.zip(attempt.failure_timings)
.map(|(phase, timings)| WasmBuildFailureDetails { phase, timings });
entries.push(WasmBuildBatchEntry {
index,
label: labeled.label.clone(),
result: attempt.result,
failure,
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}",
),
Self::SourceLeaseInvalidated => formatter.write_str(
"Wasm build session source lease was invalidated by a detected input mutation",
),
}
}
}
impl std::error::Error for WasmBuildBatchContractError {}
#[cfg(test)]
mod tests;