Dynamic and lazy modules
Modules built at runtime from a value, module handles, and modules loaded after the application has started.
A module can have a shape that depends on a value known only at runtime, so there is no struct to write. A module can also be built only when something asks for it.
This page follows examples/08-dynamic-and-lazy.
A module built at runtime
DynamicModule::new::<Owner, _>(config, closure) builds a module from a value. Its identity is the owner type plus the configuration value. The closure receives a ModuleDef and registers bindings and exports with the value API. It runs once, after identities are deduplicated.
/// The owner type of every module `feature_module` builds; with the configuration it forms the
/// module's identity.
pub struct FeatureOwner;
/// A module built at runtime from a value, with no struct of its own.
pub fn feature_module(name: String) -> DynamicModule {
DynamicModule::new::<FeatureOwner, _>(name.clone(), move |m| {
m.value(Feature(name));
m.export::<Feature>();
})
.label("FeatureModule")
}
#[derive(Clone, PartialEq, Eq, Hash)]
#[module(imports = [LogModule, feature_module(self.feature.clone())], controllers = [FeatureController])]
pub struct AppModule {
pub feature: String,
}.label("FeatureModule") sets the name reports and lookups print. What the closure captures besides the configuration value is opaque to the graph. If it matters to a module's behaviour, name it with DynamicModule::with_settings(..) so two imports of one identity are compared on it.
Find a dynamic module's handle by passing the same configuration:
let feature = server.handle.module_of(&feature_module("beta".to_owned())).unwrap();
assert_eq!(feature.name().to_string(), "FeatureModule");Module handles
A ModuleRef is a handle to one module. get and execute on it are limited to what that module sees, so it reaches a private binding the root cannot.
| Lookup | Finds |
|---|---|
app.module::<M>() | The module of type M. AmbiguousModule if several configurations of M are registered, keyed or not. |
app.module_keyed::<M, Q>() | The instance of M keyed by Q. |
app.module_of(&config) | The module whose identity is config's. Reads the graph and loads nothing: an unknown configuration is LookupError::NotFound with LookupKind::Module. |
All three exist on App<Connected> and on AppHandle. A provider can also take its own module as an injection point: a field of type ModuleRef is the enclosing module.
During connect, ModuleRef::get for a singleton the connect walk has not built yet answers LookupError::NotReady. After connect returns it cannot occur.
Lazy modules
AppHandle::load(module) wires and connects a module after startup. It returns a ModuleRef limited to what that module sees. The application does not import the module. Nothing of it is built before the call.
/// Not imported by the application: `AppHandle::load` brings it in after startup.
#[module(providers = [Reports], exports = [Reports])]
pub struct ReportsModule;let log: Dep<BuildLog> = server.handle.get().await.unwrap();
assert!(log.entries().is_empty());
assert!(matches!(server.handle.get::<Reports>().await, Err(LookupError::NotFound { .. })));
let reports = server.handle.load(ReportsModule).await.unwrap();
assert_eq!(log.entries(), ["Reports"]);
assert_eq!(reports.name().to_string(), "ReportsModule");
assert_eq!(reports.get::<Reports>().await.unwrap().title(), "quarterly");
let again = server.handle.load(ReportsModule).await.unwrap();
assert_eq!(log.entries(), ["Reports"], "an equal identity loads once");Take the handle before serve consumes the app: let handle = app.handle();. An AppHandle is Clone + Send + Sync.
A loaded module is wired against the graph the application already froze, with every error reported at once. Its own readiness checks and init hooks run during the load. Loading the same identity twice returns the existing handle. If the second load carries different settings, it fails with LoadError::Wiring holding DifferingSettings.
At shutdown, lazily loaded modules are torn down before the base graph, latest load first.
What load refuses
The graph has already been handed to the transports, so some changes cannot be made late. Each refusal is a LoadError::Refused(LoadRefusal) and the module is not loaded.
| Refused | LoadRefusal | Why |
|---|---|---|
| Controllers | Controllers | The routes are already bound. |
| Module metadata such as middleware | Middleware | Transports read it when they bind. |
| A contribution to a collection the module does not introduce and that is already read | Contribution | A binding that read Many<T> has already seen its collection. |
| A global export | GlobalExport | Global exports are fixed at wiring. |
| An execution input | Input | Inputs belong to transports, and the per-handler input check ran at wiring. |
#[module(controllers = [FeatureController])]
struct RoutesModule;
let Err(LoadError::Refused(LoadRefusal::Controllers { module })) = server.handle.load(RoutesModule).await else {
panic!("the load should be refused");
};
assert_eq!(module.to_string(), "RoutesModule");Printed: cannot load RoutesModule: it declares controllers, and routes are already bound.
Other load failures: LoadError::Wiring for the module's wiring errors, LoadError::Connect when a construction, readiness check or init hook fails, and LoadError::Closed once shutdown has begun. A failed load restores the previous graph and removes the singletons it built, so a retry wires again. Loads are serialised.
Running the example
cargo run -p ex-08-dynamic-and-lazyGET /feature answers the value of FEATURE, default alpha.