|
| 1 | +# buzz-feature-flags |
| 2 | + |
| 3 | +Provider-neutral, typed feature-flag contracts for Buzz server crates. |
| 4 | + |
| 5 | +This crate is infrastructure-only. It defines a small API for flag evaluation, |
| 6 | +plus a static evaluator and an optional LaunchDarkly adapter behind a compile |
| 7 | +feature. |
| 8 | + |
| 9 | +## Purpose |
| 10 | + |
| 11 | +`buzz-feature-flags` centralizes typed flag evaluation so server crates can use |
| 12 | +flags without importing vendor SDK types. |
| 13 | + |
| 14 | +Provider-neutral types: |
| 15 | + |
| 16 | +- `BooleanFlag` |
| 17 | +- `IntegerFlag` (`i64`, including negative values) |
| 18 | +- `EvaluationContext` (required `CommunityId`, optional actor `PublicKey`) |
| 19 | +- `FlagEvaluator` (typed `evaluate_bool` and `evaluate_int`) |
| 20 | +- `StaticEvaluator` (always returns declared defaults) |
| 21 | +- `EnvironmentEvaluator` (process-wide immutable environment snapshot) |
| 22 | +- `EnvironmentDiagnostic` (sanitized malformed-value report) |
| 23 | + |
| 24 | +LaunchDarkly support is optional and compile-gated behind |
| 25 | +`buzz-feature-flags/launchdarkly`. |
| 26 | + |
| 27 | +`EnvironmentEvaluator` is provider-neutral and always available (no Cargo |
| 28 | +feature and no external dependency). |
| 29 | + |
| 30 | +## Environment Variable Naming |
| 31 | + |
| 32 | +`EnvironmentEvaluator` reads only the fixed namespace |
| 33 | +`BUZZ_FEATURE_FLAG_`. |
| 34 | + |
| 35 | +For each flag key: |
| 36 | + |
| 37 | +- uppercase ASCII letters, |
| 38 | +- replace each run of non-ASCII-alphanumeric characters with `_`, |
| 39 | +- trim leading/trailing `_`, |
| 40 | +- prepend `BUZZ_FEATURE_FLAG_`. |
| 41 | + |
| 42 | +Example: `relay.feature.query-v2` → `BUZZ_FEATURE_FLAG_RELAY_FEATURE_QUERY_V2`. |
| 43 | + |
| 44 | +Normalized names must be unique across declared flags. Collisions (for example |
| 45 | +`a-b` and `a_b`) intentionally map to the same environment variable. Enforcing |
| 46 | +uniqueness belongs in a future flag registry; this crate does not add a |
| 47 | +registry yet. |
| 48 | + |
| 49 | +## Relay Artifact Contract (not yet wired into `buzz-relay`) |
| 50 | + |
| 51 | +The intended composition root is the outer relay artifact. It must select |
| 52 | +exactly one provider at compile time: |
| 53 | + |
| 54 | +- `static-feature-flags` |
| 55 | +- `environment-feature-flags` |
| 56 | +- `launchdarkly-feature-flags` |
| 57 | + |
| 58 | +`launchdarkly-feature-flags` is the only relay feature that forwards to |
| 59 | +`buzz-feature-flags/launchdarkly`. `static-feature-flags` and |
| 60 | +`environment-feature-flags` keep the reusable crate vendor-neutral and still |
| 61 | +allow adapter code to compile in tests. |
| 62 | + |
| 63 | +The relay artifact boundary, not this reusable crate, owns exact-one |
| 64 | +enforcement. Consumer integration PRs must carry `exact-one compile_error guards` |
| 65 | +verbatim/equivalently. That keeps `buzz-feature-flags` free to compile multiple |
| 66 | +adapters for tests while ensuring a staging or production relay artifact cannot |
| 67 | +choose a different evaluator at runtime. |
| 68 | + |
| 69 | +This repository currently adds the crate and adapter, but does **not** yet wire |
| 70 | +relay `AppState` or handlers to consume it. `crates/buzz-relay/Cargo.toml` |
| 71 | +still has no dependency on `buzz-feature-flags`, so current workspace/default |
| 72 | +builds remain intentionally unchanged. The executable contract for the future |
| 73 | +relay integration lives in |
| 74 | +`tests/fixtures/relay-feature-selection`. |
| 75 | + |
| 76 | +## Composition Root Shape (artifact boundary) |
| 77 | + |
| 78 | +Construct once at process startup, then inject shared `Arc<dyn FlagEvaluator>` |
| 79 | +into server components. |
| 80 | + |
| 81 | +```rust |
| 82 | +use std::sync::Arc; |
| 83 | +use std::time::Duration; |
| 84 | + |
| 85 | +use buzz_feature_flags::{EnvironmentEvaluator, FlagEvaluator, StaticEvaluator}; |
| 86 | +#[cfg(feature = "launchdarkly-feature-flags")] |
| 87 | +use buzz_feature_flags::launchdarkly::{ |
| 88 | + LaunchDarklyEvaluator, LaunchDarklyInitError, LaunchDarklyRuntimeConfig, |
| 89 | + LaunchDarklyStartError, |
| 90 | +}; |
| 91 | + |
| 92 | +#[cfg(not(any( |
| 93 | + feature = "static-feature-flags", |
| 94 | + feature = "environment-feature-flags", |
| 95 | + feature = "launchdarkly-feature-flags", |
| 96 | +)))] |
| 97 | +compile_error!( |
| 98 | + "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" |
| 99 | +); |
| 100 | + |
| 101 | +#[cfg(any( |
| 102 | + all(feature = "static-feature-flags", feature = "environment-feature-flags"), |
| 103 | + all(feature = "static-feature-flags", feature = "launchdarkly-feature-flags"), |
| 104 | + all(feature = "environment-feature-flags", feature = "launchdarkly-feature-flags"), |
| 105 | +))] |
| 106 | +compile_error!( |
| 107 | + "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" |
| 108 | +); |
| 109 | + |
| 110 | +#[cfg(any(feature = "static-feature-flags", feature = "environment-feature-flags"))] |
| 111 | +#[derive(Default)] |
| 112 | +struct FeatureFlagRuntimeConfig; |
| 113 | + |
| 114 | +#[cfg(feature = "launchdarkly-feature-flags")] |
| 115 | +struct FeatureFlagRuntimeConfig { |
| 116 | + sdk_key: String, |
| 117 | + relay_proxy_endpoint: Option<String>, |
| 118 | +} |
| 119 | + |
| 120 | +struct RelayCompositionRoot { |
| 121 | + feature_flags: Arc<dyn FlagEvaluator>, |
| 122 | + environment_diagnostics: Option<Arc<EnvironmentEvaluator>>, |
| 123 | + #[cfg(feature = "launchdarkly-feature-flags")] |
| 124 | + launchdarkly_lifecycle: Option<Arc<LaunchDarklyEvaluator>>, |
| 125 | +} |
| 126 | + |
| 127 | +#[cfg(feature = "launchdarkly-feature-flags")] |
| 128 | +enum RelayStartupError { |
| 129 | + LaunchDarklyInit(LaunchDarklyInitError), |
| 130 | + LaunchDarklyStart(LaunchDarklyStartError), |
| 131 | +} |
| 132 | + |
| 133 | +#[cfg(feature = "static-feature-flags")] |
| 134 | +fn build_feature_flag_evaluator(_config: FeatureFlagRuntimeConfig) -> RelayCompositionRoot { |
| 135 | + RelayCompositionRoot { |
| 136 | + feature_flags: Arc::new(StaticEvaluator), |
| 137 | + environment_diagnostics: None, |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +#[cfg(feature = "environment-feature-flags")] |
| 142 | +fn build_feature_flag_evaluator(config: FeatureFlagRuntimeConfig) -> RelayCompositionRoot { |
| 143 | + let _ = config; |
| 144 | + let owner = Arc::new(EnvironmentEvaluator::from_process_environment()); |
| 145 | + let feature_flags: Arc<dyn FlagEvaluator> = owner.clone(); |
| 146 | + RelayCompositionRoot { |
| 147 | + feature_flags, |
| 148 | + environment_diagnostics: Some(owner), |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +#[cfg(feature = "launchdarkly-feature-flags")] |
| 153 | +async fn build_feature_flag_evaluator( |
| 154 | + config: FeatureFlagRuntimeConfig, |
| 155 | +) -> Result<RelayCompositionRoot, RelayStartupError> { |
| 156 | + let mut runtime_config = LaunchDarklyRuntimeConfig::new(config.sdk_key); |
| 157 | + if let Some(relay_proxy_endpoint) = config.relay_proxy_endpoint { |
| 158 | + runtime_config = runtime_config.with_relay_proxy_endpoint(relay_proxy_endpoint); |
| 159 | + } |
| 160 | + |
| 161 | + let owner = Arc::new( |
| 162 | + LaunchDarklyEvaluator::from_runtime_config(runtime_config) |
| 163 | + .map_err(RelayStartupError::LaunchDarklyInit)?, |
| 164 | + ); |
| 165 | + owner |
| 166 | + .start_with_default_executor_and_wait(Duration::from_secs(5)) |
| 167 | + .await |
| 168 | + .map_err(RelayStartupError::LaunchDarklyStart)?; |
| 169 | + |
| 170 | + let feature_flags: Arc<dyn FlagEvaluator> = owner.clone(); |
| 171 | + Ok(RelayCompositionRoot { |
| 172 | + feature_flags, |
| 173 | + environment_diagnostics: None, |
| 174 | + launchdarkly_lifecycle: Some(owner), |
| 175 | + }) |
| 176 | +} |
| 177 | +``` |
| 178 | + |
| 179 | +Each relay feature produces exactly one `build_feature_flag_evaluator` path, and |
| 180 | +runtime config carries only the selected provider's settings. There is no |
| 181 | +runtime provider enum, no provider-name environment variable, and no fallback |
| 182 | +selector. |
| 183 | + |
| 184 | +Startup is fail-closed: if the selected provider fails initialization (including |
| 185 | +`start_with_default_executor_and_wait` for LaunchDarkly), relay startup must |
| 186 | +return an error and stop rather than falling back to another evaluator. |
| 187 | + |
| 188 | +The extra concrete `Arc` is an owner/lifecycle handle to that same evaluator, |
| 189 | +not a layered provider. Consumers receive only the cloned `Arc<dyn |
| 190 | +FlagEvaluator>` view. Retain the environment owner to drain diagnostics after |
| 191 | +evaluations, and retain the LaunchDarkly owner so shutdown can call `close()`. |
| 192 | + |
| 193 | +`EnvironmentEvaluator` snapshots environment values once at construction, |
| 194 | +retains only `BUZZ_FEATURE_FLAG_` entries, ignores `EvaluationContext`, and |
| 195 | +never rereads process environment during evaluation. |
| 196 | + |
| 197 | +For deterministic tests or embedding, `EnvironmentEvaluator::from_pairs(...)` |
| 198 | +constructs the same immutable snapshot from explicit key/value pairs. |
| 199 | + |
| 200 | +Environment entries are untyped at construction, so malformed present values |
| 201 | +are detected when a typed flag is first evaluated. `take_diagnostics()` drains |
| 202 | +each sanitized diagnostic at most once per flag key and expected type. The |
| 203 | +composition root should retain the concrete environment evaluator and emit each |
| 204 | +drained diagnostic as a warning through the application's logging stack. |
| 205 | +Diagnostics contain no raw value or environment-variable name; the value |
| 206 | +snapshot itself remains immutable. |
| 207 | + |
| 208 | +## `buzz-db` Boundary (approved correction) |
| 209 | + |
| 210 | +`buzz-db` may evaluate flags internally when choosing between equivalent query |
| 211 | +implementations. It should depend on `buzz-feature-flags` without enabling the |
| 212 | +LaunchDarkly feature, and it should never construct or import provider types. |
| 213 | + |
| 214 | +Concise example (query path selection only): |
| 215 | + |
| 216 | +```rust |
| 217 | +use buzz_core::CommunityId; |
| 218 | +use std::sync::Arc; |
| 219 | + |
| 220 | +use buzz_feature_flags::{EvaluationContext, FlagEvaluator, IntegerFlag}; |
| 221 | + |
| 222 | +pub struct Db { |
| 223 | + feature_flags: Arc<dyn FlagEvaluator>, |
| 224 | +} |
| 225 | + |
| 226 | +impl Db { |
| 227 | + pub async fn list_events( |
| 228 | + &self, |
| 229 | + community: CommunityId, |
| 230 | + ) -> anyhow::Result<Vec<EventRow>> { |
| 231 | + let context = EvaluationContext::for_community(community); |
| 232 | + |
| 233 | + let query_version = self.feature_flags.evaluate_int( |
| 234 | + IntegerFlag::new("db.events.query-version", 1), |
| 235 | + &context, |
| 236 | + ); |
| 237 | + |
| 238 | + if query_version >= 2 { |
| 239 | + self.list_events_v2_sql(community).await |
| 240 | + } else { |
| 241 | + self.list_events_v1_sql(community).await |
| 242 | + } |
| 243 | + } |
| 244 | +} |
| 245 | +``` |
| 246 | + |
| 247 | +SQL details are intentionally omitted in this example; the key point is that |
| 248 | +public `Db` methods accept only domain inputs, while feature-flag evaluator |
| 249 | +wiring remains internal to `Db` construction. |
| 250 | + |
| 251 | +`EvaluationContext::for_actor` is appropriate only when the existing DB |
| 252 | +operation already receives an authoritative authenticated actor for domain |
| 253 | +behavior. Feature targeting must not add actor/pubkey parameters to otherwise |
| 254 | +actor-free DB APIs. |
| 255 | + |
| 256 | +For LaunchDarkly, the adapter context always includes kind `community` plus |
| 257 | +optional global kind `pubkey`. Percentage rollouts must explicitly choose a |
| 258 | +kind present in evaluation: rollouts must set `contextKind` to a kind present |
| 259 | +in evaluation (`community` or `pubkey`) when they are intended to bucket Buzz |
| 260 | +traffic. LaunchDarkly rollouts where configuration omits `contextKind` defaults |
| 261 | +to `user`; Buzz does not synthesize a `user` alias, so those rollouts bucket as |
| 262 | +zero and pick the first positive-weight variation. |
| 263 | + |
| 264 | +## Guardrails |
| 265 | + |
| 266 | +- Evaluation context inputs are authoritative server-resolved values |
| 267 | + (`community`, optional `actor`), not client-supplied targeting attributes. |
| 268 | +- Flags may choose between **equivalent** implementations only. |
| 269 | +- Flags must not weaken authorization, tenant isolation, ordering guarantees, |
| 270 | + transaction/consistency behavior, or schema invariants. |
| 271 | +- Declared defaults choose the established safe path. |
| 272 | +- Integer values must be validated at the consumer boundary before affecting |
| 273 | + behavior. |
| 274 | + |
| 275 | +## Fallback, Startup, and Lifecycle |
| 276 | + |
| 277 | +- `StaticEvaluator` always returns each flag's declared default. |
| 278 | +- `EnvironmentEvaluator` returns declared defaults when values are missing, |
| 279 | + empty, invalid, non-Unicode, or the normalized flag key is unusable. Present |
| 280 | + malformed values also produce a sanitized diagnostic; missing values do not. |
| 281 | +- LaunchDarkly adapter returns declared defaults when a flag is missing, wrong |
| 282 | + type, or evaluation fails. |
| 283 | +- LaunchDarkly numbers are SDK `f64` values. Integer evaluation accepts only |
| 284 | + mathematically integral values that convert to `i64` exactly from that `f64` |
| 285 | + representation; otherwise it returns each flag's declared default. |
| 286 | +- Startup chooses one evaluator at compile time (`StaticEvaluator`, |
| 287 | + `EnvironmentEvaluator`, or LaunchDarkly); provider precedence/stacking is out |
| 288 | + of scope. |
| 289 | +- If LaunchDarkly is used, call evaluator `close()` during process shutdown. |
| 290 | + `close()` blocks the calling thread while it flushes analytics, so async |
| 291 | + shutdown code should offload it to a blocking shutdown path. |
| 292 | +- Safety invariants must never rely on remote-flag availability. |
| 293 | + |
| 294 | +## Build and Test Expectations |
| 295 | + |
| 296 | +Build modes: |
| 297 | + |
| 298 | +```bash |
| 299 | +# Provider-neutral (default): no LaunchDarkly dependency activated |
| 300 | +cargo build -p buzz-feature-flags |
| 301 | + |
| 302 | +# Provider-neutral environment evaluator is included in the default build |
| 303 | +cargo test -p buzz-feature-flags --test environment_evaluator |
| 304 | + |
| 305 | +# LaunchDarkly adapter enabled |
| 306 | +cargo build -p buzz-feature-flags --features launchdarkly |
| 307 | +``` |
| 308 | + |
| 309 | +Dependency-graph expectation checks: |
| 310 | + |
| 311 | +```bash |
| 312 | +# Default graph should exclude launchdarkly-server-sdk |
| 313 | +cargo tree -p buzz-feature-flags |
| 314 | + |
| 315 | +# Feature graph should include launchdarkly-server-sdk |
| 316 | +cargo tree -p buzz-feature-flags --features launchdarkly |
| 317 | +``` |
| 318 | + |
| 319 | +Testing expectations: |
| 320 | + |
| 321 | +- Run provider-neutral tests and LaunchDarkly-feature tests for this crate. |
| 322 | +- Run the relay-artifact compile contract in |
| 323 | + `tests/relay_feature_selection_contract.rs`, including zero-feature and |
| 324 | + multiple-feature rejection. |
| 325 | +- Keep `tests/fixtures/relay-feature-selection/Cargo.lock` checked in for the |
| 326 | + nested `--locked` compile contract. Regenerate it from repo root with: |
| 327 | + |
| 328 | +```bash |
| 329 | +cargo generate-lockfile --manifest-path crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml |
| 330 | +``` |
| 331 | + |
| 332 | +- When `buzz-db` adopts flag-gated query selection, add parity tests proving |
| 333 | + old/new query paths return equivalent rows, ordering, and transactional |
| 334 | + behavior for the same inputs. |
| 335 | + |
| 336 | +## References |
| 337 | + |
| 338 | +- [ARCHITECTURE.md](../../ARCHITECTURE.md) |
| 339 | +- [docs/multi-tenant-relay.md](../../docs/multi-tenant-relay.md) |
0 commit comments