Rules are the primary component of a ruleset. 

Rules respond to events and, conditionally, take action. The basic pattern for a rule is as follows:

when an event occurs

if some condition is true

then take some action 

This pattern is called the event-condition-action, or ECA, pattern. Many rule languages use this pattern. The ECA pattern is typical of most business rule systems and rule languages based on that pattern are a widely accepted way to build reactive systems.

Separating events from conditions is a key idea in ECA rule languages. As we’ve seen, events represent a state transition. Conditions, on the other hand, are used to determine if the current state has specific properties. 

For example, the inbound_call event signals that the phone system has detected a phone call (i.e. the state changed from one where no phone call was happening to one where a phone call was happening). Conditions can be used to check properties of the new state such as “is the call from the 801 area code,” “is it after 5pm,” or “does the user’s Google calendar show that she’s busy right now?” The separation of events from conditions provides a clear distinction between when (event), what (condition) and how (action).

Each rule conforms to the pattern for ECA rule languages given above with some significant additions. The basic structure of a KRL rule is as follows:

rule <name> {
  select when <eventex> 
  pre {
    <declarations>
  }
  if <expr> then 
    <action> 
  fired {
    <effects> 
  } else {
    <effects> 
 }
}


Only the name and eventex are required, so most rules are simpler than this template. The prelude contains a list of variable declarations that allow computation of values for the condition and action based on global values and event parameters. We will discuss the KRL expression language in greater detail later in this chapter.

Actions are the reaction that the rule makes because of the event. Actions take two general forms:

The section after the action is called the postlude and allows for “effects.” Effects are an important addition to the ECA pattern. Effects differ from actions in that they do not result in directive documents being sent to the endpoint, but rather cause side effects on the KRE system. Examples of effects include the following: 

The following pages describe the details of rules: