Help › Rules · version 1 ·

Rules, messages and flows

Your app's behaviour is written as rules. A rule says what to do when a message arrives. One run of messages through the rules is a flow. You check rules with a story: Stories.

You don't need to write rules yourself: ask your AI "when an order comes in, give members 10% off" and it writes the rule and its story. This page is for reading them, changing them, or writing your own.

What a rule is

A rule is one $when line and a body in braces:

$when hello.greet (name: String) {
  payload = "Hello, ${name}!"
}
  • hello.greet is the message it handles.
  • (name: String) are the values it takes from the message.
  • The body says what to do. payload is what the rule gives back.

Rules live in a Spec: topic, or in your project's init page, Settings:Init (Init). Every line that starts with $ is compiled; the other lines are notes for people. A $when must start its line: an indented one is just text. You can also put rules in a ```diesel fence. Save, and mistakes are shown at once.

Messages

A message is a name and some values: hello.greet (name = "Ana"). Names are words joined by dots, usually thing.action: order.place, price.refresh.

A message comes from:

A message with no rule and no built-in for it stops the flow with E_NO_HANDLER.

Values and guards

  • Values: list them after the name, each name: Type. Types are String, Int, Float, Boolean, Array and Object. Leave the type off to take anything.
  • A rule sees only the values it lists. Using one it didn't list is E_UNDEFINED. A listed value the message didn't bring is simply not defined: check it with is defined.
  • Types are checked. A wrong type stops the flow with E_TYPE. Int is not Float: send 2.0, not 2, to a Float.
  • A guard picks when the rule runs: if (…) after the values.
$when order.price (subtotal: Float, member: Boolean) if (member) {
  …
}

Guards use the expression language: is, is not, and, or, not, >, in, is defined, matches /…/. Every operator: Expressions.

When several rules match

A message runs every rule whose guard holds, in order, top to bottom. No rule "wins" by being first.

  • Each rule starts from the same payload: the one the message arrived with. A rule does not see the payload the rule before it set.
  • The last rule that sets payload gives the answer. A rule that doesn't set it leaves it alone.
  • To build an answer across several rules, keep it in ctx (next) and set payload in the last one.

Values in a flow: local, ctx, payload

  • x = … is local: only this rule sees it. The rule that sent the message never does.
  • ctx.x = … is shared by the whole flow: every rule after it, and the story, can read it.
  • payload = … is what this rule gives back to whoever sent the message.

A rule can read its caller's values too: reads go up the chain of messages. Writing x = … never changes the caller's x.

Send a message from a rule

Two ways, and they do different things:

  • As a line of its own: order.check (qty = qty). The reply becomes this rule's payload.
  • Inside an expression: tax = order.tax(amount = total). You get the reply as a value; payload is left alone.

Values are written name = value, separated by commas.

Decisions and errors

  • if (…) { … } else { … }, braces required.
  • Stop with an error: diesel.throw (code = "E_QTY", msg = "order at least one"). The flow stops, unless someone catches it.
  • Catch it: try { … } catch (e) { … }. e.code and e.message say what went wrong.
  • One statement per line, or separate them with ;. An expression can't run onto the next line outside brackets.
  • In a rule, a small function needs parentheses: xs map (x => x * 2).

Built-in messages

Some messages are answered by d2, not by your rules:

  • log (msg = …): a line in the flow's log.
  • http.json (url = …), http.text (url = …): read from the web (below).
  • json.parse (text = …), csv.parse (text = …): turn text into data. CSV numbers come back as numbers.
  • diesel.throw (code, msg): stop with an error.
  • diesel.cron (…): a message on a schedule (Crons).
  • Requests to d2: notify a member, email them, file a pipeline item, message their agents. The list: LifecycleMessages › requests-your-rules-can-send.
  • Every core function (math.sum, typeOf, dates…): Expressions.

Read from the web

$when repo.stars (name: String) {
  r = http.json(url = "https://api.github.com/repos/${name}")
  payload = r.stargazers_count
}
  • Only https, only public sites. Each read has 10 seconds and 2 MB.
  • Only in rules and flows: never in a computed field, a table or a query (that's E_WAIT: compute it in a rule and store the result).
  • You must be signed in: a run by nobody can't reach the web (E_AUTH).
  • Many at once: names map par (n => http.json(url = …)) reads up to 4 at a time (par 8 for 8, up to 32). Results keep their order.
  • Writing to a web service (http.post, http.patch) works only for sites the project allows, in Settings → Project (apps.sites).
  • Never put a password or key in a rule. Use the vault: Vault.

Events: react to what d2 does

d2 sends your project messages as things happen. Their names have .on. in them:

$when diesel.entity.on.created (category, key) if (category is "Order") {
  diesel.user.notify (to = "ana", text = "New order ${key}")
}
  • Put these in your init page, Settings:Init.
  • Each runs as its own flow, after what caused it.
  • You only handle events, never send them: a rule or story that sends one gets E_NATIVE.
  • Every event and what it carries: LifecycleMessages.

How a flow runs

  • In order. Each line runs, and a message finishes all its rules, before the next line starts.
  • One flow at a time per project. While a flow waits on the web, other flows and pages carry on.
  • Time is limited. A flow has its plan's flow time (waiting on the web is added back, up to 60 seconds in all). Past it, the flow stops with E_TIMEOUT: split the work, or move it to a cron. Your limits: Quotas.
  • See what ran: the Flows page lists the last flows, each with its full trace (Flows).

A worked example

A shop: members get 10% off, tax is 10%, and an order needs at least one item.

$when order.price (subtotal: Float, member: Boolean) {
  ctx.price = subtotal
}

$when order.price (member: Boolean) if (member) {
  ctx.price = ctx.price * 0.9
}

$when order.price {
  payload = ctx.price
}

$when order.place (qty: Int, subtotal: Float, member: Boolean) {
  if (qty < 1) {
    diesel.throw (code = "E_QTY", msg = "order at least one")
  }
  total = order.price(subtotal = subtotal, member = member)
  tax = total * 0.10
  payload = {total: total, tax: tax, due: total + tax}
}

$when order.try (qty: Int) {
  try {
    order.place (qty = qty, subtotal = 10.0, member = false)
  } catch (e) {
    payload = "refused: ${e.message}"
  }
}

What happens on order.place (qty = 2, subtotal = 200.0, member = true):

  1. order.place asks order.price for the price.
  2. All three order.price rules run, in order: the price is 200, then 180 for a member; the last rule gives it back.
  3. order.place adds the tax and answers {total: 180.0, tax: 18.0, due: 198.0}.

And order.try (qty = 0) answers "refused: order at least one". The story that checks all this: Stories › example.

Try it

  1. Open the Fiddle, Specs tab, and press New (or open one of your Spec: topics).
  2. Paste the example. It's checked as you type.
  3. Open the Stories tab and run its story (Stories › run).

Runs in the Fiddle never change your data. The Fiddle is on the project kinds that have it: Fiddle.

When things go wrong

  • E_PARSE: a line doesn't read. The message gives the line and column.
  • E_NO_HANDLER: nothing handles that message. Check the name, and that $when starts its line.
  • E_UNDEFINED: the rule uses a value it didn't list in its ( … ).
  • E_TYPE: a value of the wrong type, like 2 for a Float.
  • E_NATIVE: a rule or story sent an event. Only d2 sends those.
  • E_TIMEOUT: the flow ran too long. Split it, or move work to a cron.
  • E_WAIT: a web read outside a rule.
  • The answer isn't what you expected: open the flow on Flows and read its trace, rule by rule.

See also

Updated by razie · version 1