Skip to content

Commit 8f6b66f

Browse files
TheSentinel454codexclaude
authored
Select one feature flag provider at compile time (#7677)
## Why Buzz server components need one typed feature-flag contract without forcing the open-source build to depend on LaunchDarkly. A staging or production relay must not be able to choose the wrong provider through runtime configuration. ## What - Adds typed boolean and signed `i64` flags with static, environment, and compile-gated LaunchDarkly evaluators. - Defines an executable relay artifact contract that compiles exactly one provider. - Rejects zero or multiple relay provider features at compile time. - Runs the LaunchDarkly feature tests and the provider compile matrix in the unit CI lane and fallback test script. ## How `buzz-feature-flags` stays provider-neutral. The future relay composition root will expose one build path per artifact feature: `static-feature-flags`, `environment-feature-flags`, or `launchdarkly-feature-flags`. Runtime configuration carries only settings for the selected provider. It never carries a provider name, fallback, or precedence rule. The crate still has no relay consumer. A locked compile fixture proves each singleton builds and every zero or multi-provider combination fails until the relay adopts this contract. This removes the proposed runtime `ProviderMode` and leaves one provider, one construction path, and one evaluator per artifact. ## Risk This PR still has no relay or app consumer, so it changes no user-visible behavior. Risk is limited to the new feature-flag crate, its compile contract, and its unit-test lane. ## Testing An external Rust consumer at `30cf968bfe85e82980fda7e63f5bebe649ca939f` exercised six environment-evaluator scenarios and 59 assertions. The compile-time correction adds no live consumer to exercise manually. ## Bigger picture When `buzz-relay` adopts this crate, its build manifests must map each distribution to one provider feature. That consumer PR must verify live Relay Proxy reachability, secret ingestion, lifecycle ownership, and user-visible behavior. Generated with Codex --------- Signed-off-by: tornquist <[email protected]> Co-authored-by: Codex <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent 0275372 commit 8f6b66f

15 files changed

Lines changed: 5778 additions & 48 deletions

File tree

‎Cargo.lock‎

Lines changed: 386 additions & 48 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ members = [
1717
"crates/buzz-ws-client",
1818
"crates/buzz-admin",
1919
"crates/buzz-deletion",
20+
"crates/buzz-feature-flags",
2021
"crates/buzz-workflow",
2122
"crates/buzz-media",
2223
"crates/buzz-cli",
@@ -142,6 +143,7 @@ buzz-core = { path = "crates/buzz-core" }
142143
buzz-conformance = { path = "crates/buzz-conformance" }
143144
buzz-db = { path = "crates/buzz-db" }
144145
buzz-deletion = { path = "crates/buzz-deletion" }
146+
buzz-feature-flags = { path = "crates/buzz-feature-flags" }
145147
buzz-auth = { path = "crates/buzz-auth" }
146148
buzz-pubsub = { path = "crates/buzz-pubsub" }
147149
buzz-search = { path = "crates/buzz-search" }

‎Justfile‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,10 @@ test-unit:
414414
# because nothing in CI runs `cargo test --workspace` — workspace
415415
# membership alone buys clippy/check, not a single executed test.
416416
cargo nextest run -p buzz-backend-kubernetes
417+
# Feature-flag crate coverage: run once with LaunchDarkly enabled.
418+
# This includes all default tests plus the cfg(feature="launchdarkly")
419+
# tests, avoiding duplicate default-only execution in the unit lane.
420+
cargo nextest run -p buzz-feature-flags --features launchdarkly
417421
# buzz-agent: two infra-free concerns run together by executing the
418422
# whole crate (lib + integration tests), because nothing in CI runs
419423
# `cargo test --workspace`, so without this stanza neither the crate's
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
[package]
2+
name = "buzz-feature-flags"
3+
version.workspace = true
4+
edition.workspace = true
5+
rust-version.workspace = true
6+
license.workspace = true
7+
repository.workspace = true
8+
description = "Typed feature-flag contracts and evaluators for Buzz"
9+
10+
[features]
11+
launchdarkly = ["dep:launchdarkly-server-sdk"]
12+
13+
[dependencies]
14+
buzz-core = { workspace = true }
15+
http = "1"
16+
launchdarkly-server-sdk = { version = "=3.2.0", optional = true }
17+
thiserror = { workspace = true }
18+
19+
[dev-dependencies]
20+
serde_json = { workspace = true }
21+
tempfile = "3"
22+
tokio = { workspace = true }
Lines changed: 339 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,339 @@
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

Comments
 (0)