### Run Quick Start Example Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/examples/README.md Navigates to the examples directory and executes the quick_start.rb script to demonstrate basic flag evaluation. ```bash cd examples ruby quick_start.rb ``` -------------------------------- ### Install Confidence OpenFeature Provider for Go Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Install the provider using go get and update dependencies with go mod tidy. ```bash go get github.com/spotify/confidence-resolver/openfeature-provider/go go mod tidy ``` -------------------------------- ### Install Debug Library Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Install the 'debug' library, which the Confidence provider uses for logging, using Yarn. ```bash yarn add debug ``` -------------------------------- ### Install Confidence Provider and React Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README-REACT.md Install the necessary packages for the Confidence OpenFeature server provider and React integration using Yarn. ```bash yarn add @spotify-confidence/openfeature-server-provider-local react ``` -------------------------------- ### Quick Start: Initialize and Use Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Initialize the OpenFeature Local Resolve Provider with your client secret and register it with the OpenFeature API. Then, get a client and evaluate a boolean flag with a custom context. ```java import com.spotify.confidence.sdk.OpenFeatureLocalResolveProvider; import dev.openfeature.sdk.OpenFeatureAPI; import dev.openfeature.sdk.Client; import dev.openfeature.sdk.MutableContext; // Create and register the provider OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider("your-client-secret"); // Get from Confidence dashboard OpenFeatureAPI.getInstance().setProviderAndWait(provider); // Important: use setProviderAndWait() // Get a client Client client = OpenFeatureAPI.getInstance().getClient(); // Create evaluation context with user attributes for targeting MutableContext ctx = new MutableContext("user-123"); ctx.add("country", "US"); ctx.add("plan", "premium"); // Evaluate a flag Boolean enabled = client.getBooleanValue("test-flag.enabled", false, ctx); System.out.println("Flag value: " + enabled); // Don't forget to shutdown when your application exits (see Shutdown section) ``` -------------------------------- ### Build Project with Docker Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Build, test, and lint the entire project using Docker for a reproducible environment. No prior setup is needed. ```bash docker build . # Build, test, lint everything ``` -------------------------------- ### Run the Demo Application Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/demo/README.md Execute the main Go application to start the demo. The demo evaluates flags concurrently to test performance and state synchronization. ```bash go run main.go ``` -------------------------------- ### Install Confidence OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/python/README.md Install the provider using pip. Ensure you have Python 3.10+ and OpenFeature SDK 0.8.0+. ```bash pip install confidence-openfeature-provider ``` -------------------------------- ### Run Rails Example Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/examples/README.md Executes the rails_example.rb script, demonstrating integration within a Rails application. Includes variations for rbenv and direct client secret provision. ```bash cd examples ruby rails_example.rb ``` ```bash BUNDLE_USER_CACHE=.bundle/user-cache rbenv exec bundle install && rbenv exec ruby rails_example.rb ``` ```bash export CONFIDENCE_CLIENT_SECRET=your_client_secret_here ruby rails_example.rb ``` -------------------------------- ### Install Confidence OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Install the Confidence OpenFeature server provider for JavaScript using yarn. Optionally, install the 'debug' package to enable logging. ```bash yarn add @spotify-confidence/openfeature-server-provider-local # Optional: enable logs by installing the peer dependency yarn add debug ``` -------------------------------- ### Quick Start: Node.js Integration Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Integrate the Confidence OpenFeature server provider in a Node.js application. This example shows how to initialize the provider, set it with OpenFeature, and evaluate flags with custom context. Ensure to wait for the provider to be ready before evaluating flags. ```typescript import { OpenFeature } from '@openfeature/server-sdk'; import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local'; const provider = createConfidenceServerProvider({ flagClientSecret: process.env.CONFIDENCE_FLAG_CLIENT_SECRET!, // initializeTimeout?: number // stateUpdateInterval?: number // flushInterval?: number // fetch?: typeof fetch (Node <18 or custom transport) }); // Wait for the provider to be ready (fetches initial resolver state) await OpenFeature.setProviderAndWait(provider); const client = OpenFeature.getClient(); // Create evaluation context with user attributes for targeting const context = { targetingKey: 'user-123', country: 'US', plan: 'premium', }; // Evaluate a boolean flag const enabled = await client.getBooleanValue('test-flag.enabled', false, context); console.log('Flag value:', enabled); // Evaluate a nested value from an object flag using dot-path // e.g. flag key "experiments" with payload { groupA: { ratio: 0.5 } } const ratio = await client.getNumberValue('experiments.groupA.ratio', 0, context); // On shutdown, flush any pending logs await provider.onClose(); ``` -------------------------------- ### Run Advanced Demo Example Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/examples/README.md Executes the advanced_demo.rb script, which demonstrates real-world use cases and advanced patterns such as feature rollout and A/B testing. ```bash cd examples ruby advanced_demo.rb ``` -------------------------------- ### Build and Test Ruby OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/CLAUDE.md Commands to build, test, lint, and install the Ruby OpenFeature provider using make. ```bash make build # bundle exec rake build make test # bundle exec rake spec make lint # bundle exec rake standard make install # bundle install ``` -------------------------------- ### Install Dependencies with Bundler Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/examples/README.md Installs project dependencies using Bundler. If using rbenv, a specific command is provided to ensure correct execution. ```bash bundle install ``` ```bash BUNDLE_USER_CACHE=.bundle/user-cache rbenv exec bundle install ``` -------------------------------- ### Ruby on Rails Integration Example Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/README.md This example demonstrates how to integrate the Confidence OpenFeature provider into a Ruby on Rails application. It includes configuration within an initializer and a helper method in the ApplicationController to fetch boolean flag values. ```ruby # config/initializers/confidence.rb require "openfeature/sdk" require "confidence/openfeature" OpenFeature::SDK.configure do |config| api_client = Confidence::OpenFeature::APIClient.new( client_secret: ENV['CONFIDENCE_CLIENT_SECRET'], region: Confidence::OpenFeature::Region::EU ) config.provider = Confidence::OpenFeature::Provider.new(api_client: api_client) end # app/controllers/application_controller.rb class ApplicationController < ActionController::Base def feature_enabled?(flag_key, default: false) client = OpenFeature::SDK.build_client(name: "rails-app") ctx = OpenFeature::SDK::EvaluationContext.new( targeting_key: current_user&.id || session.id, attributes: {user: {country: request.location&.country_code}} ) client.fetch_boolean_value( flag_key: flag_key, default_value: default, evaluation_context: ctx ) end end ``` -------------------------------- ### Quick Start: Initialize and Use OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Initialize the Confidence provider with your client secret, set it in the OpenFeature SDK, and evaluate a boolean flag with a specific evaluation context. ```go package main import ( "context" "log" "github.com/open-feature/go-sdk/openfeature" "github.com/spotify/confidence-resolver/openfeature-provider/go/confidence" ) func main() { ctx := context.Background() // Create provider with your client secret provider, err := confidence.NewProvider(ctx, confidence.ProviderConfig{ ClientSecret: "your-client-secret", // Get from Confidence dashboard }) if err != nil { log.Fatalf("Failed to create provider: %v", err) } // Set the provider and wait for initialization openfeature.SetProviderAndWait(provider) // Get a client client := openfeature.NewClient("my-app") // Create evaluation context with user attributes for targeting evalCtx := openfeature.NewEvaluationContext("user-123", map[string]interface{}{ "country": "US", "plan": "premium", }) // Evaluate a flag value, err := client.BooleanValue(ctx, "test-flag.enabled", false, evalCtx) if err != nil { log.Printf("Flag evaluation failed, using default: %v", err) } log.Printf("Flag value: %v", value) } ``` -------------------------------- ### Quick Start: Initialize and Use OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/rust/README.md Initialize the Confidence provider with your client secret and set it on the OpenFeature singleton. Then, create a client to evaluate feature flags with custom context. ```rust use open_feature::{EvaluationContext, OpenFeature}; use spotify_confidence_openfeature_provider_local::{ConfidenceProvider, ProviderOptions}; #[tokio::main] async fn main() -> Result<(), Box> { // Create provider options with your client secret let options = ProviderOptions::new("your-client-secret"); // Get from Confidence dashboard // Create the Confidence provider let provider = ConfidenceProvider::new(options)?; // Set the provider on the OpenFeature singleton OpenFeature::singleton_mut() .await .set_provider(provider) .await; // Create an OpenFeature client let client = OpenFeature::singleton().await.create_client(); // Create evaluation context with user attributes for targeting let context = EvaluationContext::default() .with_targeting_key("user-123") .with_custom_field("country", "US") .with_custom_field("plan", "premium"); // Evaluate a boolean flag let enabled = client .get_bool_value("test-flag.enabled", Some(&context), None) .await .unwrap_or(false); println!("Flag value: {}", enabled); Ok(()) } ``` -------------------------------- ### In-Memory MaterializationStore Usage Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/STICKY_RESOLVE.md Example of initializing an OpenFeature provider with an in-memory MaterializationStore. This is suitable for testing and development but not for production. ```java MaterializationStore store = new InMemoryMaterializationStore(); OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider( clientSecret, store ); ``` -------------------------------- ### Wrap Component Tree with ConfidenceProvider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README-REACT.md Ensure your component tree is wrapped with `ConfidenceProvider` to make `useFlag` and `useFlagDetails` available. This example shows a basic setup where `MyComponent` can access flag evaluations. ```tsx {/* useFlag works here */} ``` -------------------------------- ### Build WASM Guest Source: https://github.com/spotify/confidence-resolver/blob/main/wasm/rust-guest/CLAUDE.md Builds the Rust guest crate for WebAssembly. Ensure the `wasm32-unknown-unknown` target is installed. ```bash make build # cargo build --target wasm32-unknown-unknown --profile wasm ``` -------------------------------- ### Build and Test Commands for Python OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/python/CLAUDE.md A collection of make commands to build the WASM binary, set up the Python environment, run tests, perform linting, format code, generate protobuf files, and install the provider with development dependencies. ```bash make build # build WASM + create venv + install + python -m build make test # pytest tests/ (excludes e2e) make test-e2e # pytest e2e tests make lint # ruff check + ruff format --check + mypy make format # ruff check --fix + ruff format make proto # generate protobuf Python files from ../proto/ make install # create venv + pip install -e ".[dev]" ``` -------------------------------- ### Basic FlagResolverService Setup Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Set up the FlagResolverService to proxy flag resolution requests from client SDKs through your backend. This requires initializing the provider and then creating the service instance. ```java import com.spotify.confidence.sdk.OpenFeatureLocalResolveProvider; import com.spotify.confidence.sdk.FlagResolverService; import dev.openfeature.sdk.OpenFeatureAPI; // Create and initialize the provider OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider("your-client-secret"); // If you're not using OpenFeature, don't forget to call provider.initialize() OpenFeatureAPI.getInstance().setProviderAndWait(provider); // Create the HTTP service FlagResolverService flagResolver = new FlagResolverService(provider); ``` -------------------------------- ### Quick Start: Initialize and Use Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/python/README.md Initialize the ConfidenceProvider with your client secret, register it with the OpenFeature API, and then evaluate a boolean flag using a defined evaluation context. ```python from openfeature import api from openfeature.evaluation_context import EvaluationContext from confidence import ConfidenceProvider # Create and register the provider provider = ConfidenceProvider(client_secret="your-client-secret") api.set_provider(provider) # Get a client client = api.get_client() # Create evaluation context with user attributes for targeting context = EvaluationContext( targeting_key="user-123", attributes={ "country": "US", "plan": "premium", } ) # Evaluate a flag enabled = client.get_boolean_value("test-flag.enabled", default_value=False, evaluation_context=context) print(f"Flag value: {enabled}") # Don't forget to shutdown when your application exits (see Shutdown section) ``` -------------------------------- ### Build and Test Commands Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/AGENTS.md Standard make commands for building the WASM module, installing dependencies, generating proto files, building the TypeScript project, and running tests. ```bash make build # build WASM (if needed) + yarn install + proto:gen + tsdown build ``` ```bash make test # format:check + typecheck + vitest (excludes *.e2e.test.ts) ``` ```bash make test-e2e # run E2E tests (requires credentials) ``` -------------------------------- ### GET /v1/state:etag Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/CLAUDE.md Returns the deployment state ETag and the resolver version. ```APIDOC ## GET /v1/state:etag ### Description Returns the deployment state ETag and the resolver version. ### Method GET ### Endpoint /v1/state:etag ### Response #### Success Response (200) - **etag** (string) - The ETag of the current deployment state. - **resolver_version** (string) - The version of the confidence resolver. ``` -------------------------------- ### Custom Channel Factory for Testing Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Configure a custom channel factory for testing with an in-process server. This example demonstrates how to create a mock factory for unit testing. ```java import com.spotify.confidence.sdk.LocalProviderConfig; import com.spotify.confidence.sdk.ChannelFactory; // Example: Custom channel factory for testing with in-process server ChannelFactory mockFactory = (target, interceptors) -> InProcessChannelBuilder.forName("test-server") .usePlaintext() .intercept(interceptors.toArray(new ClientInterceptor[0])) .build(); LocalProviderConfig config = new LocalProviderConfig(mockFactory); OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider(config, "client-secret"); ``` -------------------------------- ### ConfidenceProvider Server Component Setup Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README-REACT.md Configures the `ConfidenceProvider` for server components to resolve flags and provide them via React Context. ```tsx import { ConfidenceProvider } from '@spotify-confidence/openfeature-server-provider-local/react-server'; {children} ; ``` -------------------------------- ### Enabling Debug Logging for Confidence Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/MIGRATION.md Shows how to enable detailed debug logging for the Confidence resolver by installing the 'debug' package and setting the DEBUG environment variable. This is useful for troubleshooting state fetches and flag evaluations. ```bash yarn add debug DEBUG=cnfd:* node your-app.js ``` -------------------------------- ### JavaScript Example: Defaulting Feature to Off Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/INTEGRATION_GUIDE.md Demonstrates a safe default value for a feature flag, ensuring the feature is opt-in by default. This is a best practice for risky features. ```javascript // Default: false - feature is opt-in for safety const enabled = getFlag("new-payment-flow", false) ``` -------------------------------- ### Enable Remote Materialization Store Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Enable the built-in remote materialization store for quick setup without managing storage infrastructure. This is suitable for prototyping or lower-volume applications where network latency is acceptable. The provider automatically handles gRPC connection and authentication. ```go import ( "context" "github.com/open-feature/go-sdk/openfeature" "github.com/spotify/confidence-resolver/openfeature-provider/go/confidence" ) func main() { ctx := context.Background() // Enable remote materialization store provider, err := confidence.NewProvider(ctx, confidence.ProviderConfig{ ClientSecret: "your-client-secret", UseRemoteMaterializationStore: true, }) if err != nil { log.Fatalf("Failed to create provider: %v", err) } openfeature.SetProviderAndWait(provider) // ... } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/CLAUDE.md Standard make commands for building, testing, linting, and generating protobuf files for the Go OpenFeature provider. ```bash make build make test make lint make proto ``` -------------------------------- ### Build Project with Makefile Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Build, test, and lint the project using the Makefile. This is an alternative to using Docker for building. ```bash make # Same, using Makefile ``` -------------------------------- ### Run Full Demo App Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/examples/README.md Executes the demo_app.rb script, showcasing comprehensive provider features. Allows passing the client secret as an argument or setting the region. ```bash cd examples ruby demo_app.rb ``` ```bash ruby demo_app.rb your_client_secret_here ``` ```bash export CONFIDENCE_REGION=US # or EU (default) ruby demo_app.rb ``` -------------------------------- ### Extract WASM from Docker Source: https://github.com/spotify/confidence-resolver/blob/main/CLAUDE.md Extracts the confidence resolver WebAssembly binary from a Docker image. This method does not require a local Rust installation. ```bash docker build --target wasm-rust-guest.artifact -o wasm . # produces: wasm/confidence_resolver.wasm ``` -------------------------------- ### Build Docker Image Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/deployer/README.md Build the Docker image for the deployer from the root of the repository. Replace with your desired image name. ```bash docker build --target confidence-cloudflare-resolver.deployer -t . ``` -------------------------------- ### Run Go Benchmark with Docker Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Execute the Go benchmark using Docker. This process streams all logs and cleans up containers afterward. ```bash make go-bench ``` -------------------------------- ### Inspect WASM Exports Source: https://github.com/spotify/confidence-resolver/blob/main/CLAUDE.md Inspects the export table of a WebAssembly binary using wasm-objdump. Requires the WebAssembly Binary Toolkit (wabt) to be installed. ```bash wasm-objdump -j Export -x wasm/confidence_resolver.wasm ``` -------------------------------- ### Configure Provider with LocalProviderConfig Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Configure the OpenFeature Local Resolve Provider using LocalProviderConfig.builder(), for example, to set the resolver pool size for concurrency. ```java LocalProviderConfig config = LocalProviderConfig.builder() .resolverPoolSize(4) // Number of WASM resolver instances (default: 2). Increase for higher concurrency. .build(); OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider(config, "your-client-secret"); ``` -------------------------------- ### Node.js Import Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Import from './node' for traditional Node.js environments. This method uses fs.readFile() to load WASM from the installed package. The WASM path can be customized. ```typescript import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local/node'; ``` ```typescript const provider = createConfidenceServerProvider({ flagClientSecret: '...', wasmPath: '/custom/path/to/confidence_resolver.wasm', }); ``` -------------------------------- ### Go: Initialize Provider with Initialization Timeout Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Initialize the Confidence provider with a context that includes a timeout to prevent indefinite blocking. ```go // During initialization with timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() provider, err := confidence.NewProvider(ctx, confidence.ProviderConfig{ ClientSecret: "your-client-secret", }) if err != nil { log.Fatalf("Provider initialization failed: %v", err) } ``` -------------------------------- ### FlagResolverService with Context Decoration Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Configure the FlagResolverService to add server-side context to requests before resolution. This example demonstrates setting the targeting key from an 'X-User-Id' header. ```java import com.spotify.confidence.sdk.OpenFeatureLocalResolveProvider; import com.spotify.confidence.sdk.FlagResolverService; import com.spotify.confidence.sdk.ContextDecorator; import dev.openfeature.sdk.ImmutableContext; import java.util.List; // Assuming 'provider' is already initialized OpenFeatureLocalResolveProvider provider = new OpenFeatureLocalResolveProvider("your-client-secret"); FlagResolverService flagResolver = new FlagResolverService(provider, ContextDecorator.sync((ctx, req) -> { // Set targeting key from upstream auth middleware header List userIds = req.headers().get("X-User-Id"); if (userIds != null && !userIds.isEmpty()) { return ctx.merge(new ImmutableContext(userIds.get(0))); } return ctx; })); ``` -------------------------------- ### Build Project with Docker and Test Environment Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Build the project with Docker, including the JavaScript/TypeScript end-to-end tests. Requires Confidence credentials to be provided as a Docker secret. ```bash docker build \ --secret id=js_e2e_test_env,src=openfeature-provider/js/.env.test \ . ``` -------------------------------- ### Build and Test Commands Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/CLAUDE.md Provides essential make commands for building the WASM binary, packaging the Maven project, running unit tests, and executing end-to-end integration tests. ```bash make build # build WASM (if needed) + mvn package -DskipTests make test # build + mvn test (excludes *E2ETest) make test-e2e # build + mvn verify (integration tests against shaded JAR) ``` -------------------------------- ### Inspect WASM Host Imports Source: https://github.com/spotify/confidence-resolver/blob/main/CLAUDE.md Inspects the host import table of a WebAssembly binary using wasm-objdump. Requires the WebAssembly Binary Toolkit (wabt) to be installed. ```bash wasm-objdump -j Import -x wasm/confidence_resolver.wasm ``` -------------------------------- ### Initialize and Resolve Flags with Immediate Apply Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Initializes the Confidence provider and resolves multiple flags, applying exposures immediately. Use this for standard flag resolution where exposure logging should happen on evaluation. ```go provider, _ := confidence.NewProvider(ctx, confidence.ProviderConfig{ ClientSecret: "your-client-secret", }) openfeature.SetProviderAndWait(provider) evalCtx := openfeature.FlattenedContext{ "targeting_key": "user-123", "country": "US", } // Resolve one or more flags at once with apply=true to record exposures immediately. // Pass an empty slice to resolve all flags available to the client. resp, err := provider.Resolve(ctx, evalCtx, []string{"flag-a", "flag-b"}, true) if err != nil { log.Fatal(err) } for _, f := range resp.ResolvedFlags { log.Printf("%s → %s", f.Flag, f.Variant) } ``` -------------------------------- ### Fail Fast vs. Discovery Mode Behavior Source: https://github.com/spotify/confidence-resolver/blob/main/STICKY_ASSIGNMENTS.md Illustrates the immediate return behavior of fail-fast mode versus the comprehensive collection in discovery mode when missing materializations are encountered. ```text Flag A: ✅ Has materialization → Process normally Flag B: ❌ Missing materialization + fail_fast=true → Return immediately with [Flag B missing item] Flag C: (Not processed due to fail_fast) ``` -------------------------------- ### JavaScript Example: Defaulting Timeout Value Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/INTEGRATION_GUIDE.md Shows how to set a conservative default value for a timeout configuration. This ensures a predictable behavior even if the flag evaluation fails. ```javascript // Default: 1000ms - conservative timeout const timeout = getFlag("api-timeout", 1000) ``` -------------------------------- ### Check Code Formatting with Maven Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/CONTRIBUTING.md Run this command to check if the code adheres to the project's formatting standards using the Spotify fmt-maven-plugin. ```bash mvn fmt:check ``` -------------------------------- ### Run Deployer with Credentials Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/deployer/README.md Run the deployer Docker container, providing your Cloudflare API token and Confidence client secret as environment variables. The deployer automatically detects the account ID, creates necessary queues, fetches resolver state, and optimizes deployments by skipping unnecessary re-deployments. ```bash docker run -it \ -e CLOUDFLARE_API_TOKEN='your-cloudflare-api-token' \ -e CONFIDENCE_CLIENT_SECRET='your-confidence-client-secret' \ ghcr.io/spotify/confidence-cloudflare-deployer:latest ``` -------------------------------- ### getFlagDetails (Server) Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README-REACT.md Get full flag details in a server component. Exposure is logged immediately upon evaluation. Returns the flag's value, variant, and reason. ```APIDOC ## getFlagDetails (Server) ### Description Get full flag details in a server component. Logs exposure immediately. ### Parameters #### Required Parameters - **flagKey** (string) - The flag key (supports dot notation). - **defaultValue** (T) - Default value if flag is not found. - **context** (EvaluationContext) - User/session context for flag evaluation. #### Optional Parameters - **providerName** (string) - Named provider if not using the default. ### Response - **value** - The evaluated flag value. - **variant** - The flag variant. - **reason** - The reason for the flag evaluation. ``` -------------------------------- ### Get Detailed Flag Evaluation Results Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/rust/README.md Use `get_bool_details()` to retrieve detailed information about a flag evaluation, including value, variant, and reason, or an error if evaluation fails. ```rust // For detailed error information, use get_bool_details() let details = client .get_bool_details("my-flag.enabled", Some(&context), None) .await; match details { Ok(result) => { println!("Value: {}", result.value); println!("Variant: {:?}", result.variant); println!("Reason: {:?}", result.reason); } Err(e) => { eprintln!("Flag evaluation error: {:?}", e); } } ``` -------------------------------- ### Auto-Format Code with Maven Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/CONTRIBUTING.md Execute this command to automatically format the code according to the project's standards using the Spotify fmt-maven-plugin. ```bash mvn fmt:format ``` -------------------------------- ### Build and Test Commands for Rust Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/rust/CLAUDE.md Common commands for building, testing, and linting the Rust OpenFeature provider. These commands leverage Cargo for managing the Rust project. ```bash make build # cargo build make test # cargo test --lib make test-e2e # cargo test --test e2e make lint # cargo fmt --check + cargo clippy -- -D warnings ``` -------------------------------- ### Extend Wrangler Configuration with TOML Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/deployer/README.md Use WRANGLER_CONFIG_APPEND_FILE to include custom Cloudflare configurations like tail consumers or observability settings. Ensure the appended TOML file starts with a table header. ```toml [[tail_consumers]] service = "my-tail-worker" [observability.logs] enabled = true destinations = ["otel-gateway-logs"] head_sampling_rate = 1.0 ``` ```bash docker run -it \ -v "$PWD/wrangler-extra.toml:/tmp/wrangler-extra.toml:ro" \ -e CLOUDFLARE_API_TOKEN='your-cloudflare-api-token' \ -e CONFIDENCE_CLIENT_SECRET='your-confidence-client-secret' \ -e WRANGLER_CONFIG_APPEND_FILE='/tmp/wrangler-extra.toml' \ -e WRANGLER_DEPLOY_TAG='production-2026-05-05' \ -e WRANGLER_DEPLOY_MESSAGE='Deploy resolver state with tail worker logs' \ ghcr.io/spotify/confidence-cloudflare-deployer:latest ``` -------------------------------- ### Configure and Use Confidence OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/ruby/README.md This snippet shows how to configure the OpenFeature SDK with the Confidence provider, including setting up the API client with a client secret and region. It then demonstrates creating an OpenFeature client and fetching a boolean flag value with an evaluation context. ```ruby require "openfeature/sdk" require "confidence/openfeature" # Configure OpenFeature with Confidence provider OpenFeature::SDK.configure do |config| api_client = Confidence::OpenFeature::APIClient.new( client_secret: ENV['CONFIDENCE_CLIENT_SECRET'], # Get from Confidence dashboard region: Confidence::OpenFeature::Region::EU ) config.provider = Confidence::OpenFeature::Provider.new(api_client: api_client) end # Create a client open_feature_client = OpenFeature::SDK.build_client(name: "my-app") ctx = OpenFeature::SDK::EvaluationContext.new( targeting_key: "random", attributes: {user: {country: "SE"}} ) flag_value = open_feature_client.fetch_boolean_value( flag_key: "test-flag.boolean-key", default_value: false, evaluation_context: ctx ) print(flag_value) ``` -------------------------------- ### Go: Handle Flag Evaluation Errors with Default Fallback Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Demonstrates how the provider returns a default value on error and how to check for specific errors like FLAG_NOT_FOUND. ```go // The provider returns the default value on errors value, err := client.BooleanValue(ctx, "my-flag.enabled", false, evalCtx) if err != nil { // Log the error for debugging log.Printf("Flag evaluation failed, using default: %v", err) } // value will be 'false' if evaluation failed // For critical flags, you might want to check the error if err != nil && strings.Contains(err.Error(), "FLAG_NOT_FOUND") { log.Warn("Flag 'my-flag' not found in Confidence - check flag name") } ``` -------------------------------- ### Configure Provider Options Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/rust/README.md Instantiate `ProviderOptions` with a client secret and optionally configure initialization timeout, state poll interval, and remote materialization. ```rust use spotify_confidence_openfeature_provider_local::ProviderOptions; let options = ProviderOptions::new("your-client-secret") .with_initialize_timeout(10_000) // Max ms to wait for initial state fetch .with_state_poll_interval(30_000) // Interval in ms for polling state updates .with_confidence_materialization_store(); // Enable remote materialization ``` -------------------------------- ### Sync WASM for Go Provider Source: https://github.com/spotify/confidence-resolver/blob/main/CLAUDE.md Builds the WASM binary in Docker and copies it to the Go provider's asset directory. This command must be run after any changes to core Rust or WASM components to keep the Go provider's embedded WASM in sync. ```bash make sync-wasm-go ``` -------------------------------- ### Running Tests and Linting Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-resolver/CLAUDE.md Commands to execute the test suite and run clippy lints for the confidence_resolver crate. There is no 'build' target as it is a library. ```bash make test make lint ``` -------------------------------- ### Implement Custom Materialization Store Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/python/README.md Implement the MaterializationStore protocol for custom infrastructure management of materialization data. Your implementation must be thread-safe. ```python from confidence.materialization import ( MaterializationStore, ReadOp, ReadResult, VariantReadOp, VariantReadResult, InclusionReadOp, InclusionReadResult, VariantWriteOp, ) class MyMaterializationStore: """Custom materialization store implementation.""" def read(self, ops: list[ReadOp]) -> list[ReadResult]: results = [] for op in ops: if isinstance(op, VariantReadOp): # Look up sticky variant assignment variant = self._lookup_variant(op.unit, op.materialization, op.rule) results.append(VariantReadResult( unit=op.unit, materialization=op.materialization, rule=op.rule, variant=variant, # None if no assignment exists )) elif isinstance(op, InclusionReadOp): # Check segment inclusion included = self._check_inclusion(op.unit, op.materialization) results.append(InclusionReadResult( unit=op.unit, materialization=op.materialization, included=included, )) return results def write(self, ops: list[VariantWriteOp]) -> None: for op in ops: # Store sticky variant assignment self._store_variant(op.unit, op.materialization, op.rule, op.variant) ``` -------------------------------- ### Add Dependencies to Cargo.toml Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/rust/README.md Add the spotify-confidence-openfeature-provider-local and open-feature crates to your project's Cargo.toml file. ```toml [dependencies] spotify-confidence-openfeature-feature-provider-local = "0.1.0" open-feature = "0.2.7" ``` -------------------------------- ### Constructing New Local Confidence Server Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/MIGRATION.md Demonstrates the constructor for the new local Confidence OpenFeature provider, requiring 'flagClientSecret' and optionally accepting 'initializeTimeout', 'flushInterval', and a custom 'fetch' implementation. ```typescript import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local'; const provider = createConfidenceServerProvider({ flagClientSecret: 'your-client-secret', // this is the same client secret as before // initializeTimeout?: number // flushInterval?: number // fetch?: typeof fetch (Node <18 or custom transport) }); ``` -------------------------------- ### OPTIONS * Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/CLAUDE.md Handles CORS preflight requests for any path. ```APIDOC ## OPTIONS * ### Description Handles CORS preflight requests for any path. ### Method OPTIONS ### Endpoint * ### Response #### Success Response (200) - **Headers** - Includes necessary CORS headers like `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers`. ``` -------------------------------- ### Configure Confidence OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/demo/README.md Initialize the Confidence OpenFeature Provider with custom configuration, including client secret and poll intervals for state updates and log flushing. ```go provider, err := confidence.NewProvider(ctx, confidence.ProviderConfig{ ClientSecret: clientSecret, UseRemoteMaterializationStore: true, StatePollInterval: 30 * time.Second, // How often to fetch flag state (default: 10s) LogPollInterval: 2 * time.Minute, // How often to flush logs (default: 60s) }) ``` -------------------------------- ### Run Node.js Benchmark with Docker Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Execute the Node.js benchmark using Docker. This process streams all logs and cleans up containers afterward. ```bash make js-bench ``` -------------------------------- ### Initialize OpenFeature Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README-REACT.md Initialize the OpenFeature provider with the Confidence server provider before rendering your application. Ensure the flag client secret is set in the environment variables. ```typescript import { OpenFeature } from '@openfeature/server-sdk'; import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local'; const provider = createConfidenceServerProvider({ flagClientSecret: process.env.CONFIDENCE_FLAG_CLIENT_SECRET!, }); await OpenFeature.setProviderAndWait(provider); ``` -------------------------------- ### Build WASM Locally Source: https://github.com/spotify/confidence-resolver/blob/main/CLAUDE.md Builds the confidence resolver WebAssembly binary locally. Requires Rust and the wasm32-unknown-unknown target. ```bash make wasm/confidence_resolver.wasm ``` -------------------------------- ### Testing with Custom State Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/go/README.md Use this configuration for testing purposes only. It allows providing a custom StateProvider and FlagLogger to supply resolver state and control logging behavior. Ensure you provide both StateProvider and FlagLogger for this configuration. ```go // WARNING: This is for testing only. Do not use in production. provider, err := confidence.NewProviderForTest(ctx, confidence.ProviderTestConfig{ StateProvider: myCustomStateProvider, FlagLogger: myCustomFlagLogger, ClientSecret: "your-client-secret", Logger: myCustomLogger, // Optional: custom logger StatePollInterval: 30 * time.Second, // Optional: state polling interval LogPollInterval: 2 * time.Minute, // Optional: log flushing interval }, ) ``` -------------------------------- ### Build and Test Commands Source: https://github.com/spotify/confidence-resolver/blob/main/wasm-msg/CLAUDE.md Commands for linting and testing the wasm-msg crate. Note that tests are not yet implemented. ```bash make lint # cargo fmt --check + cargo clippy --lib --release -- -D warnings make test # no tests yet (all resolver logic tested in confidence-resolver) ``` -------------------------------- ### Constructing Old Confidence Server Provider Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/MIGRATION.md Shows the previous methods for constructing the Confidence server provider, either with a client secret and fetch implementation or with a pre-existing confidence instance. ```typescript const provider = createConfidenceServerProvider({ clientSecret: 'your-client-secret', fetchImplementation: fetch, timeout: 1000, }); // or const confidenceInstance: Confidence; // created separately const provider = createConfidenceServerProvider(confidenceInstance); ``` -------------------------------- ### Run Local Development Tools Source: https://github.com/spotify/confidence-resolver/blob/main/README.md Execute local development tasks such as running tests, linting, and building WASM artifacts using the Makefile. ```bash make test # Run tests ``` ```bash make lint # Run linting ``` ```bash make build # Build WASM ``` -------------------------------- ### JavaScript Client SDK Configuration Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/java/README.md Configure the JavaScript client SDK to connect to your OpenFeature backend. Ensure the 'resolveBaseUrl' and 'applyBaseUrl' point to your backend's flag endpoint. ```javascript import { Confidence } from '@spotify-confidence/sdk'; const confidence = Confidence.create({ clientSecret: 'not-used-but-required', resolveBaseUrl: 'https://your-backend.com/confidence-flags', applyBaseUrl: 'https://your-backend.com/confidence-flags', }); ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Format all project files using Prettier by running the 'yarn format' command. ```bash yarn format ``` -------------------------------- ### Build Confidence Cloudflare Resolver Source: https://github.com/spotify/confidence-resolver/blob/main/confidence-cloudflare-resolver/CLAUDE.md Builds the Confidence Cloudflare Resolver using make. ```bash make build ``` -------------------------------- ### Fetch Import Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/js/README.md Import from './fetch' for modern, standards-compliant environments like Deno, Bun, and browsers with compatible bundlers. This method uses fetch() with import.meta.url to load WASM. The WASM URL can be customized. ```typescript import { createConfidenceServerProvider } from '@spotify-confidence/openfeature-server-provider-local/fetch'; ``` ```typescript const provider = createConfidenceServerProvider({ flagClientSecret: '...', wasmUrl: '/assets/confidence_resolver.wasm', }); ``` -------------------------------- ### Configure Provider with Poll Intervals Source: https://github.com/spotify/confidence-resolver/blob/main/openfeature-provider/python/README.md Initialize the ConfidenceProvider with custom polling intervals for state updates and log flushing. ```python provider = ConfidenceProvider( client_secret="your-client-secret", state_poll_interval=30.0, # How often to poll for state updates (seconds) log_poll_interval=10.0, # How often to flush logs (seconds) ) ```