Configure an actor from a file
Load mailbox capacity and supervision from a config file instead of hard-coding them.
An ActorConfig sets an actor's mailbox capacity and supervision strategy. With the serde feature it is deserializable, so the values can come from a config file. The example on this page loads it with the config crate, but any format and loader supported by serde works:
cargo add tellus --features serde
cargo add config --no-default-features --features tomlWrite the configuration
mailbox_capacity = { bounded = 100 }
[supervision_strategy.restart]
max_restarts = 3
reset_after = "30s"
backoff = { min = "250ms", max = "4s" }The keys are the fields of ActorConfig:
mailbox_capacityis"unbounded"(the default) or{ bounded = n }.supervision_strategyis"stop"(the default) or arestarttable.max_restartsis the only required key ofrestart. The others default to the values shown: the backoff grows from 250 ms to at most 4 s, and the restart count resets once the actor has run for 30 s without failing.
Durations use the humantime format, so "250ms", "4s" or "1m".
Load it
let config = Config::builder()
.add_source(File::new(CONFIG_FILE, FileFormat::Toml))
.build()
.context("reading the configuration")?
.try_deserialize::<ActorConfig>()
.context("deserializing the actor configuration")?;
let system = ActorSystem::with_config(Device, config);try_deserialize produces the ActorConfig, which you pass to ActorSystem::with_config for the root, or to context.spawn_with_config for a child. Because ActorConfig is Copy, you can load it once and use it for many actors.
Rely on the validation
Invalid configuration fails while loading, not when an actor fails for the first time. An unknown key is an error, so a typo does not silently fall back to a default. A backoff whose minimum is above its maximum is an error, too:
const INVALID: &str = r#"
[supervision_strategy.restart]
max_restarts = 3
backoff = { min = "10s", max = "1s" }
"#;let error = Config::builder()
.add_source(File::from_str(INVALID, FileFormat::Toml))
.build()
.context("reading the configuration")?
.try_deserialize::<ActorConfig>()
.expect_err("contradicting backoff bounds are rejected");
println!("Rejected: {error}");The error names the offending key. In your application, return it from main instead of printing it, so a misconfigured service does not start.
Run it
From a clone of the tellus repository:
cargo run --quiet -p tellus --features serde --example how_to_configure_supervisionLoaded: ActorConfig { mailbox_capacity: Bounded(100), supervision_strategy: Restart(RestartPolicy { max_restarts: 3, backoff: Backoff { min: 250ms, max: 4s }, reset_after: 30s }) }
Rejected: max backoff 1s below min backoff 10s for key `supervision_strategy.backoff`The explanation Supervision and lifecycle describes what these values do at runtime.