Scrusted-yaml
Business rules in YAML, computed in Rust, changed while the server runs.
Rate limits, validation rules, permissions, prices, order states: keep them in files you can read and change, and let your Rust application run them.
See the examples side by side → Rust code today, the rule file, and the Rust code that reads it, with a live reload simulation.
- Live reload. Edit a rule file on a running server. The change goes live only after it validates and its tests pass, in one atomic swap; a broken change is refused and the previous version keeps serving.
- Built for Laravel Rust.
scrusted-yaml-laravelreadsconfig/*.ymllive in development and compiles them into the binary for production, where a broken rule failscargo build. - Typed results. A file resolves into your own
serdestructs. A change that no longer fits the struct is refused at reload, not discovered on a request. - Fast. Formulas are parsed once. Resolving is synchronous,
Send + Sync, and takes microseconds, so it runs inside a request handler. - Safe to edit. The validator refuses the formula mistakes that silently give a wrong answer, and evaluation has limits on steps, depth and time.
- Same files as scripted-yaml, the TypeScript library. One conformance suite of more than 4,000 cases checks that both give the same results.
- Self-contained files, with
$varsfor inputs,$schemafor structure,$testsfor examples, and$extendsfor patches and templates (state machines, menus, forms). - Skills for coding agents:
scrusted-yaml skill --installteaches an agent to write rule files, move Rust logic into them and build an editor for them.
Application code and business rules
Application code reads requests, talks to the database and renders pages.
Along the way it makes decisions: how many requests a free team gets, who may
publish a post, when an order can ship. Written in Rust, each decision is a
match or an if deep in a handler, and changing it means a pull request, a
build and a deploy.
Business rules take those decisions out into a file. The code keeps the types, the I/O and the wiring; the file keeps the numbers, the conditions and the texts. Someone who does not write Rust can read the file, and change it while the server runs.
Why YAML?
YAML is readable and compact. On top of it, scripted-yaml adds a little:
- formulas in FEEL, the expression language of decision tables:
per_minute!: if vars.plan = "pro" then 600 else 60 {{ }}in text:subject: Invoice #{{ vars.invoice.number }} is paid$varsto declare the inputs a file needs$schema(inline) or$dsl(shared) to check its structure$if!,$each!,$whento make parts of it conditional- functions the application passes in, and ten built-in text functions
Brief
Rate limits per plan
The limits live in a middleware. Nobody outside the backend team sees them, and raising the free plan's limit takes a deploy:
async
Write them in a file instead:
# rules/rate-limits.yml
$vars:
plan:
plans:
free:
per_minute: 60
pro:
per_minute: 600
enterprise:
per_minute: 3000
per_minute!: dig(plans, vars.plan).per_minute
The middleware reads the version being served now:
async
A free team floods the API during a launch. Lower its limit on the running server, and the next request reads the new value:
plans:
free:
- per_minute: 60
+ per_minute: 30
Install
[]
= { = "0.2", = ["live"] } # with live reload
# scrusted-yaml = "0.2" # validate, load, resolve only
= { = "1", = ["derive"] }
The command line, to validate and test rule files in CI:
In a Laravel Rust application, use
scrusted-yaml-laravel instead: a service provider that reads
config/*.yml live in development and compiles the files into the binary for production
(below).
The FEEL evaluator alone is the crate scrusted-feel.
When not to use it
- Complex logic. Formulas are for rules a person reads and changes: thresholds, conditions, visibility, prices. Algorithms, I/O and anything async stay in Rust.
- Untrusted authors. A rule file can call the functions and markers your application registers. Let the people who own the rules edit them, not the users of your application.
- Static config. If nothing in a file is computed and nothing changes at runtime, plain
serdeconfig is simpler.
Quick start
use ;
let rules = from_pairs;
let scrusted = builder.files.build?;
let document = scrusted.load?;
let limits: Limits = document.resolve_as?;
assert_eq!;
# Ok::
In an application, read the files from a folder with DiskFiles::new("rules/"),
and serve them with live reload (next section).
Live reload
This is the reason to use the library on a server. With the feature live, the
files under a folder are loaded at start and watched while the application runs.
use ;
use ;
pub static SCRUSTED: = new;
When a file changes, it goes through these gates, in order:
- Read the new text.
- Parse the YAML and every formula.
- Validate: names, schema, the refused formula mistakes.
- Dependents: every file that
$extends,$imports or$dsls it loads again. - Tests: the
$testsof every file in the set pass. - Shape: each file registered with
.shape::<T>()still deserializes intoT. - Swap: the new set is published with one atomic pointer write.
If a gate fails, nothing is published: the previous version keeps serving, and the problems, with file and line, go to your listener.
SCRUSTED.on_reload;
- No request sees half a change.
SCRUSTED.snapshot()gives one generation: a request that reads several files reads them all from the same version, and a request that started on version 6 finishes on 6. - No lock on the request path. Reading the live version is one atomic load; resolving is in memory.
- Admin pages.
status()lists each file's live version and its last refused change;rollback(file)publishes the previous good version through the same gates;reload_now()re-reads everything, for a deploy hook. - Files on disk are watched, debounced (150 ms by default). Files in a database, or any other
impl Files, are polled with.poll(Duration::from_secs(5)); with several servers, each one polls and runs the gates itself.
| Change | Takes effect |
|---|---|
| a number, threshold, text, condition | live |
| an item added to a table or list (a plan, a menu item, a transition) | live, when Rust reads it through a field it already has |
| a new field your Rust struct must read | deploy: the struct changes |
| a new marker or host function | deploy: a file can only call what the app passes |
Laravel Rust
scrusted-yaml-laravel wires all of this into a Laravel Rust
application with one service provider and one switch:
providers.add;
RULES_MODE |
Rules come from |
|---|---|
auto (default) |
live when APP_ENV=local, compiled otherwise |
live |
config/*.yml on disk, reloaded on save through the gates above |
compiled |
built into the binary; compiled! runs the same checks and $tests during cargo build, so a broken rule fails the build |
Handlers take Inject<Rules>, and laravel rules:status and laravel rules:test come with
it. See its README.
Examples
The examples use Laravel for Rust: its middleware, policies, notifications and workflows. Scrusted-yaml knows no framework; the same calls work in an axum or actix handler. Each example shows the rule file and the Rust code that reads it, and they are ordered by how much a team usually gains from moving the rule out of the code.
All of them read the live library from the section above, SCRUSTED.
1. Rate limits per plan and route
The full version of the brief above: limits per plan, a smaller share for expensive routes, and no daily cap for enterprise.
# rules/rate-limits.yml
$vars:
plan:
route:
plans:
free:
per_minute: 60
per_day: 1000
pro:
per_minute: 600
per_day: 50000
enterprise:
per_minute: 3000
per_day: null
routes:
uploads:
share: 6
search:
share: 2
limit!: dig(plans, vars.plan)
route_rule!: |
if vars.route = null then null
else dig(routes, vars.route)
per_minute!: |
if route_rule = null then limit.per_minute
else floor(limit.per_minute / route_rule.share)
per_day!: limit.per_day
bucket!: if vars.route = null then "api" else vars.route
async
A free team uploading gets 10 per minute in the bucket uploads; an enterprise
team gets 3,000 per minute and no daily cap.
2. Validation rules that depend on plan and tenant
The input struct keeps the types and the fixed checks. Which fields are required, and their limits, depend on the plan and the tenant, so they live in the file.
# rules/validation/signup.yml
$vars:
input:
tenant:
team!: vars.input.plan = "team"
fields:
- id: company
required!: team
max: 120
- id: seats
required!: team
min: 2
max!: if vars.tenant.tier = "enterprise" then 500 else 50
- id: vat_id
required!: vars.input.country in vars.tenant.vat_countries
pattern: '^[A-Z]{2}[0-9A-Z]{8,12}$'
unique and exists stay in Rust: they query the database. The same file can
also draw the form in the browser, with scripted-yaml.
3. Authorization policies
The policy keeps its methods, so user.authorize(PostPolicy::update, &post)
still fails to compile on a typo. The answer comes from the file.
# rules/policies/posts.yml
$vars:
user:
post:
signed_in!: vars.user != null
is_owner!: signed_in and vars.user.id = vars.post.user_id
is_editor!: signed_in and vars.user.role in ["editor", "admin"]
abilities:
update:
$value!: is_owner or is_editor
message: Only the author or an editor can change this post.
publish:
$value!: is_editor and vars.post.status = "review"
message: An editor publishes a post once it is in review.
delete:
$value!: signed_in and vars.user.role = "admin"
message: Only admins delete posts.
Anything other than true denies. Give policy files $tests, so a reload
that would open a door is refused.
4. Prices, discounts and shipping options
# rules/shop/discounts.yml
$vars:
cart:
customer:
is_vip!: |
count(vars.customer.orders) >= 10
or "vip" in vars.customer.tags
discount:
loyalty!: if is_vip then vars.cart.subtotal * 0.05 else 0
volume!: if vars.cart.subtotal >= 200 then 15 else 0
$value!: max(loyalty, volume)
note: The bigger of the two discounts applies.
to_pay!: vars.cart.subtotal - discount
shipping:
- name: Standard
price!: if to_pay >= 50 then 0 else 4.90
- name: Express
price: 12.90
$if!: is_vip
message: You pay {{ to_pay }} and save {{ discount }}.
async
A VIP cart of 240 gets the volume discount of 15 (more than the loyalty 12), pays 225, and is offered Express. Numbers are decimals: money adds up exactly.
5. Order processing as a state machine
Built on the bundled template scripted-yaml/state-machine. Each state lists the
events it takes and where they lead; a guard is a formula that gives the next state,
or null while the event is not allowed. on names the job to dispatch on entering a
state, and _ the one for every move. The jobs come from functions the file
declares and the application passes, so validate refuses a name nobody declared.
# rules/orders/order-states.yml
$extends: scripted-yaml/state-machine
$vars:
order:
about: total, in_stock
# The application passes these; each returns the job to dispatch.
$functions:
SendReceipt(order):
RefundPayment(order):
WriteAudit(order, event):
# Each state lists the events it takes and where they lead.
# A formula is a guard: null means "not now".
states:
draft:
pay!: if vars.order.total > 0 then "paid" else null
cancel: cancelled
paid:
ship!: if vars.order.in_stock then "shipped" else null
cancel: refunded
shipped:
deliver: delivered
return: refunded
delivered:
cancelled:
refunded:
# The job to dispatch on entering a state; `_` on every move.
on:
paid!: SendReceipt(vars.order)
refunded!: RefundPayment(vars.order)
_!: WriteAudit(vars.order, vars.event)
// each declared function builds a job and does nothing else: resolving is synchronous
pub async
// the buttons on the order page: the same file, without an event
Job::value wraps a job as a Value::Host, so it comes back in effects as itself.
Shipping a paid order in stock moves it to shipped and dispatches only WriteAudit.
A new state needs a variant in the Rust enum first: the shape gate refuses a
file that names one Rust does not know.
6. Which channels a notification takes
channels() runs once per recipient, is synchronous and cannot query the
database. Resolving a loaded file has the same shape.
# rules/notifications/invoice-paid.yml
$vars:
user:
invoice:
large!: vars.invoice.amount >= 1000
channels:
- name: mail
- name: sms
$if!: |
vars.user.phone != null
and (large or vars.user.sms_receipts)
subject: 'Invoice #{{ vars.invoice.number }} is paid'
sms: 'Paid: {{ vars.invoice.amount }} {{ vars.invoice.currency }}. Thank you!'
An invoice of 1,200 EUR to a user with a phone goes by mail and SMS, with the
subject Invoice #1042 is paid.
7. Throttling sign-in and one-time codes
# rules/attempts.yml
$vars:
action:
failures_today:
actions:
login:
per_minute: 5
otp:
per_minute: 3
password_reset:
per_minute: 2
per_minute!: dig(actions, vars.action).per_minute
captcha!: vars.failures_today >= 5
locked!: vars.failures_today >= 20
message!: |
if locked
then "Too many failed attempts today. Reset your password to sign in."
else "Too many attempts. Try again in a minute."
async
During an attack, lower the attempts or the captcha threshold without a deploy.
8. A navigation menu for each user
Built on the bundled template scripted-yaml/navigation-ui, which also
computes the active item, the breadcrumbs and the sitemap.
# rules/ui/navigation.yml
$extends: scripted-yaml/navigation-ui
$vars:
user:
features:
$replace:
menu:
- label: Dashboard
path: /
- label: Projects
path: /projects
- label: Reports
path: /reports
$if!: vars.features.reports
- label: Admin
$if!: vars.user.role = "admin"
items:
- label: Users
path: /admin/users
- label: Billing
path: /admin/billing
$if!: vars.user.owner
// shared Inertia props, the same for every page
At /admin/users, an admin who is not the owner sees Dashboard, Projects,
Reports and Admin with Users only, and the breadcrumbs Admin › Users.
9. Decisions inside a durable workflow
A workflow's handle replays from the top and must make the same decisions
every time. Resolve the rule file inside a step: the step's result is recorded,
so a run in flight keeps the decision it made, even after the file changes.
The order of steps stays in Rust.
# rules/workflows/onboarding.yml
$vars:
user:
active:
nudge_after_days!: if vars.user.plan = "trial" then 2 else 5
send_nudge!: vars.active = false
nudge_template!: |
if vars.user.plan = "trial" then "trial-ending"
else "getting-started"
assign_manager!: vars.user.plan = "enterprise"
The file language
| You write | It means |
|---|---|
key: value |
data; only {{ formula }} inside text is computed |
key!: formula |
the value is one formula |
key!name: value |
the value goes to the application's marker function name |
$keyword: |
a word of the language: $vars, $value, $if!, $schema, … |
Formulas
Formulas are FEEL, the expression language of DMN.
vars.method = "GET" equals is ONE =; text in double quotes
a and b a or b not(a) not is a function
vars.NAME != null "is set": an unset variable is null
if a then b else c else is required
x in ["a", "b"] day between 1 and 5 one of; within
cart.items[price > 10].name pick items; a bare name is a field of the item
count(list) sum(list) list[1] list[-1] lists count from 1
for item in list return item.price * 2 one result per item
some item in list satisfies item.price > 5 also: every
{ base: 10, total: base * 2 }.total named steps
A key is computed only when something reads it, once per resolve, and the order
of keys means nothing. A path names a key of the file: discount.loyalty, or an
item of a list by its id: stages.explore.when.
The built-in functions are FEEL's (string join, starts with, substring,
round half up, date and time, …) and ten one-word text functions:
trim, lowercase, uppercase, capitalize, slug, snakecase,
kebabcase, camelcase, pascalcase, titlecase; and dig(map, key), the
one-word get value(map, key) for a key known only at run time.
The validator refuses forms that would silently give a wrong answer, and says how to write them:
| Written | Message |
|---|---|
a == b |
equals is one = |
not x |
not is a function: write not(x) |
x in [1, 2] and y |
put the in test in brackets: (x in [..]) and y |
a && b, !a |
write and, or, not(a) |
c ? a : b |
write if c then a else b |
'text' |
text is in double quotes |
if a then b |
if needs an else |
list[0] |
positions start at 1 |
list[not(x)] |
compare it: [not(x) = true] |
Keywords
$vars: # the inputs; required unless optional or a default
cart:
coupon:
TOKEN: # kept out of error messages
'/[A-Z_]+/': # any upper-case name
$functions:
inCart(wanted)!: vars.cart.items[category = wanted] # defined in the file
fileCount(mask): # passed by the application
about: How many files match the mask.
$import:
./settings.yml: settings # another file's data, as settings.currency
discount:
loyalty!: if count(vars.cart.orders) >= 10 then vars.cart.subtotal * 0.05 else 0
volume!: if vars.cart.subtotal >= 200 then 15 else 0
$value!: max(loyalty, volume) # reading `discount` gives this
note: The bigger of the two applies.
shipping:
- name: Standard
price: 4.90
- name: Express
price: 12.90
$if!: vars.cart.subtotal > 50 # the item exists only when true ($unless! too)
- $each!: settings.warehouses # one item per value
$as: warehouse
name: Pickup in {{ warehouse.city }}
checkout:
methods:
$when: # every matching case applies; $else when none did
- $if!: vars.cart.subtotal > 1000
methods:
$tests: # run by `scrusted-yaml test` and before a reload
- about: A big cart gets the volume discount
vars:
cart:
expect:
discount: 15
count(checkout.methods): 1
$schema (or a shared $dsl: ./kind.dsl.yml) says which keys a file has:
$schema:
required: # many: a list, or a map by name
optional:
Stage:
key: id # the field that names an item
required:
optional: # files+: one or a list
rules:
- valid!: (task != null) != (run != null)
message: a stage has either task or run
Continue: # a set of allowed words
$extends makes a file a patch of another one, or of a bundled template
(scripted-yaml/state-machine, scripted-yaml/navigation-ui, scripted-yaml/forms):
$extends: ./web-testing.yml
stages:
$before: # new items at the start ($after: at the end)
lint:
title: Lint
explore:
$replace: # overwrite fields of one item
when!: base and vars.CI != null # `base` is the value it replaces
$remove:
The full reference is SPEC.md, section 4.
The Rust API
Libraries, files and markers
use ;
let scrusted = builder
.files
// `key!sh:` hands its value to this function; what it returns becomes the value
.marker
.strict // warnings are errors
.build?;
assert!;
# Ok::
DiskFiles::new("rules/")reads a folder (paths cannot leave it),MemoryFilesholds texts, and anyimpl Files(a database, an object store) works too.- A marker function may return a
MarkerOutput::Host(Arc<dyn HostValue>)instead: the value is kept as it is, andHostValue::readruns only when a formula reads the key. In a typed result, aMarked<T>field gets it back. .computed_marker(name, f)computes{{ }}and formulas inside the value first..marker_names([...])registers names only, for a validator.
Validating
# use ScrustedYaml;
let scrusted = builder.build?;
let problems = scrusted.validate_text;
assert_eq!;
# Ok::
Each Problem has file, line, column, key, message and severity.
Validation runs no marker and computes no formula.
Resolving
use ;
let scrusted = builder.build?;
let document = scrusted.load_text?;
let options = default
.functions;
// variables from vars! or from any Serialize
let vars = from_serialize?;
let value = document.resolve?;
assert_eq!;
// all missing variables are reported at once, before anything is computed
let error = document.resolve.unwrap_err;
assert!;
# Ok::
resolvegives aValue;resolve_as::<T>gives anyserde::Deserializetype. A node with$valuekeeps it under the key$value: map it with#[serde(rename = "$value")].ResolveOptionsalso holdsstrict_nulls(every silent null is an error, for authorization files),clock(whatnow()andtoday()read) andlimits(steps, depth, sizes and time per resolve;Limits::none()for tests).- A failure (
ResolveError) names the file, the key and why. document.test(&options)runs the file's$tests;document.merged_text()gives a patch with its base applied, as one file.- Documents are immutable, cheap to clone, and many threads resolve one at once.
Numbers are decimals: 0.1 + 0.2 = 0.3 is true.
The command line
--markers names the markers the files use; --computed the computed ones;
--strict makes warnings errors. The output and exit codes are scripted-yaml's,
so editors and CI read both.
Skills for coding agents
The command line carries three skills that teach a coding agent (Claude Code, Codex, OpenCode) to work with rule files:
| Skill | For |
|---|---|
scrusted-yaml |
writing and checking rule files: formulas, $vars, $schema, $tests, $extends, the mistakes the validator refuses, and reading a file into a Rust struct |
scrusted-yaml-convert |
moving a match or an if chain out of Rust into a rule file, typing the result, serving it live, and proving with a test that nothing changed |
scrusted-yaml-ui |
building an admin page that edits the rules on the running server: save through the live checks, show why a change was refused, roll back |
Every example a skill quotes is a file beside it, validated and tested with the crate.
Differences from scripted-yaml
A file both libraries accept gives the same result in both, except:
- Numbers are decimals, not binary doubles.
- The forms in the table under "Formulas" are refused at validation.
- A formula computes only the
ifbranch it takes. - A missing map key gives null without an error (
strict_nullsmakes it one). - A YAML tag (
ok!: !x) is an error, not dropped. $importtakes.ymland.yamlfiles only. A function comes from$functions, passed by the application; a Markdown file is read by the application and passed as a variable.- Evaluation has limits.
Each case is in conformance/differs/ with both answers;
SPEC.md section 2.3 and its "Implementation notes" explain why.
Contributing
SPEC.md is the specification and CLAUDE.md the working
rules. The conformance suite is regenerated from scripted-yaml with bun:
sh tools/fetch-reference.sh, then bun tools/conformance/generate.ts
(see conformance/README.md).
License: MIT.