Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(feature-flags): add async backend flag loading (#7985)
Wolf Mermelsteind98d3f408156
diff --git a/.config/hakari.toml b/.config/hakari.tomlindex 5e2db9deb0..f53ca33fc1 100644--- a/.config/hakari.toml+++ b/.config/hakari.toml@@ -43,6 +43,8 @@ workspace-members = [# Standalone protocol library. Until a deployable service consumes it,# ACP's schema features must not alter unrelated service build/codegen closures."agent_runtime_protocol",+ # No deployable consumer yet; integrate with workspace-hack when service wiring lands.+ "feature_flags","xtask",# xtask command crates: dev-only automation split out of xtask so each# `cargo x <cmd>` compiles only its own dependency set.diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 6d05bb360f..bff9b218a5 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -6291,6 +6291,11 @@"crates/remote_env_var","crates/workspace-hack"],+ "feature_flags": [+ "crates/cowlike",+ "crates/feature_flags",+ "crates/macro_user_id"+ ],"fig_engine": ["crates/fig_engine"],diff --git a/Cargo.lock b/Cargo.lockindex 74642a7d41..c3d21c5a51 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7711,6 +7711,20 @@ dependencies = ["simd-adler32",]+[[package]]+name = "feature_flags"+version = "0.1.0"+dependencies = [+ "macro_user_id",+ "reqwest 0.13.4",+ "rootcause",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "wiremock",+]+[[package]]name = "ff"version = "0.13.1"diff --git a/Cargo.toml b/Cargo.tomlindex 57f128d49f..2cf2fff4a7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -52,6 +52,7 @@ members = ["crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry","crates/favorites",+ "crates/feature_flags","crates/foreign_entity","crates/genai_telemetry","crates/generic_email_domains",diff --git a/crates/feature_flags/Cargo.toml b/crates/feature_flags/Cargo.tomlnew file mode 100644index 0000000000..bbbc01636a--- /dev/null+++ b/crates/feature_flags/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "feature_flags"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+macro_user_id = { path = "../macro_user_id" }+rootcause = { workspace = true }+reqwest = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["time"] }++[dev-dependencies]+wiremock = { workspace = true }diff --git a/crates/feature_flags/README.md b/crates/feature_flags/README.mdnew file mode 100644index 0000000000..0123bf903f--- /dev/null+++ b/crates/feature_flags/README.md@@ -0,0 +1,85 @@+# Feature flags++Await one load for the authenticated Macro user ID, then read the stable snapshot+synchronously. Consumers depend on `FeatureFlags`; composition roots select an+outbound adapter. A variant counts as enabled. Missing flags read `false`/`None`;+a failed load returns `Err`, leaving fallback policy to the caller.++```rust+use feature_flags::{FeatureFlags, FlagSnapshot, FlagValue};+use feature_flags::outbound::fake::FakeFeatureFlags;+use macro_user_id::user_id::MacroUserIdStr;++# async fn example() -> Result<(), rootcause::Report> {+let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+let mut feature_flags = FakeFeatureFlags::default();+feature_flags.set(user_id.clone(), Ok(FlagSnapshot::new([+ ("agent-code-mode".into(), FlagValue::Boolean(true)),+ ("layout".into(), FlagValue::Variant("compact".into())),+])));+let flags = feature_flags.load(&user_id).await?;+assert!(flags.is_enabled("agent-code-mode"));+assert_eq!(flags.variant("layout"), Some("compact"));+assert_eq!(flags.get("missing"), None);+# Ok(())+# }+```++Pass the authenticated user identifier used by frontend PostHog identification.+Do not substitute an email address, derive a new ID, or share one user's snapshot+with another. Snapshots have no automatic refresh; a new load creates a new one.+No flag is an authorization grant by itself.++## PostHog adapter++Construct once at the service composition root and clone to share its HTTP pool:++```rust+use feature_flags::outbound::posthog::PostHogFeatureFlags;+use std::time::Duration;++# fn example() -> Result<(), rootcause::Report> {+let feature_flags = PostHogFeatureFlags::new(+ "https://us.i.posthog.com", // Use the project's regional ingestion origin.+ "injected-project-token".to_owned(),+ Duration::from_secs(3),+)?;+# Ok(())+# }+```++The constructor rejects blank keys, zero timeouts, and hosts with credentials,+paths, queries, or fragments. There is no silently disabled configuration. HTTP+is accepted for local tests/self-hosting; production should use HTTPS. No+configuration is loaded from the environment by this crate.++Each load makes one POST to `/flags/?v=2` with the project token and exact Macro+user ID. `evaluation_runtime: "server"` requests server/all-runtime flags;+`geoip_disable: true` prevents targeting by the backend's IP. Person targeting+uses PostHog's stored properties. Group targeting and property overrides are+not supported. Reads do not emit `$feature_flag_called` events, so this adapter+alone does not provide experiment exposure tracking.++The response must contain a `flags` map and explicit boolean+`errorsWhileComputingFlags`. Computation errors, any nonempty `quotaLimited`+array, provider error fields, and per-flag `failed: true` reject the entire load.+Malformed JSON/types, mismatched flag keys, and non-success HTTP statuses also+fail. A healthy empty map succeeds. Disabled flags remain boolean `false` even+if the provider includes a variant. Error reports omit response bodies and+request URLs; the adapter logs neither credentials nor user details.++The configured timeout bounds the load, including response-body reading.+Redirects and retries are disabled. There is no cache, polling, local evaluation,+legacy-response fallback, or hidden per-key request. Callers choose whether to+propagate errors or use an explicit fallback, such as `FlagSnapshot::default()`.++Direct HTTP is intentional: the released `posthog-rs` 0.27.0 snapshot API keeps+computation-error/quota indicators private and may return partial evaluations as+`Ok`. It cannot preserve this crate's strict load-failure contract. This adapter+only maps remote results; PostHog still owns targeting and evaluation.++Wire references:++- [Official flags API](https://posthog.com/docs/api/flags)+- [Request runtime and GeoIP fields](https://github.com/PostHog/posthog/blob/master/rust/feature-flags/src/flags/flag_request.rs)+- [Official response types, including per-flag failures](https://github.com/PostHog/posthog/blob/master/rust/feature-flags/src/api/types.rs)diff --git a/crates/feature_flags/src/domain.rs b/crates/feature_flags/src/domain.rsnew file mode 100644index 0000000000..a3dee16490--- /dev/null+++ b/crates/feature_flags/src/domain.rs@@ -0,0 +1,68 @@+//! Provider-neutral flag loading and immutable evaluation results.++use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use std::{collections::HashMap, future::Future};++/// A successfully evaluated boolean flag or multivariate assignment.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FlagValue {+ /// Whether a boolean flag is enabled.+ Boolean(bool),+ /// The assigned variant of an enabled multivariate flag.+ Variant(String),+}++/// Stable results from one completed load for one authenticated user.+///+/// Reads perform no evaluation or network requests. Missing keys are distinct+/// from failed loads: only a successful load produces a snapshot.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct FlagSnapshot {+ flags: HashMap<String, FlagValue>,+}++impl FlagSnapshot {+ /// Construct a snapshot from successfully evaluated flags.+ pub fn new(flags: impl IntoIterator<Item = (String, FlagValue)>) -> Self {+ Self {+ flags: flags.into_iter().collect(),+ }+ }++ /// Whether a flag is enabled, including any assigned variant.+ /// Disabled and missing keys return `false`.+ pub fn is_enabled(&self, key: &str) -> bool {+ matches!(+ self.get(key),+ Some(FlagValue::Boolean(true) | FlagValue::Variant(_))+ )+ }++ /// Read a flag, preserving the distinction between disabled and missing.+ pub fn get(&self, key: &str) -> Option<&FlagValue> {+ self.flags.get(key)+ }++ /// Read a variant; boolean and missing flags return `None`.+ pub fn variant(&self, key: &str) -> Option<&str> {+ match self.get(key) {+ Some(FlagValue::Variant(variant)) => Some(variant),+ _ => None,+ }+ }+}++/// Capability for loading all flags for an authenticated Macro user.+///+/// Implementations use the exact Macro user ID as the distinct ID, without+/// deriving it from email or normalizing it. Failures, including incomplete+/// evaluations, return an error; callers own fallback policy. No reads on the+/// resulting snapshot can trigger further evaluation.+pub trait FeatureFlags: Send + Sync {+ /// Await evaluation once, then use synchronous reads on the returned snapshot.+ fn load(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<FlagSnapshot, Report>> + Send;+}diff --git a/crates/feature_flags/src/lib.rs b/crates/feature_flags/src/lib.rsnew file mode 100644index 0000000000..60a3dcdf0e--- /dev/null+++ b/crates/feature_flags/src/lib.rs@@ -0,0 +1,7 @@+#![deny(missing_docs)]+#![doc = include_str!("../README.md")]++pub mod domain;+pub mod outbound;++pub use domain::{FeatureFlags, FlagSnapshot, FlagValue};diff --git a/crates/feature_flags/src/outbound.rs b/crates/feature_flags/src/outbound.rsnew file mode 100644index 0000000000..78b7428450--- /dev/null+++ b/crates/feature_flags/src/outbound.rs@@ -0,0 +1,4 @@+//! Implementations of the feature flag loading capability.++pub mod fake;+pub mod posthog;diff --git a/crates/feature_flags/src/outbound/fake.rs b/crates/feature_flags/src/outbound/fake.rsnew file mode 100644index 0000000000..00b592ecab--- /dev/null+++ b/crates/feature_flags/src/outbound/fake.rs@@ -0,0 +1,35 @@+//! Deterministic, per-user feature flags for consumer tests.++use crate::{FeatureFlags, FlagSnapshot};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use std::collections::HashMap;++#[cfg(test)]+mod test;++/// A fake loader configured with independent successful or failing user results.+/// Unconfigured users fail explicitly to expose missing test setup.+#[derive(Default)]+pub struct FakeFeatureFlags {+ users: HashMap<MacroUserIdStr<'static>, Result<FlagSnapshot, String>>,+}++impl FakeFeatureFlags {+ /// Configure a user's result. An error message simulates a load failure.+ pub fn set(&mut self, user_id: MacroUserIdStr<'static>, result: Result<FlagSnapshot, String>) {+ self.users.insert(user_id, result);+ }+}++impl FeatureFlags for FakeFeatureFlags {+ async fn load(&self, user_id: &MacroUserIdStr<'_>) -> Result<FlagSnapshot, Report> {+ match self.users.get(user_id) {+ Some(Ok(snapshot)) => Ok(snapshot.clone()),+ Some(Err(message)) => Err(rootcause::report!("{message}")),+ None => Err(rootcause::report!(+ "No feature flag result configured for user"+ )),+ }+ }+}diff --git a/crates/feature_flags/src/outbound/fake/test.rs b/crates/feature_flags/src/outbound/fake/test.rsnew file mode 100644index 0000000000..0b9330ca6f--- /dev/null+++ b/crates/feature_flags/src/outbound/fake/test.rs@@ -0,0 +1,49 @@+use super::*;+use crate::FlagValue;++#[tokio::test]+async fn user_results_are_isolated_and_snapshots_remain_stable() {+ let alice = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let bob = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut flags = FakeFeatureFlags::default();+ flags.set(+ alice.clone(),+ Ok(FlagSnapshot::new([+ ("code".into(), FlagValue::Boolean(true)),+ ("layout".into(), FlagValue::Variant("compact".into())),+ ])),+ );+ flags.set(+ bob.clone(),+ Ok(FlagSnapshot::new([(+ "code".into(),+ FlagValue::Boolean(false),+ )])),+ );++ let snapshot = flags.load(&alice).await.unwrap();+ let bob_snapshot = flags.load(&bob).await.unwrap();+ assert!(snapshot.is_enabled("code"));+ assert!(snapshot.is_enabled("layout"));+ assert_eq!(snapshot.variant("layout"), Some("compact"));+ assert!(!bob_snapshot.is_enabled("code"));+ assert_eq!(bob_snapshot.get("code"), Some(&FlagValue::Boolean(false)));+ assert_eq!(bob_snapshot.variant("code"), None);+ assert!(!bob_snapshot.is_enabled("missing"));+ assert_eq!(bob_snapshot.get("missing"), None);++ flags.set(alice.clone(), Ok(FlagSnapshot::default()));+ assert!(snapshot.is_enabled("code"));+ assert!(!flags.load(&alice).await.unwrap().is_enabled("code"));+}++#[tokio::test]+async fn load_errors_are_not_successful_empty_snapshots() {+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut flags = FakeFeatureFlags::default();+ assert!(flags.load(&user).await.is_err());+ flags.set(user.clone(), Err("provider unavailable".into()));+ assert!(flags.load(&user).await.is_err());+ flags.set(user.clone(), Ok(FlagSnapshot::default()));+ assert_eq!(flags.load(&user).await.unwrap(), FlagSnapshot::default());+}diff --git a/crates/feature_flags/src/outbound/posthog.rs b/crates/feature_flags/src/outbound/posthog.rsnew file mode 100644index 0000000000..6fcd907b46--- /dev/null+++ b/crates/feature_flags/src/outbound/posthog.rs@@ -0,0 +1,171 @@+//! Strict remote evaluation through PostHog's V2 `/flags` endpoint.++use crate::{FeatureFlags, FlagSnapshot, FlagValue};+use macro_user_id::user_id::MacroUserIdStr;+use reqwest::{Client, Url};+use rootcause::Report;+use serde::Deserialize;+use std::{collections::HashMap, time::Duration};++#[cfg(test)]+mod test;++/// Remote loader with one reusable HTTP connection pool.+///+/// Construct once per service and clone to share the pool. Each load makes one+/// request; snapshot reads never make requests or record exposure events.+#[derive(Clone)]+pub struct PostHogFeatureFlags {+ client: Client,+ endpoint: Url,+ project_key: String,+ timeout: Duration,+}++impl PostHogFeatureFlags {+ /// Validate configuration and create the shared client.+ ///+ /// `host` must be an HTTP(S) origin (for example `https://us.i.posthog.com`),+ /// without credentials, a path, query, or fragment. Use the ingestion origin+ /// for the project's region. `project_key` must be nonblank and `timeout`+ /// nonzero. There is no disabled mode: missing configuration is an error.+ /// Redirects and automatic retries are disabled. The timeout bounds the+ /// entire load, including reading the response body.+ pub fn new(host: &str, project_key: String, timeout: Duration) -> Result<Self, Report> {+ let mut endpoint =+ Url::parse(host).map_err(|_| rootcause::report!("Invalid PostHog origin"))?;+ if !matches!(endpoint.scheme(), "https" | "http")+ || endpoint.host_str().is_none()+ || !endpoint.username().is_empty()+ || endpoint.password().is_some()+ || endpoint.path() != "/"+ || endpoint.query().is_some()+ || endpoint.fragment().is_some()+ {+ return Err(rootcause::report!("PostHog host must be an HTTP(S) origin"));+ }+ if project_key.trim().is_empty() || project_key.trim() != project_key {+ return Err(rootcause::report!(+ "PostHog project key must be nonblank without surrounding whitespace"+ ));+ }+ if timeout.is_zero() || std::time::Instant::now().checked_add(timeout).is_none() {+ return Err(rootcause::report!(+ "PostHog timeout must be positive and finite"+ ));+ }+ endpoint.set_path("/flags/");+ endpoint.set_query(Some("v=2"));+ let client = Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .retry(reqwest::retry::never())+ .timeout(timeout)+ .build()+ .map_err(|error| LoadError::Transport(error.without_url()))?;+ Ok(Self {+ client,+ endpoint,+ project_key,+ timeout,+ })+ }++ async fn evaluate(&self, user_id: &MacroUserIdStr<'_>) -> Result<FlagSnapshot, Report> {+ let response = self+ .client+ .post(self.endpoint.clone())+ .json(&serde_json::json!({+ "api_key": self.project_key,+ "distinct_id": user_id.as_ref(),+ "evaluation_runtime": "server",+ "geoip_disable": true,+ }))+ .send()+ .await+ .map_err(|error| LoadError::Transport(error.without_url()))?;+ if !response.status().is_success() {+ return Err(LoadError::HttpStatus(response.status().as_u16()).into());+ }+ // Never retain a decode error: serde's diagnostics may contain values+ // from the provider response, including user properties or flag keys.+ let body = response+ .bytes()+ .await+ .map_err(|error| LoadError::Transport(error.without_url()))?;+ let response: FlagsResponse =+ serde_json::from_slice(&body).map_err(|_| LoadError::MalformedResponse)?;+ if response.errors_while_computing_flags+ || !response.quota_limited.is_empty()+ || response.error.is_some()+ || !response.errors.is_empty()+ {+ return Err(LoadError::IncompleteEvaluation.into());+ }+ let flags = response+ .flags+ .into_iter()+ .map(|(key, flag)| {+ if flag.failed {+ return Err(LoadError::IncompleteEvaluation);+ }+ if key.is_empty()+ || key != flag.key+ || flag.variant.as_ref().is_some_and(String::is_empty)+ {+ return Err(LoadError::MalformedResponse);+ }+ let value = match (flag.enabled, flag.variant) {+ (false, _) => FlagValue::Boolean(false),+ (true, Some(variant)) => FlagValue::Variant(variant),+ (true, None) => FlagValue::Boolean(true),+ };+ Ok((key, value))+ })+ .collect::<Result<Vec<_>, _>>()?;+ Ok(FlagSnapshot::new(flags))+ }+}++impl FeatureFlags for PostHogFeatureFlags {+ async fn load(&self, user_id: &MacroUserIdStr<'_>) -> Result<FlagSnapshot, Report> {+ tokio::time::timeout(self.timeout, self.evaluate(user_id))+ .await+ .map_err(|_| LoadError::Timeout)?+ }+}++#[derive(Debug, thiserror::Error)]+enum LoadError {+ #[error("PostHog transport failed")]+ Transport(#[source] reqwest::Error),+ #[error("PostHog returned HTTP status {0}")]+ HttpStatus(u16),+ #[error("PostHog returned a malformed flags response")]+ MalformedResponse,+ #[error("PostHog could not completely evaluate feature flags")]+ IncompleteEvaluation,+ #[error("PostHog flag load timed out")]+ Timeout,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct FlagsResponse {+ // Required: neither a missing map nor missing health status is success.+ flags: HashMap<String, Flag>,+ errors_while_computing_flags: bool,+ #[serde(default)]+ quota_limited: Vec<String>,+ error: Option<serde_json::Value>,+ #[serde(default)]+ errors: Vec<serde_json::Value>,+}++#[derive(Deserialize)]+struct Flag {+ key: String,+ enabled: bool,+ variant: Option<String>,+ #[serde(default)]+ failed: bool,+}diff --git a/crates/feature_flags/src/outbound/posthog/test.rs b/crates/feature_flags/src/outbound/posthog/test.rsnew file mode 100644index 0000000000..aacf97c123--- /dev/null+++ b/crates/feature_flags/src/outbound/posthog/test.rs@@ -0,0 +1,244 @@+use super::*;+use serde_json::{Value, json};+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{body_partial_json, method, path, query_param},+};++const PROJECT_KEY: &str = "test-project-key";+const TIMEOUT: Duration = Duration::from_secs(2);++fn loader(server: &MockServer) -> PostHogFeatureFlags {+ PostHogFeatureFlags::new(&server.uri(), PROJECT_KEY.into(), TIMEOUT).unwrap()+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn healthy(flags: Value) -> Value {+ json!({"flags": flags, "errorsWhileComputingFlags": false, "requestId": "test-request"})+}++#[tokio::test]+async fn loads_once_per_user_and_reads_a_stable_snapshot() {+ let server = MockServer::start().await;+ let alice = user();+ let bob = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ Mock::given(method("POST"))+ .and(path("/flags/"))+ .and(query_param("v", "2"))+ .and(body_partial_json(json!({+ "api_key": PROJECT_KEY, "distinct_id": alice.as_ref(),+ "evaluation_runtime": "server", "geoip_disable": true,+ })))+ .respond_with(ResponseTemplate::new(200).set_body_json(healthy(json!({+ "code": {"key": "code", "enabled": true},+ "off": {"key": "off", "enabled": false, "variant": "old"},+ "layout": {"key": "layout", "enabled": true, "variant": "compact"}+ }))))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(body_partial_json(json!({"distinct_id": bob.as_ref()})))+ .respond_with(ResponseTemplate::new(200).set_body_json(healthy(json!({+ "code": {"key": "code", "enabled": false}+ }))))+ .expect(1)+ .mount(&server)+ .await;++ let provider = loader(&server);+ let snapshot = provider.load(&alice).await.unwrap();+ let bob_snapshot = provider.clone().load(&bob).await.unwrap();+ assert!(!bob_snapshot.is_enabled("code"));+ for _ in 0..3 {+ assert!(snapshot.is_enabled("code"));+ assert!(snapshot.is_enabled("layout"));+ assert_eq!(snapshot.variant("layout"), Some("compact"));+ assert_eq!(snapshot.get("off"), Some(&FlagValue::Boolean(false)));+ assert_eq!(snapshot.variant("off"), None);+ assert!(!snapshot.is_enabled("missing"));+ assert_eq!(snapshot.get("missing"), None);+ }+ assert_eq!(server.received_requests().await.unwrap().len(), 2);+}++#[tokio::test]+async fn accepts_an_explicitly_healthy_empty_snapshot() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(healthy(json!({}))))+ .expect(1)+ .mount(&server)+ .await;+ assert_eq!(+ loader(&server).load(&user()).await.unwrap(),+ FlagSnapshot::default()+ );+}++#[tokio::test]+async fn rejects_incomplete_quota_and_provider_errors() {+ let responses = [+ json!({"flags": {}, "errorsWhileComputingFlags": true}),+ json!({"flags": {"code": {"key": "code", "enabled": true}}, "errorsWhileComputingFlags": true}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "quotaLimited": ["feature_flags"]}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "quotaLimited": ["database"]}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "error": "sensitive-value"}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "errors": ["sensitive-value"]}),+ healthy(json!({"code": {"key": "code", "enabled": false, "failed": true}})),+ ];+ for response in responses {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(response))+ .expect(1)+ .mount(&server)+ .await;+ let error = loader(&server).load(&user()).await.unwrap_err();+ assert!(matches!(+ error.downcast_current_context::<LoadError>(),+ Some(LoadError::IncompleteEvaluation)+ ));+ assert!(!format!("{error:?}").contains("sensitive-value"));+ }+}++#[tokio::test]+async fn rejects_malformed_success_without_leaking_body_values() {+ let responses = [+ json!({}),+ json!({"flags": {}}),+ json!({"errorsWhileComputingFlags": false}),+ json!({"flags": null, "errorsWhileComputingFlags": false}),+ json!({"flags": {}, "errorsWhileComputingFlags": null}),+ json!({"flags": {}, "errorsWhileComputingFlags": "sensitive-value"}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "quotaLimited": true}),+ json!({"flags": {}, "errorsWhileComputingFlags": false, "quotaLimited": null}),+ healthy(json!({"code": {"enabled": true}})),+ healthy(json!({"code": {"key": "code"}})),+ healthy(json!({"code": {"key": "different", "enabled": true}})),+ healthy(json!({"code": {"key": "code", "enabled": "sensitive-value"}})),+ healthy(json!({"code": {"key": "code", "enabled": true, "variant": 1}})),+ healthy(json!({"code": {"key": "code", "enabled": true, "variant": ""}})),+ healthy(json!({"code": {"key": "code", "enabled": false, "failed": null}})),+ ];+ for response in responses {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(response))+ .expect(1)+ .mount(&server)+ .await;+ let error = loader(&server).load(&user()).await.unwrap_err();+ assert!(matches!(+ error.downcast_current_context::<LoadError>(),+ Some(LoadError::MalformedResponse)+ ));+ assert!(!format!("{error:?}").contains("sensitive-value"));+ }+}++#[tokio::test]+async fn rejects_http_errors_redirects_and_non_json_without_retrying() {+ for status in [204, 302, 401, 429, 500, 502, 200] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(+ ResponseTemplate::new(status)+ .insert_header("Location", format!("{}/redirected", server.uri()))+ .set_body_string("sensitive-value"),+ )+ .expect(1)+ .mount(&server)+ .await;+ let error = loader(&server).load(&user()).await.unwrap_err();+ let diagnostic = format!("{error:?}");+ assert!(!diagnostic.contains("sensitive-value"));+ assert!(!diagnostic.contains(PROJECT_KEY));+ assert!(!diagnostic.contains(user().as_ref()));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+ }+}++#[tokio::test]+async fn total_timeout_returns_error() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(healthy(json!({})))+ .set_delay(Duration::from_secs(2)),+ )+ .expect(1)+ .mount(&server)+ .await;+ let provider =+ PostHogFeatureFlags::new(&server.uri(), PROJECT_KEY.into(), Duration::from_millis(50))+ .unwrap();+ let result = tokio::time::timeout(Duration::from_secs(1), provider.load(&user())).await;+ assert!(result.expect("load must honor its own deadline").is_err());+}++#[test]+fn invalid_or_disabled_configuration_fails_at_construction() {+ for key in ["", " ", " key", "key "] {+ assert!(PostHogFeatureFlags::new("https://us.i.posthog.com", key.into(), TIMEOUT).is_err());+ }+ for host in [+ "not a url",+ "ftp://posthog.com",+ "https://user:[email protected]",+ "https://posthog.com/path",+ "https://posthog.com/?key=secret",+ "https://posthog.com/#fragment",+ ] {+ assert!(PostHogFeatureFlags::new(host, PROJECT_KEY.into(), TIMEOUT).is_err());+ }+ assert!(+ PostHogFeatureFlags::new(+ "https://us.i.posthog.com",+ PROJECT_KEY.into(),+ Duration::ZERO+ )+ .is_err()+ );+}++#[tokio::test]+async fn deadline_also_bounds_a_stalled_response_body() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let host = format!("http://{}", listener.local_addr().unwrap());+ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = [0; 1];+ socket.read_exact(&mut request).await.unwrap();+ socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nContent-Type: application/json\r\n\r\n{").await.unwrap();+ tokio::time::sleep(Duration::from_secs(2)).await;+ });+ let provider =+ PostHogFeatureFlags::new(&host, PROJECT_KEY.into(), Duration::from_millis(100)).unwrap();+ let result = tokio::time::timeout(Duration::from_secs(1), provider.load(&user())).await;+ server.abort();+ assert!(+ result+ .expect("body read must honor the load deadline")+ .is_err()+ );+}++#[tokio::test]+async fn connection_failure_is_not_a_missing_flag() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let host = format!("http://{}", listener.local_addr().unwrap());+ drop(listener);+ let provider = PostHogFeatureFlags::new(&host, PROJECT_KEY.into(), TIMEOUT).unwrap();+ let error = provider.load(&user()).await.unwrap_err();+ assert!(matches!(+ error.downcast_current_context::<LoadError>(),+ Some(LoadError::Transport(_))+ ));+ assert!(!format!("{error:?}").contains(&host));+}