Evaluate in your application
Rust SDK
The Rust SDK evaluates flags, variations and variables inside your Rust application, from a datafile it holds in memory, so no decision waits on the network. Its command line runs your project's test specs through this SDK, and an OpenFeature provider is available.
Install#
[dependencies]featurevisor = "3.0"The SDK supports Rust 1.74 and later. On Rust 1.74, run cargo update -p psm --precise 0.1.26 if dependency resolution selects a psm release that needs a newer compiler. Upgrading an existing application? Follow the Rust migration guide.
The CLI is behind the cli feature:
featurevisor = { version = "3.0", features = ["cli"] }Create an instance#
Read a datafile and create an instance with it:
use featurevisor::{context, create_featurevisor, DatafileInput, FeaturevisorOptions};fn main() -> Result<(), Box<dyn std::error::Error>> { let datafile = std::fs::read_to_string("featurevisor-all.json")?; let f = create_featurevisor(FeaturevisorOptions { datafile: Some(DatafileInput::Json(datafile)), ..Default::default() }); let context = context! { "userId" => "user-4" }; println!("{}", f.is_enabled("checkout", Some(&context))); f.close(); Ok(())}This example closes the instance at once. In a long running service, keep it for every evaluation and close it at shutdown. datafile takes DatafileInput::Json with the text, or DatafileInput::Content with a parsed DatafileContent. Every option is optional, so an instance can start without a datafile and receive one later:
| Option | Sets |
|---|---|
datafile | The datafile to evaluate |
context | The instance context |
sticky_features, sticky_variables | Sticky values |
log_level, on_diagnostic | Diagnostics |
modules | Modules |
Create one instance and reuse it. On a server that handles many users, give each request a child instance.
Concurrency#
Featurevisor is Clone, Send and Sync, and evaluations are safe from many threads. Apply changes, such as set_datafile, set_context, set_sticky_features, set_sticky_variables, add_module, remove_module and close, from one thread at a time, never during evaluations. Callbacks run without internal locks, so they can call the instance again.
An evaluation is not pinned to one datafile: a definition already selected finishes with it, and later dependency reads can see an update a callback made. Deep dependency chains grow the stack on the calling thread with stacker, so evaluation stays synchronous and keeps thread local context. WebAssembly is unsupported, since it cannot grow the stack.
Context#
Context is a map of attribute values, which the context! macro builds. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
let f = create_featurevisor(FeaturevisorOptions { datafile: Some(DatafileInput::Json(datafile)), context: Some(context! { "country" => "nl" }), ..Default::default()});Add to it later with set_context, or replace it by passing true as the second argument:
f.set_context(context! { "userId" => "user-4" }, false);f.set_context( context! { "userId" => "user-2", "country" => "nl", }, true,);Context passed to an evaluation is merged over the instance context for that call only:
let context = context! { "userId" => "user-4", "country" => "nl",};f.is_enabled("checkout", Some(&context));get_context(None) returns the instance context, and get_context(Some(&context! { "country" => "de" })) shows it merged with extra values without storing them.
Check a flag#
is_enabled reads a flag. Dutch users have the new checkout:
let context = context! { "userId" => "user-4", "country" => "nl",};if f.is_enabled("checkout", Some(&context)) { // show the new checkout}Get a variation#
get_variation returns the variation of a feature, or None if the feature is disabled or has none:
if f.get_variation("pricing", Some(&context), None).as_deref() == Some("treatment") { // show the new pricing}For user-4 it returns "control", and for user-2 it returns "treatment".
Get a variable#
get_variable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":
let label = f.get_variable("buyButton", "label", Some(&context), None);get_global_variable reads a global variable instead, since Rust has no overloading. supportEmail returns "[email protected]" for user-4:
let email = f.get_global_variable("supportEmail", Some(&context), None);A value is a VariableValue, which serializes as JSON with serde.
Typed methods#
Each typed method returns None when the value has another type, and never parses a string. get_variable_integer returns None for the string "1", and get_variable_boolean returns None for "true".
| Method | Returns |
|---|---|
get_variable_boolean | Option<bool> |
get_variable_string | Option<String> |
get_variable_integer | Option<i64> |
get_variable_double | Option<f64> |
get_variable_array | Option<Vec<VariableValue>> |
get_variable_object | Option<HashMap<String, VariableValue>> |
get_variable_json | Option<VariableValue> |
Each has a global form, such as get_global_variable_string:
let settings = f.get_global_variable_object("checkoutSettings", Some(&context), None);// {"currency": "EUR", "paymentMethods": ["card"]}Composed variables#
Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as get_global_variable_string for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and None.
A composition is evaluated in this order:
- A sticky value for the whole variable, which skips everything after it.
- Root
conditions. When they miss, no source is read and no override runs. The result isdisabledValuewhen supplied, otherwiseNone, with reasonconditions_unmet. - The sources, with their own sticky values, the context and modules taking part as usual.
- The overrides, which run as they do for any global variable.
Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is variable_composed, and a match reports variable_override_rule, with variable_override_paths listing every override that changed the value. Cycles, and chains of more than 256 dependencies, fail the whole evaluation.
Default values#
Pass default_variation_value or default_variable_value in OverrideOptions for when an evaluation produces no value, such as a feature missing from the datafile:
use featurevisor::OverrideOptions;let label = f.get_variable( "buyButton", "label", Some(&context), Some(&OverrideOptions { default_variable_value: Some("Buy".into()), ..Default::default() }),);A default counts as given whenever it is Some, so "", 0, false and VariableValue::Null are all valid defaults.
Evaluate everything at once#
get_feature_evaluations evaluates every loaded feature, or only the keys you pass:
let keys = ["checkout", "pricing", "buyButton"].map(String::from);let evaluations = f.get_feature_evaluations(Some(&context), &keys, None);// checkout: enabled// pricing: enabled, variation "control"// buyButton: enabled, variation "treatment", variables {"label": "Nu kopen"}get_global_variable_evaluations does the same for global variables:
let keys = ["supportEmail", "checkoutSettings"].map(String::from);let variables = f.get_global_variable_evaluations(Some(&context), &keys, None);Pass an empty slice to evaluate them all. To see what is loaded without evaluating anything:
get_feature_keys()lists every feature in the datafile, enabled or not.get_global_variable_keys()lists global variables, andget_variable_keys("buyButton")lists that feature's variables.has_variations("pricing")istruewhen a feature has variations, andfalsefor an unknown feature.
Hand results from server to client#
Both results serialize to the shape sticky values take. A server can evaluate once per request and pass the results to its client, so the first render matches what the server saw. The JavaScript SDK's sticky values read them in a browser.
Sticky values#
Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
use std::collections::HashMap;use featurevisor::EvaluatedFeature;let f = create_featurevisor(FeaturevisorOptions { sticky_features: Some(HashMap::from([ ("checkout".to_string(), EvaluatedFeature { enabled: true, variation: None, variables: None }), ("pricing".to_string(), EvaluatedFeature { enabled: true, variation: Some("treatment".to_string()), variables: None, }), ])), sticky_variables: Some(HashMap::from([ ])), ..Default::default()});A sticky feature can also set variables. Change sticky values later with set_sticky_features and set_sticky_variables. Both merge when the second argument is false, and replace the whole map when it is true:
f.set_sticky_features( HashMap::from([( "checkout".to_string(), EvaluatedFeature { enabled: false, variation: None, variables: None }, )]), true,);Update the datafile#
set_datafile gives the instance a newer datafile:
let accepted = f.set_datafile(DatafileInput::Json(datafile_json), false);It returns true when the datafile is accepted, even if nothing changed, and false when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.
Merge or replace#
With false, the new datafile is merged into the current one:
- Its features, segments and global variables replace those with the same keys.
- Definitions it does not contain are kept.
- Its
revisionandschemaVersionare taken.
Pass true to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
f.set_datafile(DatafileInput::Json(datafile_json), true);Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.
Refresh on an interval#
The SDK starts no timer of its own. Refresh from your runtime's scheduler, such as a Tokio interval:
let refresher = f.clone();tokio::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs(5 * 60)); loop { interval.tick().await; match reqwest::get(DATAFILE_URL).await { Ok(response) if response.status().is_success() => { if let Ok(text) = response.text().await { refresher.set_datafile(DatafileInput::Json(text), true); } } _ => eprintln!("Could not refresh datafile"), } }});A failed fetch keeps the previous datafile. set_datafile does not panic for an invalid datafile, it reports it through diagnostics. Abort the task when you stop, since close() does not stop it. Each accepted update emits datafile_set.
Child instances#
A server handles many users at once, so give each request a child with its own context:
let child = f.spawn( context! { "userId" => "user-4", "country" => "nl", }, Default::default(),);child.is_enabled("checkout", None);- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
- Sticky values are not inherited. Pass them in
SpawnOptionswhen the child needs some. - A child has the parent's evaluation methods, plus
get_context,set_context,set_sticky_features,set_sticky_variables,onandclose. close()removes the child's listeners, including the ones it registered on its parent.
Events#
on subscribes to an EventName with an EventHandler and returns an Unsubscribe, safe to call more than once. The handler receives EventDetails, an enum with a variant per event.
datafile_set#
Emitted for every accepted datafile:
use std::sync::Arc;use featurevisor::{EventDetails, EventName};let unsubscribe = f.on(EventName::DatafileSet, Arc::new(|details: &EventDetails| { if let EventDetails::DatafileSet(set) = details { // set.revision, set.previous_revision, set.revision_changed, set.replaced, // set.features, set.variables and set.segments // evaluate the listed features and variables again }}));unsubscribe();DatafileSetDetails is #[non_exhaustive], so read its fields rather than build it. replaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is ["netherlands"], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.
context_set#
Emitted by set_context:
let unsubscribe = f.on(EventName::ContextSet, Arc::new(|details: &EventDetails| { if let EventDetails::ContextSet(set) = details { // set.context is the new instance context // set.keys lists the top level keys whose values changed }}));keys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context {"userId": "user-4", "country": "nl"}:
use featurevisor::{AttributeValue, Context};f.set_context( Context::from([("country".to_string(), AttributeValue::from("de"))]), false,);// keys: ["country"]f.set_context( Context::from([ ("country".to_string(), AttributeValue::from("de")), ("plan".to_string(), AttributeValue::from("paid")), ]), false,);// keys: ["plan"]f.set_context( Context::from([ ("userId".to_string(), AttributeValue::from("user-4")), ("country".to_string(), AttributeValue::from("de")), ]), true,);// keys: ["plan"]A replace also lists the keys it removed, as plan above. Objects and arrays compare item by item, and numbers by value, so Integer(30) and Double(30.0) are the same. keys is sorted. ContextSetDetails is #[non_exhaustive] too.
sticky_features_set#
Emitted by set_sticky_features, with features, every feature that had a sticky value before the call or has one after it, and replaced.
sticky_variables_set#
Emitted by set_sticky_variables, with variables and replaced.
error#
Emitted for every diagnostic at error, with EventDetails::Error holding the diagnostic.
Diagnostics#
The SDK reports what happens during evaluation as diagnostics, at one of five levels: Fatal, Error, Warn, Info and Debug. By default, those at Info and above go to the console with a [Featurevisor] prefix.
Debug shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later with set_log_level. To send diagnostics somewhere other than the console, pass a handler:
use std::sync::Arc;use featurevisor::{Diagnostic, LogLevel};let f = create_featurevisor(FeaturevisorOptions { log_level: Some(LogLevel::Warn), on_diagnostic: Some(Arc::new(|diagnostic: &Diagnostic| { // send diagnostic.level, code, message and details to your observability system })), ..Default::default()});f.set_log_level(LogLevel::Debug);Every diagnostic has a level, a code, a message and a details object. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in details. The module, module name and original error say where an error came from, when known.
Evaluation errors#
conditions_parse_error is an Error diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during set_datafile for v3 datafiles. Its details contain conditions with the raw string, entityType and entityKey.
The whole malformed selector evaluates to false, even under not, while other entities keep working and set_datafile returns true for an otherwise valid datafile. A malformed root gate is unmet and reports conditions_unmet.
Regular expression conditions use the regex crate, which supports Featurevisor's portable subset. Lookaround and backreferences cannot run there, so they report condition_match_error rather than match. Lint your project before shipping its datafiles.
Dependency cycles fail the whole evaluation with reason error. SDK evaluation errors return the ordinary false or None result, and other entities keep working.
Evaluation details#
The evaluate methods return how a value was reached, not only the value:
f.evaluate_flag("checkout", Some(&context));f.evaluate_variation("pricing", Some(&context), None);f.evaluate_variable("buyButton", "label", Some(&context), None);f.evaluate_global_variable("supportEmail", Some(&context), None);For user-4, evaluate_flag returns an Evaluation with these fields set:
| Field | Value |
|---|---|
evaluation_type | Flag |
feature_key | "checkout" |
reason | Rule |
bucket_key | "user-4.checkout" |
bucket_value | 89312 |
rule_key | "netherlands" |
enabled | true |
Every evaluation has a type and a reason. The others are None unless they apply:
feature_key, empty for global variablesbucket_keyandbucket_value, from 0 to 100,000, and therule_keythat matchedenabled,variationandvariation_valuevariable_key,variable_value,variable_schemaand the global variable's definitionvariable_override_keyandvariable_override_indexwhen a keyed override matched, andvariable_override_pathfor a nested onevariable_override_paths, every override path matched in order, for accumulating overrides. The singular fields describe the last matchconditionswhen a root gate stopped the evaluationerrorwhen evaluation failed
Evaluation reasons#
Test specs can assert them, written as JSON writes them.
| Reason | Meaning |
|---|---|
feature_not_found | The feature is not in the datafile |
disabled | The feature is disabled |
no_variations | A variation was requested from a feature without variations |
variation_disabled | A disabled feature returned its disabledVariationValue |
variable_not_found | The feature variable or global variable is not in the datafile |
variable_default | The variable returned its default value |
variable_composed | A global variable read its composition sources with no override match |
variable_disabled | A disabled feature returned the variable's disabled value |
variable_override_variation | A feature variable override matched inside a variation |
variable_override_rule | A feature variable override or global variable override matched |
conditions_unmet | Root conditions did not match. See conditions |
no_match | No rule, allocation or variation matched, or the bucket fell outside the rollout |
forced | A force entry supplied the result |
sticky | A sticky value supplied the result |
rule | A matching rule supplied the result |
allocated | Bucketing allocated the result |
error | Evaluation failed. See error |
Modules#
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Implement the parts you need of the FeaturevisorModule trait:
use featurevisor::{ ConfigureBucketValueOptions, EvaluateOptions, Evaluation, FeaturevisorModule, ModuleApi,};struct AuditModule;impl FeaturevisorModule for AuditModule { fn name(&self) -> Option<&str> { Some("audit") } fn setup(&self, api: &ModuleApi) { println!("Ready for revision {}", api.get_revision()); } fn before_evaluation(&self, mut options: EvaluateOptions) -> EvaluateOptions { // evaluation_type, feature_key, variable_key and context options.context.insert("plan".into(), "paid".into()); options } fn after_evaluation(&self, evaluation: Evaluation, _options: &EvaluateOptions) -> Evaluation { evaluation } // between 0 and 100,000 fn bucket_value(&self, options: ConfigureBucketValueOptions) -> u32 { options.bucket_value } fn close(&self) { // clean up when the instance closes }}before_evaluation and after_evaluation run for flags, variations and both kinds of variable, every module in registration order. A variable evaluation without a feature key is a global one.
before_evaluation also runs when a schema validates, with EvaluateOptions::entry() naming the schema, its kind schema and its key, instead of a feature key, so context it adds reaches the schema's conditions too. after_evaluation does not run then, since a validation's result is not an evaluation. Check entry() before reading the keys.
The trait cannot tell which methods a module overrides, so every module takes part in evaluations. One that only sets up, such as a package's, returns false from takes_part_in_evaluations, and evaluations skip it and cost what they did without it.
The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
Dependency evaluations#
Conditions and composition members are evaluated through modules too. Their options carry dependency_of, naming the requesting evaluation, and dependency_purpose, condition for an eligibility check and composition for a consumed member value. Direct calls have neither.
When tracking consumed evaluations, skip eligibility checks, not every read with dependency_of, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
Register a module#
Pass modules when creating the instance, or add them later:
use std::sync::Arc;let f = create_featurevisor(FeaturevisorOptions { modules: vec![Arc::new(AuditModule)], ..Default::default()});let remove = f.add_module(Arc::new(TrackingModule));// laterif let Some(remove) = remove { remove();}f.remove_module("audit");add_module returns None for a module whose name is already registered, and reports duplicate_module.
Read the datafile from a module#
A package, such as schemas, reads the datafile through the ModuleApi setup receives:
get_entry(section, key)returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such asschemas, andget_entry_keys(section)lists a section's keys.match_conditions(conditions, context, options)answers the package's own conditions with the instance's engine, segments and feature leaves included.MatchConditionsOptionsreaders answer leaves only the package knows, such asinput.evaluate(&PackageEvaluationRequest::new(kind, key).with_context(context), |scope| ...)evaluates the package's own entry as a getter evaluates a flag. Every module'sbefore_evaluationruns first, withEvaluateOptions::entry()naming the entry, and the conditions the closure answers withscope.match_conditions(conditions, readers)read the context the modules leave, in one dependency session.
Feature and variable leaves reach modules as dependencies, whose dependency_of has EvaluationType::Entry and names the package's entry in entry. ModuleApi can be cloned and kept, and has_module(name) on the instance says whether a module of that name is registered.
Schemas#
Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.
Schemas are experimental, so their API may change in a minor release, as in JavaScript.
Create a schemas instance#
They are a separate crate, released with the same version as the SDK:
[dependencies]featurevisor = "3.0"featurevisor-schemas = "3.0"Create it from the SDK instance. Call it s, as the SDK instance is f:
use featurevisor_schemas::Schemas;let s = Schemas::new(&f);It holds no copy of the schemas. Every call reads the datafile f has now, so a new datafile applies at the next validation. Schemas and its handles are cheap to clone, safe to share between threads, and close when the last of them is dropped, or with close().
Validate a value#
let value = serde_json::json!({ "displayName": "A", "country": "nl",});let result = s.validate("signUp", &value, None);if !result.is_valid() { // show result.issues beside the form's fields}s.validate(key, &value, context)returns aValidationResultwith itsissues. It never coerces, fills defaults or strips keys.s.is_valid(key, &value, context)returns a boolean.s.parse::<T>(key, &value, context)validates and then deserializes into your own type, or returnsParseError::Invalidwith the issues.contextis merged over the instance's, for the conditions a schema's rules read.- A validation runs as the schema's own evaluation, so a module's
before_evaluationsees it, withEvaluateOptions::entry()naming the schema, and context the module adds reaches every condition, as it does for flags. s.keys()lists the schemas the datafile has, ands.contains(key)says whether it has one.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at Warn, once per key.
Read the issues#
Every issue has a message, a path of object keys and array indices, the code of the rule that failed, its params, and the schema validated. It serializes to JSON for an error response.
Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in params["title"], and one whose rule a mutation set names it in mutation.
| Code | Raised when |
|---|---|
type | The value has another type |
const, enum | The value is not one allowed |
minimum, maximum | A number is out of range |
minLength, maxLength | A string is too short or too long |
pattern, format | A string has the wrong shape |
minItems, maxItems | An array has too few or too many items |
uniqueItems | An array repeats an item |
required, additionalProperties | A key is missing, or there is one it does not allow |
oneOf | No branch matches, or more than one does |
refine | An issues entry matches, or a check in code fails |
refineError | A check in code fails with an error, or the schema cannot be applied |
schemaNotFound | The datafile has no such schema or field |
result.flatten() groups the messages by field, in the shape of Zod's flattenError:
if !result.is_valid() { // { "formErrors": [], "fieldErrors": { "displayName": ["..."] } } return (StatusCode::UNPROCESSABLE_ENTITY, Json(result.flatten()));}Get a handle#
s.get(key) gives the schema's handle:
let sign_up = s.get("signUp");A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. It is stable, and reads the current datafile whenever it is used, so keep one for the life of the service.
| Member | What it is |
|---|---|
validate, is_valid, parse | As on s, without the key |
field(path) | The handle of one field, such as field("displayName") |
fields() | An object's fields' handles, in order, each with its name() |
constraints(), field_constraints() | HTML validation attributes, by field path from field_constraints(), below |
options(), field_options(), option(value) | Its choices, by field path from field_options(), and one choice by value |
render_as() | What its rules say the field renders as, such as Some("select") |
annotations() | Its annotations |
with_input(&input, context) | The same handle with an input |
reads() | The fields its rules' conditions read |
subscribe(listener) | A call when a new datafile changes the schema |
key(), path(), name() | The schema's key, and the field's path and own name |
field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound.
Read constraints and choices#
constraints() are named after HTML attributes:
let constraints = sign_up.field("displayName").constraints();// required: true, min_length: Some(2), max_length: Some(40)constraints.attributes();// [("required", ""), ("minlength", "2"), ("maxlength", "40")], for a templaterequired, when the key is required, so an input left empty failsmin_lengthandmax_length, from the same rules on a stringminandmax, fromminimumandmaximumon a numberstepof 1, for anintegermultiple, for an array, such as a multiple select
options() lists a field's choices in the order of its rules, each with what its annotations say, and option(value) finds one, for showing a value saved earlier:
let country = sign_up.field("country");country.options(); // nl, de and becountry.option(&"nl".into()).and_then(|o| o.title().map(String::from)); // Some("Netherlands")country.option(&"fr".into()); // NoneA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. render_as() answers the switch every generic form writes, from the field's rules alone: text, date-time, version, number, boolean, select, multiselect, object or list. Your own annotation, such as input: select, still wins over it.
Read annotations#
A handle's annotations() are its node's own, and fields() gives an object's fields in its order:
sign_up.annotations().get("title"); // Some("Create your account")sign_up.fields().iter().map(|field| field.path()).collect::<Vec<_>>();// ["displayName", "email", "country"]default is the value a form starts a field with, and a handle from with_input has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. Annotations on Schemas writes them.
Follow the values typed so far#
A handle's constraints and choices describe the schema's own rules, which no condition changes. with_input(&input, context) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:
let values = serde_json::json!({ "accountType": "business", "country": "nl",});sign_up.field("taxId").constraints().required; // falsesign_up.with_input(&values, None).field("taxId").constraints().required; // trueEvery member follows the input, at every depth. Make one where you render rather than keeping one. reads() lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
Choose the messages#
SchemasOptions words every schema's issues, per code, as a template or a function with Message::function:
use featurevisor_schemas::SchemasOptions;let s = Schemas::with_options(&f, SchemasOptions::new().message("required", "This field is required"));SchemasOptions and HandleOptions are built with new() and their methods, since they may gain fields. HandleOptions::new().message("password", "minLength", "...") with s.get_with words one form, by field and code. For each issue, the first of these that words it wins:
- A check in code's own message, then the form's.
- The schema's own, and then the
messageof its issues entry. - The application's, from
SchemasOptions. - The default, in English.
translate on SchemasOptions gets each issue, with the message chosen, and returns what the issue says, or None to keep it. With translations, schemas and messages hold keys, such as errors.required, and translate turns each into text.
Check in code#
Some checks need your application, such as whether a display name is taken. Give them to a handle in HandleOptions::refine, each a Refinement with a key, a path and a check, and a message and reads as it needs them:
use featurevisor_schemas::{HandleOptions, Refinement};let sign_up = s.get_with( "signUp", HandleOptions::new().refine( Refinement::new("nameAvailable", "displayName", |value, _info| { Ok(names.is_available(value.as_str().unwrap_or_default())) }) .message("That display name is taken"), ),);let result = sign_up.validate(&value, None);- A check gets the value at its path, and a
CheckInfowith the wholeinputand thecontext. It returnsOk(true)when the value passes. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
- With an empty path, the check gets the whole value, and runs only when the value has no issue at all.
.reads(["items"])names other fields whose issues hold it back too, such asitemsfor a check of an order's total. - Its issue has code
refineand therefineparam"nameAvailable", with the field's title. A check that returns an error or panics givesrefineError, validation fails closed, and oneschema_check_errordiagnostic per schema and check key says why, withschemaKey,checkandpathin its details. - In the handle of a field, a check's
inputis the field's value. In a view made from the schema's root withwith_input, it is the whole input with the field's value in its place. - Checks run in order, synchronously.
Options from your application#
Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource in HandleOptions::option_sources, with a key, a path, and a search, a lookup or both:
use featurevisor_schemas::OptionSource;let cities = OptionSource::new("cities", "city") .reads(["country"]) .search(|query, info| Ok(city_index.search(&info.input["country"], query))) .lookup(|city, info| Ok(city_index.find(&info.input["country"], city))) .message("Choose a city from the list");let sign_up = s.get_with("signUp", HandleOptions::new().option_source(cities));let city = sign_up.with_input(&serde_json::json!({ "country": "nl" }), None).field("city");let suggestions = city.search("am", None)?;// Amsterdam and Amersfoortsearchreturns choices asSchemaOptions. A handle'ssearchpasses it the values given towith_input, so the cities follow the country.is_searchable()says whether a field has one.lookupreturns what the source says about a value,Somewith its fields when found, orNonewhen there is none. A handle'slookup(&value, None)returns the schema's own choice first, then the source's.- Validation runs
lookupas a check in code, after the schema's rules, only for a value that is there, and not while a fieldreadsnames has an issue. A value it cannot find has codeenum, worded by its message.
Validate on the server#
parse validates a request and deserializes it into your own type, with the issues when it fails:
#[derive(serde::Deserialize)]struct SignUp { #[serde(rename = "displayName")] display_name: String,}async fn sign_up(Json(body): Json<serde_json::Value>) -> Response { match s.parse::<SignUp>("signUp", &body, None) { Ok(sign_up) => create_account(sign_up).await.into_response(), Err(ParseError::Invalid(result)) => { (StatusCode::UNPROCESSABLE_ENTITY, Json(result.flatten())).into_response() } Err(error) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(), }}A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
Listen for changes#
subscribe calls back when a new datafile changes the schema, through a schema it references too, and returns an Unsubscribe that stops it:
let stop = s.get("signUp").field("country").subscribe(|| render_choices());A datafile whose schema is unchanged calls nothing. s.close() stops every listener the instance started and removes its module from the Featurevisor instance.
Patterns#
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: $ is the end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, or that the regex crate cannot compile, such as one with lookbehind, fails every value with one schema_pattern_unsupported diagnostic. A mutation whose operations cannot be applied fails the value with refineError and one schema_mutation_error diagnostic, and so does a check that returns an error or panics, with schema_check_error. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels deep, and the 129th fails closed with refineError and one schema_reference_depth diagnostic. Each of these diagnostics is reported once per datafile revision.
A key required lists is required whether or not the object has properties, so an object with additionalProperties only reports each missing key as required, and an unknown type fails every value with a type issue. Rust has no "no value" for a field's handle, since validate takes a JSON value and null is one, so a field validated alone is never read as absent.
Close#
close() removes event listeners and closes modules, on the instance and on a child:
f.close();Closing more than once does nothing more. Close an instance or a child when you finish with it, above all when your callbacks capture it, since Rust reference counting does not collect ownership cycles. Dropping an Unsubscribe does not unsubscribe, so call it. Evaluations already in progress finish with the datafile they read.
OpenFeature#
The OpenFeature provider is published as a separate crate. Applications that only use the Featurevisor SDK do not compile or link OpenFeature, Tokio, or the provider code.
The provider supports the official OpenFeature Rust SDK 0.3.0 and requires Rust 1.80.1 or newer. The base Featurevisor crate continues to support Rust 1.74 or newer.
[dependencies]featurevisor = "3.0"featurevisor-openfeature = "3.0"open-feature = "0.3"tokio = { version = "1", features = ["macros", "rt-multi-thread"] }Create a provider that owns its Featurevisor instance:
use featurevisor::{DatafileInput, FeaturevisorOptions};use featurevisor_openfeature::{FeaturevisorProvider, FeaturevisorProviderOptions};use open_feature::{EvaluationContext, OpenFeature};async fn configure(datafile: String) -> Result<(), Box<dyn std::error::Error>> { let provider = FeaturevisorProvider::new(FeaturevisorProviderOptions { featurevisor_options: FeaturevisorOptions { datafile: Some(DatafileInput::Json(datafile)), ..Default::default() }, ..Default::default() })?; let mut api = OpenFeature::singleton_mut().await; api.set_provider(provider).await; let client = api.create_client(); drop(api); let enabled = client .get_bool_value( "checkout", Some(&EvaluationContext::default().with_targeting_key("user-4")), None, ) .await?; println!("Checkout enabled: {enabled}"); Ok(())}Pass an existing Featurevisor instance for the provider to borrow. The provider does not close it:
use featurevisor_openfeature::FeaturevisorProvider;let provider = FeaturevisorProvider::from_featurevisor(f.clone())?;OpenFeature uses one flag key while Featurevisor supports flags, variations, feature variables, and global variables:
| OpenFeature key | Featurevisor evaluation |
|---|---|
checkout | Flag for feature checkout |
checkout:variation | Variation for feature checkout |
buyButton:label | Variable title inside feature checkout |
variable:supportEmail | Global variable supportEmail |
targeting_key_field, key_separator, variation_key, and global_variable_prefix customize this mapping. The targeting key maps to userId by default. The global variable prefix defaults to variable and cannot contain the separator.
The provider implements boolean, integer, float, string, and structure resolution. The OpenFeature Rust SDK represents top level object values with StructValue. Arrays can be nested in those objects, but its provider contract does not expose a separate top level array resolver.
The upstream structure value type cannot represent null. Resolving a null structure reports a type mismatch so the OpenFeature client can use its supplied default. Null object properties and array members are omitted during structure conversion, including in composed values.
Featurevisor evaluation reasons, variation values, revision, schema version, rule keys, bucket information, and override information are mapped to OpenFeature resolution details and flag metadata. Missing definitions, type mismatches, invalid contexts, and invalid datafiles use standard OpenFeature errors. Replacing an invalid datafile with a valid one recovers the provider.
An unmet root condition keeps the Featurevisor reason conditions_unmet and maps to OpenFeature DISABLED. Composed values map to TARGETING_MATCH, including matched composed overrides. The provider does not decode composed JSON values again.
The OpenFeature Rust SDK does not currently expose provider tracking or provider event callbacks. Featurevisor modules and diagnostics continue to work inside the Featurevisor instance.
The provider status accessor reports Error for an invalid initial datafile, independently of the diagnostic log level, and Ready after a valid update. The upstream Rust initialization method has no error return value. Evaluations report ParseError while the datafile is unhealthy. Borrowed instances remain owned by the caller.
See the OpenFeature provider guide for the shared key convention and providers for other languages.
CLI usage#
Install the optional CLI with Cargo, from featurevisor-schemas so schema specs validate their values with the schemas crate as the JavaScript CLI does:
cargo install featurevisor-schemas --version "^2.0" --features clicargo install featurevisor --features cli installs the same CLI without schemas, where each schema spec case fails asking for them. Both binaries are named featurevisor, so in this repository build them one package at a time. make build does not build the one with schema specs, so use cargo build -p featurevisor-schemas --features cli for it.
The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
npm install --save-dev @featurevisor/cli@^4.0.0Project parsing, test definitions, execution protocol, matrix expansion and datafile generation use npx featurevisor. Evaluations run through this Rust SDK. Use the Node.js CLI directly for authoring commands. This native CLI provides only test, benchmark and distribution commands. The SDK runtime has no Node.js dependency.
Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.
Duplicate targets are evaluated once, at their first position.
Test#
featurevisor test \ --project-directory-path=/path/to/featurevisor-project \ --only-failuresSee Testing for authoring specs and Checks for check syntax and operators.
Useful test options:
--key-pattern=<pattern>and--assertion-pattern=<pattern>filter tests.--entity-type=scenarioselects scenarios, and--entity-type=schemaschema specs.--set=<set>selects one project set. Omitting--setruns all sets.--case=<id>reruns one expanded case. Copy the opaque ID or rerun command from a failure report.--json --prettyproduces an indented JSON report.--coveragereports observed rule and override selections.--uncoveredlists features and global variables without associated specs.--only-failures,--quiet,--verboseand--show-datafilecontrol diagnostic output.
Benchmark#
The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. Rust evaluates them. Replace checkout with a feature defined in your project.
featurevisor benchmark \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --context='{"country":"nl"}' \ --n=1000Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.
Assess distribution#
featurevisor assess-distribution \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --populate-uuid=userId \ --n=1000Repeat --populate-uuid=<key> or --populate-uuid <key> to generate UUID values for multiple context attributes. Add --verbose to print generated contexts. Both measurement commands accept --n=1000, --n 1000, -n=1000 and -n 1000. Counts must be positive integers. Quote JSON context and paths containing spaces as one shell argument. See Assess distribution.
The legacy --with-scopes, --with-tags, --schemaVersion and --schema-version options are accepted and ignored.
GitHub repositories#
- SDK: featurevisor/featurevisor-rust
- Example application: featurevisor/featurevisor-example-rust

