Featurevisor

Use cases

Validating data

Validate the data your services receive against schemas in your Featurevisor project, so a limit or a format changes in a pull request rather than a release. This guide follows an order service from its first schema to a rule rolled out to a quarter of its users.

Experimental

@featurevisor/schemas is experimental, so its API may change in a minor release.

How it works

  • A schema describes the data, and a target delivers it in the service's datafile, the way it delivers flags.
  • The service validates each request with @featurevisor/schemas, against the datafile it already holds, so a merged change reaches it at its next refresh.
  • The rules can read the request's context, segments, flags and global variables, so they change by market, by plan or by percentage like any feature.

Describe the order

An order has a country and postcode to deliver to, and one to ten products, each a code and a quantity. A phone number and a coupon code are optional:

schemas/order.yml
description: An order placed at checkout
type: object
properties:
deliveryCountry:
type: string
enum: [nl, de]
postcode:
type: string
phone:
type: string
couponCode:
type: string
products:
type: array
minItems: 1
maxItems: 10
items:
type: object
properties:
sku:
type: string
pattern: ^[A-Z0-9-]+$
quantity:
type: integer
minimum: 1
maximum: 9
required: [sku, quantity]
required: [deliveryCountry, postcode, products]

The keywords are the ones variables use, as Schemas lists them. An object with properties rejects any key it does not list, so a request cannot slip extra fields past the service.

Deliver it to the service

A target for the order service delivers the schema by key. The service evaluates no flags of its own, so the target leaves features and global variables out, and it renders no forms, so it leaves annotations out too:

targets/order-service.yml
description: Order service
excludeFeatures: "*"
excludeVariables: "*"
includeSchemas:
- order
includeAnnotations: false

Lint, test and build as usual, and deploy datafiles/featurevisor-order-service.json as you deploy any datafile. A segment, feature or global variable that the schema's rules read later comes along into it, whatever the target excludes, as Targets explains.

Validate each request

Create one SDK instance for the server, with a schemas instance from it, and refresh its datafile as you would for flags:

src/featurevisor.js
import { createFeaturevisor } from '@featurevisor/sdk'
import { createSchemas } from '@featurevisor/schemas'
const response = await fetch(
'https://cdn.example.com/featurevisor-order-service.json',
)
export const f = createFeaturevisor({
datafile: await response.json(),
})
export const s = createSchemas(f)

s.parse returns the request body as it came, never changed, or throws a SchemaError, whose flattened holds the issues by field. One handler answers every bad request:

app/api/orders/route.js
import { SchemaError } from '@featurevisor/schemas'
import { s } from '../../../src/featurevisor'
export async function POST(request) {
try {
const order = s.parse('order', await request.json())
return Response.json(await placeOrder(order))
} catch (error) {
if (error instanceof SchemaError) {
return Response.json(error.flattened, { status: 400 })
}
throw error
}
}

An order whose product has a lowercase code and a quantity of 12 gets a 400 that names both fields:

{
"formErrors": [],
"fieldErrors": {
"products.0.sku": [
"Value at \"products.0.sku\" does not match the expected pattern."
],
"products.0.quantity": [
"Value at \"products.0.quantity\" must be at most 9 (got 12)."
]
}
}

A tRPC procedure or a Hono route can take the schema's handle, s.get('order'), in place of the handler above, as the JavaScript SDK shows. The router validates with the instance's context. That is enough while the rules read only the order, but once a rule reads the plan, as largerOrders does below, validate in the handler with the request's context.

Check the postcode per market

A Dutch postcode and a German one have different shapes. A mutation changes a rule when its conditions match, and input reads a field of the order itself:

schemas/order.yml
# ...
mutations:
- key: dutchPostcode
conditions:
- input: deliveryCountry
operator: equals
value: nl
mutate:
properties.postcode.pattern: ^[1-9][0-9]{3} ?[A-Z]{2}$
properties.postcode.messages:
pattern: Enter a Dutch postcode, such as 1011 AB
- key: germanPostcode
conditions:
- input: deliveryCountry
operator: equals
value: de
mutate:
properties.postcode.pattern: ^[0-9]{5}$
properties.postcode.messages:
pattern: Enter a German postcode, such as 10115
# ...
mutations:
- key: dutchPostcode
conditions: input('deliveryCountry') == 'nl'
mutate:
properties.postcode.pattern: ^[1-9][0-9]{3} ?[A-Z]{2}$
properties.postcode.messages:
pattern: Enter a Dutch postcode, such as 1011 AB
- key: germanPostcode
conditions: input('deliveryCountry') == 'de'
mutate:
properties.postcode.pattern: ^[0-9]{5}$
properties.postcode.messages:
pattern: Enter a German postcode, such as 10115
deliveryCountrypostcodeIssues
nl1011 ABNone
de10115None
de1011 ABEnter a German postcode, such as 10115

The issue names the mutation that set its rule, mutation: germanPostcode, so a log can say why an order failed. Adding a market is one pull request: a value in the enum and a mutation beside these.

Allow more for paying accounts

A rule can depend on who is asking, through the same conditions features use. Paying accounts, the payingAccounts segment from Segments, may order up to 50 products:

schemas/order.yml
# ...
mutations:
# ...
- key: largerOrders
conditions: payingAccounts
mutate:
properties.products.maxItems: 50

A server handles many users with one SDK instance, so give each request its own context as the third argument:

const session = await getSession(request)
const context = {
userId: session.userId,
plan: session.plan,
}
const order = s.parse('order', await request.json(), context)
planAn order of 20 products
freemaxItems, at most 10
paidValid

Ask your database

Whether a coupon code exists is in your database, not in the schema. Give the handle a check in code, with a key, the field it checks and a message:

app/api/orders/route.js
import { SchemaError } from '@featurevisor/schemas'
import { s } from '../../../src/featurevisor'
const order = s.get('order', {
refine: [
{
key: 'couponExists',
path: 'couponCode',
check: async (couponCode) => db.coupons.exists(couponCode),
message: 'That coupon code does not exist',
},
],
})
export async function POST(request) {
const session = await getSession(request)
const context = {
userId: session.userId,
plan: session.plan,
}
try {
const value = await order.parse(await request.json(), { context })
return Response.json(await placeOrder(value))
} catch (error) {
if (error instanceof SchemaError) {
return Response.json(error.flattened, { status: 400 })
}
throw error
}
}

The check runs after the schema's own rules, and waits only for issues at or inside its path, couponCode, or in the fields its reads names. A coupon code of the wrong type never reaches the database, but an order with a lowercase sku, which fails anyway, still asks it about the coupon. Name products in the check's reads to make it wait for them too. A code that does not exist answers { "couponCode": ["That coupon code does not exist"] } under fieldErrors. Since the check is asynchronous, so is parse, and a handle takes the context inside its options.

Roll out a stricter rule

Couriers want a phone number for every order, but a new required field can lose orders. Roll it out like any feature, to a quarter of users first, and watch what happens:

features/requirePhone.yml
description: Orders need a phone number for the courier
bucketBy: userId
rules:
- key: everyone
conditions: "*"
percentage: 25
schemas/order.yml
# ...
mutations:
# ...
- key: requirePhone
conditions:
- feature: requirePhone
mutate:
required:appendUnique: phone
# ...
mutations:
# ...
- key: requirePhone
conditions: feature('requirePhone')
mutate:
required:appendUnique: phone
UserBucketAn order without a phone
user-181.5Valid
user-239.3Valid
user-96.0required at phone, mutation: requirePhone

The flag reaches the service's datafile because the schema reads it, even though the target excludes features. Raise its percentage to reach more users. Once everyone has it, add phone to the schema's required, then remove the mutation and the flag. A global variable can serve as a kill switch the same way, relaxing a rule for everyone during an incident.

Test it

With every rule above, schemas/order.yml reads:

schemas/order.yml
description: An order placed at checkout
type: object
properties:
deliveryCountry:
type: string
enum: [nl, de]
postcode:
type: string
phone:
type: string
couponCode:
type: string
products:
type: array
minItems: 1
maxItems: 10
items:
type: object
properties:
sku:
type: string
pattern: ^[A-Z0-9-]+$
quantity:
type: integer
minimum: 1
maximum: 9
required: [sku, quantity]
required: [deliveryCountry, postcode, products]
mutations:
- key: dutchPostcode
conditions:
- input: deliveryCountry
operator: equals
value: nl
mutate:
properties.postcode.pattern: ^[1-9][0-9]{3} ?[A-Z]{2}$
properties.postcode.messages:
pattern: Enter a Dutch postcode, such as 1011 AB
- key: germanPostcode
conditions:
- input: deliveryCountry
operator: equals
value: de
mutate:
properties.postcode.pattern: ^[0-9]{5}$
properties.postcode.messages:
pattern: Enter a German postcode, such as 10115
- key: largerOrders
conditions: payingAccounts
mutate:
properties.products.maxItems: 50
- key: requirePhone
conditions:
- feature: requirePhone
mutate:
required:appendUnique: phone
description: An order placed at checkout
type: object
properties:
deliveryCountry:
type: string
enum: [nl, de]
postcode:
type: string
phone:
type: string
couponCode:
type: string
products:
type: array
minItems: 1
maxItems: 10
items:
type: object
properties:
sku:
type: string
pattern: ^[A-Z0-9-]+$
quantity:
type: integer
minimum: 1
maximum: 9
required: [sku, quantity]
required: [deliveryCountry, postcode, products]
mutations:
- key: dutchPostcode
conditions: input('deliveryCountry') == 'nl'
mutate:
properties.postcode.pattern: ^[1-9][0-9]{3} ?[A-Z]{2}$
properties.postcode.messages:
pattern: Enter a Dutch postcode, such as 1011 AB
- key: germanPostcode
conditions: input('deliveryCountry') == 'de'
mutate:
properties.postcode.pattern: ^[0-9]{5}$
properties.postcode.messages:
pattern: Enter a German postcode, such as 10115
- key: largerOrders
conditions: payingAccounts
mutate:
properties.products.maxItems: 50
- key: requirePhone
conditions: feature('requirePhone')
mutate:
required:appendUnique: phone

A spec states what the service accepts, with the context each rule reads:

tests/schemas/order.spec.yml
schema: order
assertions:
- description: A Dutch order is accepted
context:
userId: user-1
value:
deliveryCountry: nl
postcode: 1011 AB
products:
- sku: BOOK-1
quantity: 2
expectedToBeValid: true
- description: A German order needs a German postcode
context:
userId: user-1
value:
deliveryCountry: de
postcode: 1011 AB
products:
- sku: BOOK-1
quantity: 2
expectedIssues:
- path: [postcode]
code: pattern
mutation: germanPostcode
- description: The rollout asks user-9 for a phone
context:
userId: user-9
value:
deliveryCountry: nl
postcode: 1011 AB
products:
- sku: BOOK-1
quantity: 2
expectedIssues:
- path: [phone]
code: required
mutation: requirePhone
Command
npx featurevisor test --entity-type=schema

Testing covers schema specs in full.

Change it safely

A delivered schema is a contract with every service that loads it, and it changes without them being deployed again. Narrowing it, such as a lower limit, only rejects more requests. Widening it lets through values that code written against its old types may not expect, so diff warns before you merge:

Command
npx featurevisor diff
Output
Warning: Schema "order" now accepts values it rejected before: deliveryCountry.enum gains "be". Target "order-service" delivers it to applications, whose code may not expect them. Regenerate their types and release them before this change.

Regenerate the service's types with code generation, for its target alone:

Command
npx featurevisor generate-code \
--language typescript \
--out-dir ./src/generated \
--target=order-service \
--schemas

Release the service with its new types first, then merge the schema change. In a project with environments, a change can reach staging a pull request before production, as Environments shows.

Previous
Remote configuration