The Featurevisor Elixir SDK evaluates flags, variations and variables in Elixir applications, from a datafile it holds in memory.
- Install
- Create an instance
- Context
- Check a flag
- Get a variation
- Get a variable
- Default values
- Evaluate everything at once
- Sticky values
- Update the datafile
- Child instances
- Events
- Diagnostics
- Evaluation details
- Modules
- Schemas
- Close
- OpenFeature
- CLI usage
- GitHub repositories
- Development
- Publishing
- License
Add featurevisor to your dependencies in mix.exs:
def deps do
[
{:featurevisor, "~> 2.0"}
]
endThen run mix deps.get. The SDK supports Elixir 1.15 and later. Upgrading an existing application? Follow the Elixir migration guide.
Read a datafile and create an instance with it:
datafile =
"featurevisor-all.json"
|> File.read!()
|> Jason.decode!()
f = Featurevisor.create_featurevisor(%{datafile: datafile})
try do
IO.puts(Featurevisor.enabled?(f, "checkout", %{"userId" => "user-4"}))
after
Featurevisor.close(f)
endThis example closes the instance at once. In a long running application, keep it for every evaluation, or let a supervisor own it. datafile takes a decoded map or the JSON text. 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 share it between processes. On a server that handles many users, give each request a child instance.
In an OTP application, start the instance under your supervisor:
children = [
{Featurevisor,
name: MyApp.Featurevisor,
datafile: datafile,
log_level: :warn}
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)Resolve its handle wherever you need it:
f = Featurevisor.instance(MyApp.Featurevisor)The supervisor owns shutdown and restart, and module close callbacks run when it stops the instance. Resolve the handle again after a restart. create_featurevisor/1 is not linked to the calling process, so whoever creates an instance that way calls Featurevisor.close/1 at shutdown.
The handle is a plain term, safe to share between processes, and evaluations run concurrently in the calling process. Apply changes, such as set_datafile, set_context, set_sticky_features, set_sticky_variables, add_module and remove_module, from one owner rather than racing them. Callbacks can call the instance again.
Context is a map of attribute values, with string keys, so they match the datafile's attribute names and nested paths. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
f = Featurevisor.create_featurevisor(%{
datafile: datafile,
context: %{"country" => "nl"}
})Add to it later with set_context, or replace it by passing true:
Featurevisor.set_context(f, %{"userId" => "user-4"})
Featurevisor.set_context(
f,
%{
"userId" => "user-2",
"country" => "nl"
},
true
)Context passed to an evaluation is merged over the instance context for that call only:
context = %{
"userId" => "user-4",
"country" => "nl"
}
Featurevisor.enabled?(f, "checkout", context)Featurevisor.get_context(f) returns the instance context, and Featurevisor.get_context(f, %{"country" => "de"}) shows it merged with extra values without storing them.
Date conditions take ISO 8601 strings with an explicit time zone, and DateTime values, not Date or NaiveDateTime. Fractions are truncated to milliseconds, and a value that is not a valid date makes both before and after false.
enabled? reads a flag, as isEnabled does in JavaScript. Dutch users have the new checkout:
context = %{
"userId" => "user-4",
"country" => "nl"
}
if Featurevisor.enabled?(f, "checkout", context) do
# show the new checkout
endget_variation returns the variation of a feature, or nil if the feature is disabled or has none:
case Featurevisor.get_variation(f, "pricing", context) do
"treatment" -> show_new_pricing()
_ -> show_pricing()
endFor user-4 it returns "control", and for user-2 it returns "treatment".
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":
label = Featurevisor.get_variable(f, "buyButton", "label", context)get_global_variable reads a global variable instead. supportEmail returns "support-nl@example.com" for user-4:
email = Featurevisor.get_global_variable(f, "supportEmail", context)JSON variables are decoded before they are returned.
Each typed method returns nil when the value has another type, and never parses a string. get_variable_integer returns nil for the string "1", and get_variable_boolean returns nil for "true".
| Method | Returns |
|---|---|
get_variable_boolean |
boolean() |
get_variable_string |
String.t() |
get_variable_integer |
integer() |
get_variable_number |
number(), for a variable of type number or double |
get_variable_array |
list() |
get_variable_object |
map() |
get_variable_json |
the decoded JSON |
Each has a global form, such as get_global_variable_string:
settings = Featurevisor.get_global_variable_object(f, "checkoutSettings", context)
# %{"currency" => "EUR", "paymentMethods" => ["card"]}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 nil.
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, otherwisenil, with reason:conditions_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.
Pass default_variation_value or default_variable_value in the options for when an evaluation produces no value, such as a feature missing from the datafile:
label =
Featurevisor.get_variable(f, "buyButton", "label", context, %{
default_variable_value: "Buy"
})A default counts as given whenever the key is present, so "", 0, false and nil are all valid defaults.
get_feature_evaluations evaluates every loaded feature, or only the keys you pass:
evaluations = Featurevisor.get_feature_evaluations(f, context, ["checkout", "pricing", "buyButton"])
# %{
# "checkout" => %{enabled: true},
# "pricing" => %{enabled: true, variation: "control"},
# "buyButton" => %{enabled: true, variation: "treatment", variables: %{"label" => "Nu kopen"}}
# }get_global_variable_evaluations does the same for global variables:
variables = Featurevisor.get_global_variable_evaluations(f, context, ["supportEmail", "checkoutSettings"])Leave out the keys to evaluate them all. To see what is loaded without evaluating anything:
get_feature_keys(f)lists every feature in the datafile, enabled or not.get_global_variable_keys(f)lists global variables, andget_variable_keys(f, "buyButton")lists that feature's variables.has_variations?(f, "pricing")istruewhen a feature has variations, andfalsefor an unknown feature.
Both results encode to JSON in 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 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:
f = Featurevisor.create_featurevisor(%{
sticky_features: %{
"checkout" => %{"enabled" => true},
"pricing" => %{"enabled" => true, "variation" => "treatment"}
},
sticky_variables: %{"supportEmail" => "support@example.com"}
})A sticky feature can also set "variables". Change sticky values later with set_sticky_features and set_sticky_variables. Both merge by default, and replace the whole map when passed true:
Featurevisor.set_sticky_features(f, %{"checkout" => %{"enabled" => false}}, true)Treat the maps you pass as read only, and use a setter to change them.
set_datafile gives the instance a newer datafile, decoded or as JSON text:
accepted = Featurevisor.set_datafile(f, datafile)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, with the reason in the diagnostic's original_error.
By default, 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:
Featurevisor.set_datafile(f, datafile, 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.
The SDK starts no process of its own and chooses no HTTP client. Refresh from a process you supervise, such as a GenServer with Req:
defmodule MyApp.DatafileRefresher do
use GenServer
@url "https://cdn.example.com/featurevisor-all.json"
@interval :timer.minutes(5)
def start_link(f), do: GenServer.start_link(__MODULE__, f)
@impl true
def init(f) do
Process.send_after(self(), :refresh, @interval)
{:ok, f}
end
@impl true
def handle_info(:refresh, f) do
case Req.get(@url) do
{:ok, %{status: 200, body: body}} -> Featurevisor.set_datafile(f, body, true)
_ -> Logger.warning("Could not refresh datafile")
end
Process.send_after(self(), :refresh, @interval)
{:noreply, f}
end
endA failed fetch keeps the previous datafile. set_datafile does not raise for an invalid datafile, it reports it through diagnostics. Stop the process when you close the instance. Each accepted update emits :datafile_set.
A server handles many users at once, so give each request a child with its own context:
child =
Featurevisor.spawn(f, %{
"userId" => "user-4",
"country" => "nl"
})
Featurevisor.Child.enabled?(child, "checkout")- 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
sticky_featuresandsticky_variablesas the third argument when the child needs some. Featurevisor.Childhas the parent's evaluation functions, plusget_context,set_context,set_sticky_features,set_sticky_variables,onandclose.Featurevisor.Child.close/1removes the child's listeners, including the ones it registered on its parent.
Featurevisor.on/3 subscribes to an event and returns a function that unsubscribes, safe to call more than once. The callback receives the event's details as a map.
Emitted for every accepted datafile:
unsubscribe =
Featurevisor.on(f, :datafile_set, fn details ->
# details.revision, details.previousRevision, details.revisionChanged,
# details.replaced, details.features, details.variables and details.segments
# evaluate the listed features and variables again
end)
unsubscribe.()The details keep the JavaScript SDK's names, as atoms, so previousRevision rather than previous_revision, as diagnostic details do. 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.
Emitted by set_context:
Featurevisor.on(f, :context_set, fn details ->
# details.context is the new instance context
# details.keys lists the top level keys whose values changed
end)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"}:
Featurevisor.set_context(f, %{
"country" => "de"
})
# keys: ["country"]
Featurevisor.set_context(f, %{
"country" => "de",
"plan" => "paid"
})
# keys: ["plan"]
Featurevisor.set_context(
f,
%{
"userId" => "user-4",
"country" => "de"
},
true
)
# keys: ["plan"]A replace also lists the keys it removed, as plan above. Maps and lists compare item by item, and numbers by value, so 30 and 30.0 are the same. keys is sorted.
Emitted by set_sticky_features, with features, every feature that had a sticky value before the call or has one after it, and replaced.
Emitted by set_sticky_variables, with variables and replaced.
Emitted for every diagnostic at :error, with the diagnostic.
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 Logger, and errors to standard error, 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 else, pass a handler:
f = Featurevisor.create_featurevisor(%{
datafile: datafile,
log_level: :warn,
on_diagnostic: fn diagnostic ->
# send diagnostic.level, code, message and details to your observability system
end
})
Featurevisor.set_log_level(f, :debug)Every Featurevisor.Diagnostic has a level, a code, a message and a details map. 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.
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 follow Featurevisor's portable subset, which project linting enforces. The g flag does nothing here, and an invalid pattern or flag reports condition_match_error and does not match.
Dependency cycles fail the whole evaluation with reason :error. SDK evaluation errors return the ordinary false or nil result, and other entities keep working.
The evaluate functions return how a value was reached, not only the value:
Featurevisor.evaluate_flag(f, "checkout", context)
Featurevisor.evaluate_variation(f, "pricing", context)
Featurevisor.evaluate_variable(f, "buyButton", "label", context)
Featurevisor.evaluate_global_variable(f, "supportEmail", context)For user-4, evaluate_flag returns a Featurevisor.Evaluation with these fields set:
| Field | Value |
|---|---|
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 nil unless they apply:
feature_key,nilfor 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
Featurevisor.Evaluation.to_map/1 gives it with the camel case names JSON uses.
Test specs can assert them, written as JSON writes them, without the colon.
| 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 |
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Set the callbacks you need on a Featurevisor.Module:
module = %Featurevisor.Module{
name: "audit",
setup: fn api ->
IO.puts("Ready for revision #{api.get_revision.()}")
end,
before_evaluation: fn options ->
# options.type, options.feature_key, options.variable_key and options.context
%{options | context: Map.put(options.context, "plan", "paid")}
end,
after_evaluation: fn evaluation, _options ->
evaluation
end,
# between 0 and 100,000
bucket_value: fn options ->
options.bucket_value
end,
close: fn ->
# clean up when the instance closes
:ok
end
}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. A module without either, or the bucket callbacks, costs evaluations nothing.
before_evaluation also runs when a schema validates, with type schema and the schema's 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 type before reading the keys.
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.
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.
Pass modules when creating the instance, or add them later:
f = Featurevisor.create_featurevisor(%{modules: [module]})
remove = Featurevisor.add_module(f, tracking_module)
# later
remove.()
Featurevisor.remove_module(f, "audit")A module whose name is already registered is not added, and reports duplicate_module. Featurevisor.has_module?/2 says whether a module of a name is registered. A module whose setup fails is removed again, and its close runs.
A package, such as schemas, reads the datafile through the API setup receives:
api.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, ornil, andapi.get_entry_keys.(section)lists a section's keys.api.match_conditions.(conditions, context, readers: readers)answers the package's own conditions with the instance's engine, segments and feature leaves included. Readers answer leaves only the package knows, such asinput, with{:ok, value}, or:errorfor no value.api.evaluate.(%{type: type, key: key, context: context}, fn scope -> ... end)evaluates the package's own entry as a getter evaluates a flag. Every module'sbefore_evaluationruns first, withtypeandkeynaming the entry, and the conditions the function answers withFeaturevisor.PackageEvaluationScope.match_conditions(scope, conditions, readers)read the context the modules leave, in one dependency session.
Feature and variable leaves reach modules as dependencies, whose dependency_of names the package's entry by type and key.
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.
They are a separate Hex package, released with the same version as the SDK:
def deps do
[
{:featurevisor, "~> 2.1"},
{:featurevisor_schemas, "~> 2.1"}
]
endCreate it from the SDK instance, not a child. Call it s, as the SDK instance is f:
s = FeaturevisorSchemas.create(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. It and its handles are plain terms, safe to keep in application state and share between processes.
value = %{
"email" => "user-1@example.com",
"displayName" => "A",
"country" => "nl"
}
case FeaturevisorSchemas.validate(s, "signUp", value) do
{:ok, value} -> create_account(value)
{:error, issues} -> render_errors(issues)
endFeaturevisorSchemas.validate(s, key, value, context: context)returns{:ok, value}or{:error, issues}. It never coerces, fills defaults or strips keys.FeaturevisorSchemas.valid?/4returns a boolean, andvalidate!/4returns the value or raisesFeaturevisorSchemas.ValidationErrorwith 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, withtypeschemaand the schema'skey, and context the module adds reaches every condition, as it does for flags. FeaturevisorSchemas.keys(s)lists the schemas the datafile has, andFeaturevisorSchemas.has?(s, key)says whether it has one.
A value can be maps with string or atom keys, lists, primitives and structs. Lengths count code points, as the other SDKs do, where String.length/1 counts graphemes.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at :warn, once per key until the next datafile.
required applies with or without properties, so an object with only additionalProperties and required: ["en-GB"] must have an en-GB key.
Every FeaturevisorSchemas.Issue has a message, a path of object keys and list indices, the code of the rule that failed, its params, and the schema validated. It encodes 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 |
FeaturevisorSchemas.flatten(issues) groups the messages by field, in the shape of Zod's flattenError:
{:error, issues} ->
# %{form_errors: [], field_errors: %{"displayName" => ["..."]}}
conn |> put_status(422) |> json(FeaturevisorSchemas.flatten(issues))A handle is one schema as a term your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. FeaturevisorSchemas.get(s, key) gives one, and FeaturevisorSchemas.Handle reads it:
alias FeaturevisorSchemas.Handle
sign_up = FeaturevisorSchemas.get(s, "signUp")A handle reads the current datafile whenever it is used, so keep one for the life of the application.
| Function | What it gives |
|---|---|
validate, valid?, validate! |
As on FeaturevisorSchemas, without the key |
field(handle, path) |
The handle of one field, such as field(sign_up, "displayName") |
fields |
An object's fields' handles, in order, each with its name |
constraints, field_constraints |
HTML validation attributes, by field path with field_constraints, below |
options, field_options, option(handle, value) |
Its choices, by field path with field_options, and one choice by value |
render_as |
What its rules say the field renders as, such as "select" |
annotations |
Its annotations |
with_input(handle, input, context: context) |
The same handle with an input |
reads |
The fields its rules' conditions read |
subscribe(handle, 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, with the field in its params, and with no schema_not_found diagnostic, since the schema itself is there.
A field's handle always has a value to validate, since nil is the JSON null, which is a value. It has no way to be given no value, as JavaScript's undefined does for a form library's empty field. To leave a field out, validate the object around it, where a missing key reports required only when the schema requires it.
Handle.constraints/1 gives a FeaturevisorSchemas.Constraints, named after HTML attributes:
constraints = sign_up |> Handle.field("displayName") |> Handle.constraints()
# %FeaturevisorSchemas.Constraints{required: true, min_length: 2, max_length: 40}
FeaturevisorSchemas.Constraints.attributes(constraints)
# %{required: true, 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
Handle.options/1 lists a field's choices in the order of its rules, each a FeaturevisorSchemas.Option with what its annotations say, and Handle.option/2 finds one, for showing a value saved earlier:
country = Handle.field(sign_up, "country")
Handle.options(country) # nl, de and be
Handle.option(country, "nl").title # "Netherlands"
Handle.option(country, "fr") # nilA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. Handle.render_as/1 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.
A handle's annotations are its node's own, and fields gives an object's fields in its order:
Handle.annotations(sign_up)["title"] # "Create your account"
sign_up |> Handle.fields() |> Enum.map(&Handle.path/1)
# ["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.
A handle's constraints and choices describe the schema's own rules, which no condition changes. Handle.with_input/3 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:
values = %{
"accountType" => "business",
"country" => "nl"
}
(sign_up |> Handle.field("taxId") |> Handle.constraints()).required # false
(sign_up |> Handle.with_input(values) |> Handle.field("taxId") |> Handle.constraints()).required # trueEvery function follows the input, at every depth. Handle.reads/1 lists the fields the conditions of a handle's mutations and issues read, ["accountType", "country", "confirmEmail", "email", "displayName", "invites[].admin"] for signUp, so a LiveView can validate again only when one of them changes.
:messages on create words every schema's issues, per code, as text with placeholders or a function of the params and the FeaturevisorSchemas.MessageInfo:
s = FeaturevisorSchemas.create(f, messages: %{"required" => "This field is required"}):messages on FeaturevisorSchemas.get/3 words one form, by field and code, such as messages: %{"displayName" => %{"minLength" => "Use {minLength} characters or more"}}. 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
create. - The default, in English.
:translate on create gets each issue, with the message chosen, and returns what the issue says, or nil to keep it. With translations, :messages holds keys, such as errors.required, and :translate turns each into text, with Gettext for example.
Some checks need your application, such as whether a display name is taken. Give them to a handle in :refine, each a FeaturevisorSchemas.Refinement with a key and a check, and the path it checks, a message and reads as it needs them:
sign_up =
FeaturevisorSchemas.get(s, "signUp",
refine: [
%FeaturevisorSchemas.Refinement{
key: "nameAvailable",
path: "displayName",
message: "That display name is taken",
check: fn name, _info -> Accounts.name_available?(name) end
}
]
)
Handle.validate(sign_up, value)- A check gets the value at its path, and a
FeaturevisorSchemas.CheckInfowith theinputand thecontext. It returnstruewhen the value passes. inputis the whole value on the schema's handle, and the field's own value on a field's handle, such asHandle.field(sign_up, "displayName"). A field's handle fromwith_inputis the exception: its checks get the whole input, with the field's value in its place.- 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.
- Its issue has code
refineand therefineparam"nameAvailable", with the field's title. A check that returns{:error, reason}, raises or exits givesrefineError, and validation fails closed, with aschema_check_errordiagnostic that carries the error. - Without a path, the check gets the whole value, and runs only when the value has no issue at all.
reads: ["country"]names other fields whose issues hold it back too. - Checks run in order, in the calling process.
Some lists only your application can answer for, such as cities for a city field. Give a handle a FeaturevisorSchemas.OptionSource in :option_sources, with a key, a path, and a search, a lookup or both:
cities = %FeaturevisorSchemas.OptionSource{
key: "cities",
path: "city",
reads: ["country"],
message: "Choose a city from the list",
search: fn query, info -> {:ok, Places.search_cities(info.input["country"], query)} end,
lookup: fn city, info ->
case Places.find_city(info.input["country"], city) do
nil -> :error
found -> {:ok, %{"title" => found.name}}
end
end
}
city =
s
|> FeaturevisorSchemas.get("signUp", option_sources: [cities])
|> Handle.with_input(%{"country" => "nl"})
|> Handle.field("city")
{:ok, suggestions} = Handle.search(city, "am")
# Amsterdam and Amersfoortsearchreturns{:ok, choices}, each a value or a map with a"value". A handle'ssearchpasses it the values given towith_input, so the cities follow the country.Handle.searchable?/1says whether a field has one.lookupreturns what the source says about a value,{:ok, fields}when found, or:errorwhen there is none. A handle'slookupreturns 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. A lookup that returns{:error, reason}, raises or exits givesrefineErrorandschema_check_error, as a check does.
validate checks a request before it reaches your code:
def create(conn, params) do
case FeaturevisorSchemas.validate(s, "signUp", params) do
{:ok, params} ->
json(conn, Accounts.create!(params))
{:error, issues} ->
conn |> put_status(422) |> json(FeaturevisorSchemas.flatten(issues))
end
endA rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
Handle.subscribe/2 calls back when a new datafile changes the schema, and returns a function that stops it:
pid = self()
stop = s |> FeaturevisorSchemas.get("signUp") |> Handle.subscribe(fn -> send(pid, :schema_changed) end)A datafile whose schema is unchanged calls nothing. FeaturevisorSchemas.close(s) removes its module from the Featurevisor instance.
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: ^ and $ are the start and 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, such as [a-z\_], 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.
A schema that references itself can nest at most 128 references deep in a value, a limit on how deep a value can go. A value nested deeper fails with refineError and a schema_reference_depth diagnostic, and so does a loop of references at one value, which lint rejects.
A schema that fails values closed says why with an :error diagnostic, once per datafile revision, so a new datafile reports again:
| Code | Reported when |
|---|---|
schema_pattern_unsupported |
A pattern does not compile, once per pattern |
schema_mutation_error |
A mutation cannot be applied, with the error in original_error |
schema_reference_depth |
A value nests a schema's references to itself more than 128 deep |
schema_check_error |
A check in code or a lookup raises, exits or answers an error |
schema_check_error is reported once per schema and check key. Its details are schemaKey, check, the check's key, and path, the check's path as written or an empty string. A schema_not_found warning is once per key and revision too.
Featurevisor.close/1 removes event listeners and closes modules, and Featurevisor.Child.close/1 does the same for a child:
Featurevisor.close(f)Closing more than once does nothing more. An evaluation already in progress finishes with the datafile it read. Do not close a supervised instance yourself: stop its supervisor or remove it as a child. A closed handle evaluates against an empty datafile, so flags return false, variations and variables return nil, and the revision is "unknown".
The OpenFeature provider is published as a separate Hex package. Applications that only use the Featurevisor SDK do not install or compile OpenFeature or the provider code.
def deps do
[
{:featurevisor, "~> 2.0"},
{:featurevisor_openfeature, "~> 2.0"},
{:open_feature, "~> 0.1.3"}
]
endCreate a provider that owns its Featurevisor instance:
provider =
FeaturevisorOpenFeature.Provider.new(
featurevisor_options: %{datafile: datafile}
)
{:ok, provider} = OpenFeature.set_provider(provider)
client = OpenFeature.get_client()
enabled =
OpenFeature.Client.get_boolean_value(client, "checkout", false,
context: %{"targetingKey" => "user-4"}
)Pass an existing Featurevisor instance for the provider to borrow. The provider does not close it:
provider = FeaturevisorOpenFeature.Provider.new(featurevisor: f)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 official OpenFeature Elixir SDK represents evaluation context as a map. The provider accepts "targetingKey", "targeting_key", or :targeting_key and copies its string value to the configured Featurevisor targeting field.
The provider implements boolean, string, number, and map resolution. Root conditions_unmet maps to OpenFeature DISABLED. Compositions and matched overrides map to TARGETING_MATCH. Composed values are already evaluated and are not JSON decoded again. 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, and invalid datafiles use standard OpenFeature errors. Replacing an invalid datafile with a valid one recovers the provider.
The OpenFeature Elixir SDK does not currently expose provider tracking. Featurevisor modules and diagnostics continue to run inside the Featurevisor instance.
An invalid initial datafile makes provider initialization return {:error, :parse_error}, independently of log_level. A valid update restores evaluation health. Initialize or register the provider again after a failed registration. Shutdown removes provider subscriptions and closes only an owned instance.
See the OpenFeature provider guide for the shared key convention and providers for other languages.
Build the escript from this SDK repository's schemas project, so schema specs validate their values with schemas as the JavaScript CLI does:
cd schemas
FEATUREVISOR_SCHEMAS_PATH=.. mix deps.get
FEATUREVISOR_SCHEMAS_PATH=.. mix escript.buildmix escript.build at the root builds the same CLI without schemas, where each schema spec case fails asking for them.
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 Elixir 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.
./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.
Segment owners and checks evaluate through ordinary SDK gates with the selected environment, Target, fixed bucket, effective context and sticky state. Selected compiled Target segments remain authoritative. The execution protocol restores missing definitions from its compiled transitive _segments map. Attribute only segment chains can run without an environment, while dependent segments require the selected datafile. Check references are preflighted transitively before any getter runs. Synthetic segment helper features are excluded from coverage.
Linting remains a separate authoring step. The native test command does not automatically run lint.
Printed rerun commands use POSIX shell quoting. JSON reports also include raw argument arrays.
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. Elixir 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.
./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.
- SDK: featurevisor/featurevisor-elixir
- Example application: featurevisor/featurevisor-example-elixir
The aggregate evaluation reference has moved to Evaluate everything at once.
Install dependencies and run the complete local gate:
mix deps.get
make checkRun the SDK against the sibling Featurevisor example project:
make test-example-1The native tests cover runtime conformance and project integration.
Run mix test test/readme_initialization_test.exs to execute the actual initialization snippet with an isolated local datafile. The check covers evaluation, cleanup and failures, and also runs in the ordinary SDK suite and CI.
make check verifies both the base SDK and OpenFeature provider. The separate make test-example-1 target requires the sibling Featurevisor monorepo, so checks and publishing workflows run that integration after the package gate.
Before tagging a release:
make check
mix hex.publish --dry-runThe repository publishes featurevisor, featurevisor_openfeature and featurevisor_schemas with the same version. The release workflow verifies the tag, package contents, documentation, and example-1 integration, then publishes the base package before the provider and schemas packages.
Hex can only resolve the provider's exact base package dependency after the matching featurevisor release is visible. The workflow waits for that release before it performs the final provider dry run and publication.
The published Hex package includes runtime source, tests, both canonical conformance fixtures, mix.exs, the README, and the licence so its source distribution can run the same verification.
MIT © Fahad Heylaal