# Zenmanage Rust SDK
[](https://github.com/zenmanage/zenmanage-rust/actions/workflows/ci.yml) [](https://crates.io/crates/zenmanage) [](LICENSE) [](https://app.codacy.com/gh/zenmanage/zenmanage-rust/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [](https://docs.rs/zenmanage)
Add feature flags to your Rust services. Rules are fetched once and evaluated in your process, so reading a flag doesn't call the API for an answer.
- Async, on `tokio`
- Targeting by context, segment and attributes
- Percentage rollouts that put the same user in the same bucket every time
- Your defaults when a flag or the API can't be reached
- Memory, filesystem, no-op or your own cache
- State helpers for Axum, Actix Web and Rocket
## Requirements
- Rust 1.88 or later
- A `tokio` runtime
- A server key (`srv_...`). This SDK is for servers, so client (`cli_`) and mobile (`mob_`) keys are rejected.
## Installation
```bash
cargo add zenmanage
```
With a web framework integration:
```bash
cargo add zenmanage --features axum
```
```bash
cargo add zenmanage --features actix
```
```bash
cargo add zenmanage --features rocket
```
## Get started
```rust,no_run
use zenmanage::{ConfigBuilder, Zenmanage};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let sdk = Zenmanage::new(
ConfigBuilder::create()
.with_environment_token("srv_your_server_key_here")
.build()?,
)?;
let flag = sdk.flags().single("new-dashboard", Some(false)).await?;
if flag.is_enabled() {
println!("New dashboard enabled");
}
// Only needed in programs that exit straight away. See "Usage reporting".
sdk.flags().flush_usage().await;
Ok(())
}
```
Create one `Zenmanage` when your application starts and share it. `flags()` is cheap: every manager it returns uses the same loaded rules.
## Targeting with a context
A context describes who or what you're evaluating for. Rules target its type, identifier and attributes.
```rust,no_run
# use zenmanage::{Attribute, Context, Zenmanage};
# async fn example(sdk: &Zenmanage) -> zenmanage::Result<()> {
let context = Context::single("user", "user-123", Some("Taylor"))
.add_attribute(Attribute::new("country", vec!["US"]))
.add_attribute(Attribute::new("plan", vec!["pro"]));
let flag = sdk
.flags()
.with_context(context)
.single("advanced-reports", Some(false))
.await?;
# Ok(())
# }
```
`with_context` returns a manager scoped to that context. It doesn't change any other manager, so build one per request.
Attributes can hold several values. A condition such as "equals" or "contains" matches when any of them does, and its opposite matches when none does.
## Percentage rollouts
There's nothing to configure in code. Start a rollout in Zenmanage and pass a context with an identifier. The SDK hashes the rollout's salt with the identifier (CRC32B), so a user stays in or out on every server and across restarts. A context without an identifier is never in a rollout.
## Defaults
`single` looks for a value in this order:
1. The flag from Zenmanage
2. The default you pass to `single`
3. The `DefaultsCollection` entry
4. If there is none of these, an error
```rust,no_run
# use zenmanage::{DefaultsCollection, Zenmanage};
# async fn example(sdk: &Zenmanage) -> zenmanage::Result<()> {
let defaults = DefaultsCollection::new()
.set("new-ui", true)
.set("max-items", 25);
let flag = sdk
.flags()
.with_defaults(defaults)
.single("max-items", None::<i32>)
.await?;
# Ok(())
# }
```
If the rules can't be loaded, `single` logs a warning and uses your default, so an outage doesn't turn into a failed request. Give every flag a default.
## Flag values
A flag is a `boolean`, `string`, `number` or `json` flag, with an accessor for each: `as_bool()`, `as_string()`, `as_number()` and `as_json()`. Use `is_enabled()` to ask whether a boolean flag is on.
```rust,no_run
# use zenmanage::Zenmanage;
# async fn example(sdk: &Zenmanage) -> zenmanage::Result<()> {
let theme = sdk
.flags()
.single("theme-config", Some(serde_json::json!({"mode": "light"})))
.await?;
println!("{}", theme.as_json());
# Ok(())
# }
```
Calling the wrong accessor never panics and never converts. It returns an empty value:
| Flag type | `as_bool()` | `as_string()` | `as_number()` | `as_json()` |
|---|---|---|---|---|
| `boolean` | the value | `""` | `0` | `{}` |
| `string` | `true` | the value | `0` | `{}` |
| `number` | `true` | `""` | the value | `{}` |
| `json` | `true` | `""` | `0` | the object or array |
`as_bool()` is `true` for every flag that isn't boolean, even a number flag set to `0`. `is_enabled()` is `false` for all of them.
A default takes its type from the Rust value: `bool`, text, `i32` or `f64`, or a `serde_json::Value`. A JSON object, array or `null` becomes a `json` default. A JSON scalar becomes the matching plain type.
## All flags
```rust,no_run
# use zenmanage::Zenmanage;
# async fn example(sdk: &Zenmanage) -> zenmanage::Result<()> {
for flag in sdk.flags().all().await? {
println!("{}: {:?}", flag.key(), flag.value());
}
# Ok(())
# }
```
`all()` evaluates every flag for the manager's context. It returns an error if the rules have never loaded, and it doesn't report usage.
## Caching and refreshing
Rules are loaded the first time you need them and used for the cache TTL (one hour by default), counted from when they were fetched, even if they come from a shared cache. The next read after that reloads them. If the reload fails, the SDK keeps using the rules it has and tries again within 30 seconds.
To pick up a change right away:
```rust,no_run
# use zenmanage::Zenmanage;
# async fn example(sdk: &Zenmanage) -> zenmanage::Result<()> {
sdk.flags().refresh_rules().await?;
# Ok(())
# }
```
Choose where the rules are cached:
```rust,no_run
# use zenmanage::{CacheBackendType, ConfigBuilder};
# fn example() -> zenmanage::Result<()> {
let config = ConfigBuilder::create()
.with_environment_token("srv_your_server_key_here")
.with_cache_ttl(300)
.with_cache_backend(CacheBackendType::FileSystem)
.with_cache_directory("/var/cache/zenmanage")
.build()?;
# Ok(())
# }
```
Use a separate cache directory for each environment. To cache somewhere else, such as Redis, implement `CacheBackend` and pass it to `with_cache`. A cache that fails is logged and skipped; the SDK fetches from the API instead.
## Usage reporting
Each `single` call reports the flag key, your context and your default, so Zenmanage can show which flags are in use. Reports are sent in the background and never delay or fail an evaluation.
A report that's still in flight is lost when the `tokio` runtime shuts down. In a command-line tool, job or serverless function, call `flush_usage` before you exit:
```rust,no_run
# use zenmanage::Zenmanage;
# async fn example(sdk: &Zenmanage) {
sdk.flags().flush_usage().await;
# }
```
`report_usage` records a flag you read some other way, such as from `all()`. Turn reporting off with `with_usage_reporting(false)`.
## Errors and logging
Methods return `zenmanage::Result`, with `ZenmanageError` saying what failed. Requests that fail to connect, time out or get a 5xx response are tried three times.
The SDK logs through the [`log`](https://docs.rs/log) crate. Add a logger such as `env_logger` to see its warnings.
## Web frameworks
Each integration puts a shared SDK in your framework's state.
| Framework | Feature | Helper | Example |
|---|---|---|---|
| Axum 0.8 | `axum` | `integrations::axum::extension_layer` | [`axum_integration.rs`](examples/axum_integration.rs) |
| Actix Web 4 | `actix` | `integrations::actix::app_data` | [`actix_integration.rs`](examples/actix_integration.rs) |
| Rocket 0.5 | `rocket` | `integrations::rocket::manage_sdk` | [`rocket_integration.rs`](examples/rocket_integration.rs) |
```rust,ignore
async fn handler(Extension(sdk): Extension<Arc<Zenmanage>>) -> String {
let context = Context::single("user", "user-123", None::<String>);
match sdk.flags().with_context(context).single("new-dashboard", Some(false)).await {
Ok(flag) => format!("enabled: {}", flag.is_enabled()),
Err(error) => format!("error: {error}"),
}
}
```
## Configuration
| Builder method | Environment variable | Default |
|---|---|---|
| `with_environment_token` | `ZENMANAGE_ENVIRONMENT_TOKEN` | required |
| `with_cache_ttl` (seconds) | `ZENMANAGE_CACHE_TTL` | `3600` |
| `with_cache_backend` | `ZENMANAGE_CACHE_BACKEND` (`memory`, `filesystem`, `null`) | memory |
| `with_cache_directory` | `ZENMANAGE_CACHE_DIR` | required for `filesystem` |
| `with_usage_reporting` | `ZENMANAGE_ENABLE_USAGE_REPORTING` | on |
| `with_api_endpoint` | `ZENMANAGE_API_ENDPOINT` | `https://api.zenmanage.com` |
| `with_cache` | | none |
`ConfigBuilder::from_environment()` reads the variables.
## Examples
```bash
export ZENMANAGE_ENVIRONMENT_TOKEN="srv_your_server_key_here"
```
```bash
cargo run --example simple_flags
```
The [examples](examples) folder covers contexts, defaults, caching, A/B tests, percentage rollouts and each web framework.
## Versioning
The crate follows [semantic versioning](https://semver.org).
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md). To report a security problem, see [SECURITY.md](SECURITY.md).
## License
MIT. See [LICENSE](LICENSE).