Current section
Files
Jump to
Current section
Files
featurevisor
README.md
README.md
# Featurevisor Elixir SDK <!-- omit in toc -->
The Featurevisor Elixir SDK evaluates flags, variations and variables in Elixir applications, from a datafile it holds in memory.
## Table of contents <!-- omit in toc -->
- [Install](#install)
- [Create an instance](#create-an-instance)
- [Supervision](#supervision)
- [Concurrency](#concurrency)
- [Context](#context)
- [Check a flag](#check-a-flag)
- [Get a variation](#get-a-variation)
- [Get a variable](#get-a-variable)
- [Typed methods](#typed-methods)
- [Composed variables](#composed-variables)
- [Default values](#default-values)
- [Evaluate everything at once](#evaluate-everything-at-once)
- [Hand results from server to client](#hand-results-from-server-to-client)
- [Sticky values](#sticky-values)
- [Update the datafile](#update-the-datafile)
- [Merge or replace](#merge-or-replace)
- [Refresh on an interval](#refresh-on-an-interval)
- [Child instances](#child-instances)
- [Events](#events)
- [`datafile_set`](#datafile_set)
- [`context_set`](#context_set)
- [`sticky_features_set`](#sticky_features_set)
- [`sticky_variables_set`](#sticky_variables_set)
- [`error`](#error)
- [Diagnostics](#diagnostics)
- [Evaluation errors](#evaluation-errors)
- [Evaluation details](#evaluation-details)
- [Evaluation reasons](#evaluation-reasons)
- [Modules](#modules)
- [Dependency evaluations](#dependency-evaluations)
- [Register a module](#register-a-module)
- [Read the datafile from a module](#read-the-datafile-from-a-module)
- [Schemas](#schemas)
- [Create a schemas instance](#create-a-schemas-instance)
- [Validate a value](#validate-a-value)
- [Read the issues](#read-the-issues)
- [Get a handle](#get-a-handle)
- [Read constraints and choices](#read-constraints-and-choices)
- [Read annotations](#read-annotations)
- [Choose the messages](#choose-the-messages)
- [Check in code](#check-in-code)
- [Options from your application](#options-from-your-application)
- [Follow the values typed so far](#follow-the-values-typed-so-far)
- [Validate on the server](#validate-on-the-server)
- [Listen for changes](#listen-for-changes)
- [Patterns](#patterns)
- [Diagnostics of a schema](#diagnostics-of-a-schema)
- [Close](#close)
- [OpenFeature](#openfeature)
- [CLI usage](#cli-usage)
- [Test](#test)
- [Benchmark](#benchmark)
- [Assess distribution](#assess-distribution)
- [GitHub repositories](#github-repositories)
- [Development](#development)
- [Publishing](#publishing)
- [License](#license)
<!-- FEATUREVISOR_DOCS_BEGIN -->
## Install
Add `featurevisor` to your dependencies in `mix.exs`:
```elixir
def deps do
[
{:featurevisor, "~> 2.0"}
]
end
```
Then run `mix deps.get`. The SDK supports Elixir 1.15 and later. Upgrading an existing application? Follow the [Elixir migration guide](https://featurevisor.com/docs/migrations/v4/elixir/).
## Create an instance
Read a [datafile](https://featurevisor.com/docs/building-datafiles/) and create an instance with it:
```elixir
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)
end
```
This example closes the instance at once. In a long running application, keep it for every evaluation, or let a [supervisor](#supervision) 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](#update-the-datafile):
| Option | Sets |
| ------------------------------------- | -------------------------------- |
| `datafile` | The datafile to evaluate |
| `context` | The [instance context](#context) |
| `sticky_features`, `sticky_variables` | [Sticky values](#sticky-values) |
| `log_level`, `on_diagnostic` | [Diagnostics](#diagnostics) |
| `modules` | [Modules](#modules) |
Create one instance and share it between processes. On a server that handles many users, give each request a [child instance](#child-instances).
### Supervision
In an OTP application, start the instance under your supervisor:
```elixir
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:
```elixir
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.
### Concurrency
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
Context is a map of [attribute](https://featurevisor.com/docs/attributes/) 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:
```elixir
f = Featurevisor.create_featurevisor(%{
datafile: datafile,
context: %{"country" => "nl"}
})
```
Add to it later with `set_context`, or replace it by passing `true`:
```elixir
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:
```elixir
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.
## Check a flag
`enabled?` reads a [flag](https://featurevisor.com/docs/flags/), as `isEnabled` does in JavaScript. Dutch users have the new `checkout`:
```elixir
context = %{
"userId" => "user-4",
"country" => "nl"
}
if Featurevisor.enabled?(f, "checkout", context) do
# show the new checkout
end
```
## Get a variation
`get_variation` returns the [variation](https://featurevisor.com/docs/variations/) of a feature, or `nil` if the feature is disabled or has none:
```elixir
case Featurevisor.get_variation(f, "pricing", context) do
"treatment" -> show_new_pricing()
_ -> show_pricing()
end
```
For `user-4` it returns `"control"`, and for `user-2` it returns `"treatment"`.
## Get a variable
`get_variable` reads a [feature variable](https://featurevisor.com/docs/variables/#feature-variables) with a feature key and a variable key. For `user-4`, the `netherlands` rule sets the buy button's label to `"Nu kopen"`:
```elixir
label = Featurevisor.get_variable(f, "buyButton", "label", context)
```
`get_global_variable` reads a [global variable](https://featurevisor.com/docs/variables/#global-variables) instead. `supportEmail` returns `"support-nl@example.com"` for `user-4`:
```elixir
email = Featurevisor.get_global_variable(f, "supportEmail", context)
```
JSON variables are decoded before they are returned.
### Typed methods
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`:
```elixir
settings = Featurevisor.get_global_variable_object(f, "checkoutSettings", context)
# %{"currency" => "EUR", "paymentMethods" => ["card"]}
```
### Composed variables
Read a [composed global variable](https://featurevisor.com/docs/variables/#compose-values) 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:
1. A sticky value for the whole variable, which skips everything after it.
2. Root `conditions`. When they miss, no source is read and no override runs. The result is `disabledValue` when supplied, otherwise `nil`, with reason `:conditions_unmet`.
3. The sources, with their own sticky values, the context and modules taking part as usual.
4. The [overrides](https://featurevisor.com/docs/variables/#override-composed-values), 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 the options for when an evaluation produces no value, such as a feature missing from the datafile:
```elixir
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.
## Evaluate everything at once
`get_feature_evaluations` evaluates every loaded feature, or only the keys you pass:
```elixir
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:
```elixir
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, and `get_variable_keys(f, "buyButton")` lists that feature's variables.
- `has_variations?(f, "pricing")` is `true` when a feature has variations, and `false` for an unknown feature.
### Hand results from server to client
Both results encode to JSON in the shape [sticky values](#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](https://featurevisor.com/docs/sdks/javascript/#hand-results-from-server-to-client) 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:
```elixir
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`:
```elixir
Featurevisor.set_sticky_features(f, %{"checkout" => %{"enabled" => false}}, true)
```
Treat the maps you pass as read only, and use a setter to change them.
## Update the datafile
`set_datafile` gives the instance a newer datafile, decoded or as JSON text:
```elixir
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](#diagnostics), with the reason in the diagnostic's `original_error`.
### Merge or replace
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 `revision` and `schemaVersion` are taken.
Pass `true` to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
```elixir
Featurevisor.set_datafile(f, datafile, true)
```
Merging is what lets one instance hold datafiles for several [targets](https://featurevisor.com/docs/targets/), loaded as each part of the application needs them. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/).
### Refresh on an interval
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`:
```elixir
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
end
```
A 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`](#datafile-set).
## Child instances
A server handles many users at once, so give each request a child with its own context:
```elixir
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_features` and `sticky_variables` as the third argument when the child needs some.
- `Featurevisor.Child` has the parent's evaluation functions, plus `get_context`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `on` and `close`.
- `Featurevisor.Child.close/1` removes the child's listeners, including the ones it registered on its parent.
## Events
`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.
### `datafile_set`
Emitted for every accepted datafile:
```elixir
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](#read-the-datafile-from-a-module), such as `schemas`.
### `context_set`
Emitted by `set_context`:
```elixir
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"}`:
```elixir
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.
### `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 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 `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:
```elixir
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.
### 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 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.
## Evaluation details
The `evaluate` functions return how a value was reached, not only the value:
```elixir
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`, `nil` for global variables
- `bucket_key` and `bucket_value`, from 0 to 100,000, and the `rule_key` that matched
- `enabled`, `variation` and `variation_value`
- `variable_key`, `variable_value`, `variable_schema` and the global variable's definition
- `variable_override_key` and `variable_override_index` when a keyed override matched, and `variable_override_path` for a nested one
- `variable_override_paths`, every override path matched in order, for [accumulating overrides](https://featurevisor.com/docs/mutations/#accumulate-overrides). The singular fields describe the last match
- `conditions` when a [root gate](https://featurevisor.com/docs/conditions/) stopped the evaluation
- `error` when evaluation failed
`Featurevisor.Evaluation.to_map/1` gives it with the camel case names JSON uses.
### Evaluation reasons
[Test specs](https://featurevisor.com/docs/testing/) 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` |
## 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. Set the callbacks you need on a `Featurevisor.Module`:
```elixir
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](#schemas) 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.
### Dependency evaluations
[Conditions](https://featurevisor.com/docs/conditions/) and [composition members](https://featurevisor.com/docs/variables/#compose-values) 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:
```elixir
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.
### Read the datafile from a module
A package, such as [schemas](#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 as `schemas`, or `nil`, and `api.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 as `input`, with `{:ok, value}`, or `:error` for 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's `before_evaluation` runs first, with `type` and `key` naming the entry, and the conditions the function answers with `Featurevisor.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
Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) 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 Hex package, released with the same version as the SDK:
```elixir
def deps do
[
{:featurevisor, "~> 2.1"},
{:featurevisor_schemas, "~> 2.1"}
]
end
```
Create it from the SDK instance, not a child. Call it `s`, as the SDK instance is `f`:
```elixir
s = FeaturevisorSchemas.create(f)
```
It holds no copy of the schemas. Every call reads the datafile `f` has now, so a [new datafile](#update-the-datafile) applies at the next validation. It and its handles are plain terms, safe to keep in application state and share between processes.
### Validate a value
```elixir
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)
end
```
- `FeaturevisorSchemas.validate(s, key, value, context: context)` returns `{:ok, value}` or `{:error, issues}`. It never coerces, fills defaults or strips keys.
- `FeaturevisorSchemas.valid?/4` returns a boolean, and `validate!/4` returns the value or raises `FeaturevisorSchemas.ValidationError` with the issues.
- `:context` is merged over the instance's, for the [conditions](https://featurevisor.com/docs/schemas/#read-the-context) a schema's rules read.
- A validation runs as the schema's own evaluation, so a [module](#modules)'s `before_evaluation` sees it, with `type` `schema` and the schema's `key`, and context the module adds reaches every condition, as it does for flags.
- `FeaturevisorSchemas.keys(s)` lists the schemas the datafile has, and `FeaturevisorSchemas.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](#diagnostics) 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.
### Read the issues
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](https://featurevisor.com/docs/schemas/#title-the-fields) carries it in `params["title"]`, and one whose rule a [mutation](https://featurevisor.com/docs/schemas/#mutations) 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](#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`:
```elixir
{:error, issues} ->
# %{form_errors: [], field_errors: %{"displayName" => ["..."]}}
conn |> put_status(422) |> json(FeaturevisorSchemas.flatten(issues))
```
### Get a handle
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:
```elixir
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](#read-annotations), each with its `name` |
| `constraints`, `field_constraints` | HTML validation attributes, by field path with `field_constraints`, [below](#read-constraints-and-choices) |
| `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](#read-annotations) |
| `with_input(handle, input, context: context)` | The same handle with an [input](#follow-the-values-typed-so-far) |
| `reads` | The fields its rules' conditions read |
| `subscribe(handle, listener)` | A call when a [new datafile](#listen-for-changes) 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.
### Read constraints and choices
`Handle.constraints/1` gives a `FeaturevisorSchemas.Constraints`, named after HTML attributes:
```elixir
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 template
```
- `required`, when the key is required, so an input left empty fails
- `min_length` and `max_length`, from the same rules on a string
- `min` and `max`, from `minimum` and `maximum` on a number
- `step` of 1, for an `integer`
- `multiple`, 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](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `Handle.option/2` finds one, for showing a value saved earlier:
```elixir
country = Handle.field(sign_up, "country")
Handle.options(country) # nl, de and be
Handle.option(country, "nl").title # "Netherlands"
Handle.option(country, "fr") # nil
```
A 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.
### Read annotations
A handle's `annotations` are its node's own, and `fields` gives an object's fields in its `order`:
```elixir
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](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). 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](https://featurevisor.com/docs/schemas/#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. `Handle.with_input/3` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen:
```elixir
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 # true
```
Every 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.
### Choose the messages
`:messages` on `create` words every schema's issues, per code, as text with placeholders or a function of the params and the `FeaturevisorSchemas.MessageInfo`:
```elixir
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:
1. A check in code's own message, then the form's.
2. The schema's own, and then the `message` of its [issues](https://featurevisor.com/docs/schemas/#issues) entry.
3. The application's, from `create`.
4. 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.
### Check in code
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:
```elixir
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.CheckInfo` with the `input` and the `context`. It returns `true` when the value passes.
- `input` is the whole value on the schema's handle, and the field's own value on a field's handle, such as `Handle.field(sign_up, "displayName")`. A field's handle from [`with_input`](#follow-the-values-typed-so-far) is 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 `refine` and the `refine` param `"nameAvailable"`, with the field's title. A check that returns `{:error, reason}`, raises or exits gives `refineError`, and validation fails closed, with a `schema_check_error` [diagnostic](#diagnostics) 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.
### Options from your application
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:
```elixir
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 Amersfoort
```
- `search` returns `{:ok, choices}`, each a value or a map with a `"value"`. A handle's `search` passes it the values given to `with_input`, so the cities follow the country. `Handle.searchable?/1` says whether a field has one.
- `lookup` returns what the source says about a value, `{:ok, fields}` when found, or `:error` when there is none. A handle's `lookup` returns the schema's own choice first, then the source's.
- Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by its message. A lookup that returns `{:error, reason}`, raises or exits gives `refineError` and `schema_check_error`, as a check does.
### Validate on the server
`validate` checks a request before it reaches your code:
```elixir
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
end
```
A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
### Listen for changes
`Handle.subscribe/2` calls back when a new datafile changes the schema, and returns a function that stops it:
```elixir
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.
### Patterns
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.
### Diagnostics of a schema
A schema that fails values closed says why with an `:error` [diagnostic](#diagnostics), 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](#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.
## Close
`Featurevisor.close/1` removes event listeners and closes modules, and `Featurevisor.Child.close/1` does the same for a child:
```elixir
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"`.
## OpenFeature
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.
```elixir
def deps do
[
{:featurevisor, "~> 2.0"},
{:featurevisor_openfeature, "~> 2.0"},
{:open_feature, "~> 0.1.3"}
]
end
```
Create a provider that owns its Featurevisor instance:
```elixir
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:
```elixir
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](https://featurevisor.com/docs/sdks/openfeature/) for the shared key convention and providers for other languages.
## CLI usage
Build the escript from this SDK repository's `schemas` project, so schema specs validate their values with [schemas](#schemas) as the JavaScript CLI does:
```bash
cd schemas
FEATUREVISOR_SCHEMAS_PATH=.. mix deps.get
FEATUREVISOR_SCHEMAS_PATH=.. mix escript.build
```
`mix 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:
```bash
npm install --save-dev @featurevisor/cli@^4.0.0
```
Project 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.
### Test
```bash
./featurevisor test \
--project-directory-path=/path/to/featurevisor-project \
--only-failures
```
See [Testing](https://featurevisor.com/docs/testing/) for authoring specs and [Checks](https://featurevisor.com/docs/testing/#checks) for check syntax and operators.
Useful test options:
- `--key-pattern=<pattern>` and `--assertion-pattern=<pattern>` filter tests.
- `--entity-type=scenario` selects scenarios, and `--entity-type=schema` schema specs. `--set=<set>` selects one project set. Omitting `--set` runs all sets.
- `--case=<id>` reruns one expanded case. Copy the opaque ID or rerun command from a failure report.
- `--json --pretty` produces an indented JSON report.
- `--coverage` reports observed rule and override selections. `--uncovered` lists features and global variables without associated specs.
- `--only-failures`, `--quiet`, `--verbose` and `--show-datafile` control 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.
### 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. Elixir evaluates them. Replace `checkout` with a feature defined in your project.
```bash
./featurevisor benchmark \
--project-directory-path=/path/to/featurevisor-project \
--feature=checkout \
--context='{"country":"nl"}' \
--n=1000
```
Use `--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](https://featurevisor.com/docs/cli/#benchmarking).
### Assess distribution
```bash
./featurevisor assess-distribution \
--project-directory-path=/path/to/featurevisor-project \
--feature=checkout \
--populate-uuid=userId \
--n=1000
```
Repeat `--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](https://featurevisor.com/docs/cli/#assess-distribution).
## GitHub repositories
- SDK: [featurevisor/featurevisor-elixir](https://github.com/featurevisor/featurevisor-elixir)
- Example application: [featurevisor/featurevisor-example-elixir](https://github.com/featurevisor/featurevisor-example-elixir)
<!-- FEATUREVISOR_DOCS_END -->
<a id="getting-all-evaluations"></a>
<a id="getting-evaluations"></a>
The aggregate evaluation reference has moved to [Evaluate everything at once](#evaluate-everything-at-once).
## Development
Install dependencies and run the complete local gate:
```sh
mix deps.get
make check
```
Run the SDK against the sibling Featurevisor example project:
```sh
make test-example-1
```
The 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.
## Publishing
Before tagging a release:
```sh
make check
mix hex.publish --dry-run
```
The 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.
## License
MIT © [Fahad Heylaal](https://fahad19.com)