use std::sync::Arc;
use crate::app::shared::AppShared;
use crate::error::{Closed, LoadError};
use crate::graph::ModuleId;
use crate::graph::wire::{self, LazyFailure, LazyWiring, WireEnv};
use crate::lifecycle::connect;
use crate::module::Module;
use crate::module::handle::ModuleRef;
pub(crate) async fn load(shared: &Arc<AppShared>, module: Box<dyn Module>) -> Result<ModuleRef, LoadError> {
if !shared.phase.allows_load() {
return Err(LoadError::Closed(Closed::new()));
}
let _serial = shared.load_lock.lock().await;
if !shared.phase.allows_load() {
return Err(LoadError::Closed(Closed::new()));
}
let base = shared.graph();
if let Some(&existing) = base.by_identity.get(&module.identity()) {
return Ok(shared.module_ref(existing));
}
let env = WireEnv {
timer: shared.config.timer.clone(),
runtime: shared.config.runtime.clone(),
knobs_set: shared.config.knobs_set(),
};
let LazyWiring { graph, module: loaded, singletons } = match wire::wire_lazy(&base, module, &env) {
Ok(wiring) => wiring,
Err(LazyFailure::Wiring(errors)) => return Err(LoadError::Wiring(errors)),
Err(LazyFailure::Refused(refusal)) => return Err(LoadError::Refused(refusal)),
};
let modules: Vec<ModuleId> = (base.modules.len()..graph.modules.len()).map(|i| ModuleId(i as u32)).collect();
shared.publish(Arc::new(graph));
if let Err(failure) = connect::connect(shared, &singletons, &modules).await {
shared.publish(base);
for id in &singletons {
shared.singletons.remove(*id);
}
return Err(LoadError::Connect(failure));
}
Ok(shared.module_ref(loaded))
}