Feature flags with OpenFeature
Install an OpenFeature provider at startup, inject a flag client, and hide a route behind a flag with a guard that reads the flag name from #[meta].
A route that ships dark and turns on for some callers needs a flag system, a way to pass the caller to it, and a gate on the route. OpenFeature separates the application from the flag vendor: the application evaluates flags through a client, and a provider crate (flagd, LaunchDarkly and others) answers. Here a Flags singleton wraps the client and a FlagGuard evaluates the flag a handler declares.
This recipe compiled and ran against open-feature 0.3.0 with ulo 0.1.0-alpha.3.
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
ulo-transport = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
open-feature = "0.3"The code
The Table provider stands in for a vendor crate. It answers booleans only: new-search is on for everyone and beta-checkout is on for the targeting key ada.
use std::collections::HashMap;
use open_feature::provider::{FeatureProvider, ProviderMetadata, ResolutionDetails};
use open_feature::{
Client, EvaluationContext, EvaluationError, EvaluationErrorCode, EvaluationResult, OpenFeature, StructValue, async_trait,
};
use ulo::{App, AppBuilder, BoxError, Dep, Guard, controller, handlers, injectable, module};
use ulo_http::{CallError, ErrorKind, Http, HttpCx};
/// A flag's rule: on for everyone, or on for the listed targeting keys only.
enum Rule {
Everyone,
Only(&'static [&'static str]),
}
/// Stands in for flagd, LaunchDarkly or any other provider crate.
struct Table {
metadata: ProviderMetadata,
rules: HashMap<&'static str, Rule>,
}
impl Table {
fn new() -> Table {
Table {
metadata: ProviderMetadata::new("table"),
rules: HashMap::from([("new-search", Rule::Everyone), ("beta-checkout", Rule::Only(&["ada"]))]),
}
}
}
fn unsupported<T>() -> EvaluationResult<T> {
Err(EvaluationError::builder().code(EvaluationErrorCode::TypeMismatch).message("the table holds booleans only").build())
}
#[async_trait]
impl FeatureProvider for Table {
fn metadata(&self) -> &ProviderMetadata {
&self.metadata
}
async fn resolve_bool_value(&self, flag_key: &str, context: &EvaluationContext) -> EvaluationResult<ResolutionDetails<bool>> {
match self.rules.get(flag_key) {
Some(Rule::Everyone) => Ok(ResolutionDetails::new(true)),
Some(Rule::Only(keys)) => Ok(ResolutionDetails::new(context.targeting_key.as_deref().is_some_and(|key| keys.contains(&key)))),
None => Err(EvaluationError::builder().code(EvaluationErrorCode::FlagNotFound).build()),
}
}
async fn resolve_int_value(&self, _: &str, _: &EvaluationContext) -> EvaluationResult<ResolutionDetails<i64>> {
unsupported()
}
async fn resolve_float_value(&self, _: &str, _: &EvaluationContext) -> EvaluationResult<ResolutionDetails<f64>> {
unsupported()
}
async fn resolve_string_value(&self, _: &str, _: &EvaluationContext) -> EvaluationResult<ResolutionDetails<String>> {
unsupported()
}
async fn resolve_struct_value(&self, _: &str, _: &EvaluationContext) -> EvaluationResult<ResolutionDetails<StructValue>> {
unsupported()
}
}
/// The application's handle on the flag system. Installing the provider is the constructor's
/// job, so it happens once, at `connect()`.
pub struct Flags {
client: Client,
}
#[injectable]
impl Flags {
async fn new() -> Flags {
let mut api = OpenFeature::singleton_mut().await;
api.set_provider(Table::new()).await;
Flags { client: api.create_client() }
}
}
impl Flags {
/// An unknown flag, a provider error and a missing provider all read as off.
pub async fn enabled(&self, flag: &str, user: Option<&str>) -> bool {
let mut context = EvaluationContext::default();
context.targeting_key = user.map(str::to_owned);
self.client.get_bool_value(flag, Some(&context), None).await.unwrap_or(false)
}
}
/// Declared with `#[meta(..)]` on a handler that is behind a flag.
pub struct Flag(pub &'static str);
/// Refuses a handler declaring `Flag(name)` unless `name` is on for the caller in `x-user`.
/// The handler is answered as if its route did not exist.
#[injectable]
pub struct FlagGuard {
flags: Dep<Flags>,
}
impl Guard<Http> for FlagGuard {
async fn can_activate(&self, cx: &HttpCx) -> Result<bool, BoxError> {
let Some(Flag(name)) = cx.exec().handler().and_then(|handler| handler.meta::<Flag>()) else { return Ok(true) };
let user = cx.headers().get("x-user").and_then(|value| value.to_str().ok());
if self.flags.enabled(name, user).await {
Ok(true)
} else {
Err(CallError::new(ErrorKind::NotFound, "not found").into())
}
}
}
#[controller]
pub struct ShopController;
#[handlers]
#[guards(FlagGuard)]
impl ShopController {
#[ulo_http::get("/cart")]
fn cart(&self) -> &'static str {
"cart"
}
#[ulo_http::get("/checkout")]
#[meta(Flag("beta-checkout"))]
fn checkout(&self) -> &'static str {
"beta checkout"
}
#[ulo_http::get("/typo")]
#[meta(Flag("beta-chekout"))]
fn typo(&self) -> &'static str {
"unreachable"
}
}
#[module(providers = [Flags, FlagGuard], controllers = [ShopController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
Flags::newis anasyncconstructor, which an#[injectable]impl allows. It installs the provider into OpenFeature's process-wide singleton and builds the client from it. The constructor runs atconnect(), before the first request.Flags::enabledbuilds anEvaluationContextfor the call. The targeting key is what a provider's rules match on, and further attributes go in withwith_custom_field.- Every failure reads as off. An evaluation error makes
get_bool_valuereturnErr, an unknown flag (FlagNotFound) included, andunwrap_or(false)turns that into a closed route. Flagis the declaration.#[meta(Flag("beta-checkout"))]on a handler records it, and the guard reads it throughcx.exec().handler(). A handler with noFlagpasses.FlagGuardanswers a closed flag with aNotFounderror and notOk(false), which would answer 403. The route reads as nonexistent to a caller the flag excludes.- The context comes from the call: here the
x-userheader. Production code reads an identity an earlier guard wrote into the execution's extensions.
Test
The test uses the example support crate in the repository (ex_support::start and call); any HTTP client does the same.
use ex_support::http::{Call, call};
use ex_support::start;
use r3::flags::builder;
#[tokio::test]
async fn a_flagged_route_exists_only_for_the_callers_the_flag_admits() {
let server = start(builder()).await;
let status = async |path: &str, user: Option<&str>| {
let mut request = Call::get(path);
if let Some(user) = user {
request = request.header("x-user", user);
}
call(server.addr, request).await.status
};
assert_eq!(status("/cart", None).await, 200);
assert_eq!(status("/checkout", None).await, 404);
assert_eq!(status("/checkout", Some("bob")).await, 404);
assert_eq!(status("/checkout", Some("ada")).await, 200);
assert_eq!(status("/typo", Some("ada")).await, 404, "a flag the provider does not know reads as off");
server.stop().await.unwrap();
}Failure modes
- OpenFeature's provider registry is process-global. Two applications in one process, a test binary running several
TestApps included, share the provider thatFlags::newinstalled last. Run flag tests in one test per binary, or install the provider once outside the application and haveFlags::newonly create the client. - A misspelled flag name never fails startup. It reads as off, so the route stays closed, as
/typoshows. A test that asserts each flagged route opens for some caller catches it. Flags::enabledawaits the provider on every guarded request. A provider that calls a remote service should cache or stream its flags; the guard has no timeout of its own.- The guard is written for
Httpbecause it reads a header. The flag evaluation is transport-neutral, and a guard for another transport reads its own context the way the one-guard-two-transports pattern does.
Reference
- Guards: declaring a guard, order, and reading
#[meta]through the handler. - Macros:
#[meta],#[guards]and#[injectable]. - Error handling:
CallErrorand what it renders as. - Providers: the async constructor.