Featurevisor Elixir SDK <!-- omit in toc -->

Copy Markdown View Source

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

Add featurevisor to your dependencies in mix.exs:

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.

Create an instance

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)
end

This 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:

OptionSets
datafileThe datafile to evaluate
contextThe instance context
sticky_features, sticky_variablesSticky values
log_level, on_diagnosticDiagnostics
modulesModules

Create one instance and share it between processes. On a server that handles many users, give each request a child instance.

Supervision

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.

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 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.

Check a flag

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
end

Get a variation

get_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()
end

For user-4 it returns "control", and for user-2 it returns "treatment".

Get a variable

get_variable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":

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.

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".

MethodReturns
get_variable_booleanboolean()
get_variable_stringString.t()
get_variable_integerinteger()
get_variable_numbernumber(), for a variable of type number or double
get_variable_arraylist()
get_variable_objectmap()
get_variable_jsonthe 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"]}

Composed variables

Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as get_global_variable_string for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and 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, 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:

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:

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, 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 take. A server can evaluate once per request and pass the results to its client, so the first render matches what the server saw. The JavaScript SDK's sticky values read them in a browser.

Sticky values

Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:

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.

Update the datafile

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.

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:

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.

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:

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.

Child instances

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_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:

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.

context_set

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.

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:

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:

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:

FieldValue
type:flag
feature_key"checkout"
reason:rule
bucket_key"user-4.checkout"
bucket_value89312
rule_key"netherlands"
enabledtrue

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. The singular fields describe the last match
  • conditions when a root gate 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 can assert them, written as JSON writes them, without the colon.

ReasonMeaning
:feature_not_foundThe feature is not in the datafile
:disabledThe feature is disabled
:no_variationsA variation was requested from a feature without variations
:variation_disabledA disabled feature returned its disabledVariationValue
:variable_not_foundThe feature variable or global variable is not in the datafile
:variable_defaultThe variable returned its default value
:variable_composedA global variable read its composition sources with no override match
:variable_disabledA disabled feature returned the variable's disabled value
:variable_override_variationA feature variable override matched inside a variation
:variable_override_ruleA feature variable override or global variable override matched
:conditions_unmetRoot conditions did not match. See conditions
:no_matchNo rule, allocation or variation matched, or the bucket fell outside the rollout
:forcedA force entry supplied the result
:stickyA sticky value supplied the result
:ruleA matching rule supplied the result
:allocatedBucketing allocated the result
:errorEvaluation 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:

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.

Dependency evaluations

Conditions and composition members are evaluated through modules too. Their options carry dependency_of, naming the requesting evaluation, and dependency_purpose, :condition for an eligibility check and :composition for a consumed member value. Direct calls have neither.

When tracking consumed evaluations, skip eligibility checks, not every read with dependency_of, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.

Register a module

Pass modules when creating the instance, or add them later:

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, 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 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:

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:

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.

Validate a value

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 a schema's rules read.
  • A validation runs as the schema's own evaluation, so a module'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 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 carries it in params["title"], and one whose rule a mutation set names it in mutation.

CodeRaised when
typeThe value has another type
const, enumThe value is not one allowed
minimum, maximumA number is out of range
minLength, maxLengthA string is too short or too long
pattern, formatA string has the wrong shape
minItems, maxItemsAn array has too few or too many items
uniqueItemsAn array repeats an item
required, additionalPropertiesA key is missing, or there is one it does not allow
oneOfNo branch matches, or more than one does
refineAn issues entry matches, or a check in code fails
refineErrorA check in code fails with an error, or the schema cannot be applied
schemaNotFoundThe 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))

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:

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.

FunctionWhat 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")
fieldsAn object's fields' handles, in order, each with its name
constraints, field_constraintsHTML 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_asWhat its rules say the field renders as, such as "select"
annotationsIts annotations
with_input(handle, input, context: context)The same handle with an input
readsThe fields its rules' conditions read
subscribe(handle, listener)A call when a new datafile changes the schema
key, path, nameThe 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:

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 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")        # 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:

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.

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 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    # 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:

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 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:

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 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 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:

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, 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:

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:

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, once per datafile revision, so a new datafile reports again:

CodeReported when
schema_pattern_unsupportedA pattern does not compile, once per pattern
schema_mutation_errorA mutation cannot be applied, with the error in original_error
schema_reference_depthA value nests a schema's references to itself more than 128 deep
schema_check_errorA 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:

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.

def deps do
  [
    {:featurevisor, "~> 2.0"},
    {:featurevisor_openfeature, "~> 2.0"},
    {:open_feature, "~> 0.1.3"}
  ]
end

Create 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 keyFeaturevisor evaluation
checkoutFlag for feature checkout
checkout:variationVariation for feature checkout
buyButton:labelVariable title inside feature checkout
variable:supportEmailGlobal 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.

CLI usage

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.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:

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

./featurevisor test \
  --project-directory-path=/path/to/featurevisor-project \
  --only-failures

See 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=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.

./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.

Assess distribution

./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.

GitHub repositories

The aggregate evaluation reference has moved to Evaluate everything at once.

Development

Install dependencies and run the complete local gate:

mix deps.get
make check

Run the SDK against the sibling Featurevisor example project:

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:

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