# How It Works

Source: https://appfig.com/docs/how-it-works

A detailed look at how AppFig evaluates rules on the client side.

## The Big Picture

```
┌─────────────────────────────────────────────────────────────┐
│ 1. INITIALIZATION                                           │
│    Your app starts → SDK loads rules (from file or server) │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 2. TRACKING                                                 │
│    Your app logs events, sets properties                    │
│    - AppFig.LogEvent("level_complete")                      │
│    - AppFig.SetUserProperty("tier", "premium")              │
│    All stored locally in memory                             │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 3. EVALUATION (when you call GetFeatureValue)              │
│    SDK checks rules against stored events/properties        │
│    - Loops through rules in order                           │
│    - First matching rule wins                               │
│    - Returns value or null                                  │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 4. YOUR APP USES THE VALUE                                 │
│    if (value == "on") { EnableFeature(); }                  │
└─────────────────────────────────────────────────────────────┘
```

## Step-by-Step: Rule Evaluation

Let's walk through exactly what happens when you call `GetFeatureValue()`.

### Setup

You have this feature defined:

```json
Feature: "veteran_bonus"
Rules: [
  {
    "conditions": {
      "events": {
        "mode": "simple",
        "operator": "AND",
        "items": [
          {
            "key": "level_complete",
            "count": { "operator": ">=", "value": 10 }
          }
        ]
      },
      "user_properties": [],
      "device": []
    },
    "value": "2x"
  }
]
```

Your app has done this:

```csharp
AppFig.LogEvent("level_complete"); // Called 12 times
AppFig.GetFeatureValue("veteran_bonus"); // ← What happens now?
```

### Evaluation Process

**Step 1: Find the feature's rules**

```
SDK looks up "veteran_bonus" in its rules dictionary
Found: 1 rule to evaluate
```

**Step 2: Loop through rules (first match wins)**

```
Evaluating Rule #1...
```

**Step 3: Check event conditions**

```
Event condition: "level_complete" count >= 10

SDK counts matching events in history:
- Found 12 "level_complete" events
- Compare: 12 >= 10? ✓ YES

Event conditions: PASS ✓
```

**Step 4: Check user property conditions**

```
User property conditions: [] (empty)
No conditions to check

User property conditions: PASS ✓
```

**Step 5: Check device conditions**

```
Device conditions: [] (empty)
No conditions to check

Device conditions: PASS ✓
```

**Step 6: All conditions passed!**

```
✓ Events: PASS
✓ User Properties: PASS
✓ Device: PASS

Rule #1 MATCHES!
Return value: "2x"
```

**Result:**

```csharp
string bonus = AppFig.GetFeatureValue("veteran_bonus");
// bonus = "2x"
```

## Event History

The SDK maintains an in-memory list of all events you log:

```csharp
AppFig.LogEvent("level_complete"); // Event #1
AppFig.LogEvent("purchase_made");  // Event #2
AppFig.LogEvent("level_complete"); // Event #3
```

**Stored as:**

```
Event History = [
  { name: "level_complete", timestamp: 2025-01-15T10:00:00Z, params: {} },
  { name: "purchase_made",  timestamp: 2025-01-15T10:05:00Z, params: {} },
  { name: "level_complete", timestamp: 2025-01-15T10:10:00Z, params: {} }
]
```

When a rule checks `"level_complete" count >= 2`, the SDK:
1. Filters history for events named "level_complete"
2. Counts them (2 events found)
3. Compares: 2 >= 2? Yes ✓

## Event Modes

### Simple Mode (AND/OR)

Checks if events exist with certain criteria.

**Example: User completed 10+ levels AND made a purchase**

```json
{
  "events": {
    "mode": "simple",
    "operator": "AND",
    "items": [
      {
        "key": "level_complete",
        "count": { "operator": ">=", "value": 10 }
      },
      {
        "key": "purchase_made",
        "count": { "operator": ">=", "value": 1 }
      }
    ]
  }
}
```

**Evaluation:**
```
Check: level_complete count >= 10? (found 12) ✓
Check: purchase_made count >= 1?   (found 1)  ✓
Both pass → Rule matches!
```

### Sequence Mode (Direct/Indirect)

Checks if events occurred in a specific order.

**Example: User completed tutorial → made purchase → completed level**

```json
{
  "events": {
    "mode": "sequence",
    "ordering": "direct",
    "steps": [
      { "key": "tutorial_complete" },
      { "key": "purchase_made" },
      { "key": "level_complete" }
    ]
  }
}
```

**Direct ordering:** Events must occur **consecutively** (no other events between them)

```
Event history:
1. tutorial_complete ← Step 1 ✓
2. purchase_made     ← Step 2 ✓
3. level_complete    ← Step 3 ✓

Sequence matches!
```

**Indirect ordering:** Events must occur **in order** but can have other events between

```
Event history:
1. tutorial_complete ← Step 1 ✓
2. app_open         (ignored)
3. settings_changed  (ignored)
4. purchase_made     ← Step 2 ✓
5. level_complete    ← Step 3 ✓

Sequence matches!
```

## Property Matching

### User Properties

Set by your app, checked against rules:

```csharp
AppFig.SetUserProperty("subscription_tier", "premium");
```

**Rule checks:**
```json
{
  "user_properties": [
    {
      "key": "subscription_tier",
      "value": { "operator": "==", "value": "premium" }
    }
  ]
}
```

**Evaluation:**
```
Lookup: user_properties["subscription_tier"] → "premium"
Compare: "premium" == "premium" → ✓ PASS
```

### Device Properties

Auto-detected by SDK, no setup needed:

```
Device properties (auto-populated):
{
  "platform": "iOS",
  "os_version": "17.0",
  "language": "en-US",
  "country": "US",
  "device_brand": "Apple",
  "device_model": "iPhone 15"
}
```

**Rule checks:**
```json
{
  "device": [
    {
      "key": "platform",
      "value": { "operator": "in", "value": ["iOS", "Android"] }
    }
  ]
}
```

**Evaluation:**
```
Lookup: device["platform"] → "iOS"
Compare: "iOS" in ["iOS", "Android"] → ✓ PASS
```

## Time Windows

Events can be filtered by time:

```json
{
  "key": "level_complete",
  "count": { "operator": ">=", "value": 5 },
  "within_last_days": 7
}
```

**Evaluation:**
```
1. Filter events: name == "level_complete"
   Found: 12 events

2. Filter by time: timestamp >= (now - 7 days)
   Found: 3 events (9 were older than 7 days)

3. Check count: 3 >= 5? ✗ FAIL

Rule does not match
```

## Operators

### Comparison Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `==` | Equals | "premium" == "premium" |
| `!=` | Not equals | "free" != "premium" |
| `>` | Greater than | 10 &gt; 5 |
| `<` | Less than | 3 &lt; 10 |
| `>=` | Greater or equal | 10 &gt;= 10 |
| `<=` | Less or equal | 5 &lt;= 10 |

### Array Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `in` | Value in array | "iOS" in ["iOS", "Android"] |
| `not_in` | Value not in array | "Windows" not_in ["iOS", "Android"] |

### String Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `contains` | String contains substring | "hello world" contains "world" |

## Negation (NOT)

Any condition can be negated with `"not": true`:

```json
{
  "key": "purchase_made",
  "count": { "operator": ">=", "value": 1 },
  "not": true
}
```

**Evaluation:**
```
1. Check condition: purchase_made count >= 1? (found 0) → FAIL
2. Apply NOT: !FAIL → ✓ PASS

Matches users who have NOT made a purchase
```

## Performance: Why It's Fast

AppFig is optimized for high-performance client-side evaluation:

- **In-Memory Processing** - Rules, events, and properties are kept in memory for fast access
- **Smart Caching** - Feature values are cached after evaluation and invalidated only when relevant data changes
- **Efficient Evaluation** - The rule engine is optimized to minimize computational overhead

These optimizations ensure feature checks are extremely fast, with subsequent checks being nearly instantaneous due to caching.

## Rule Evaluation Order

Rules are evaluated in the order you define them. **First match wins.**

```json
Feature: "discount"
Rules: [
  Rule 1: IF premium user → "50% off"
  Rule 2: IF any user → "10% off"
]
```

**Premium user evaluation:**
```
Check Rule 1: premium user? ✓ YES
→ Return "50% off"
(Rule 2 never evaluated)
```

**Free user evaluation:**
```
Check Rule 1: premium user? ✗ NO
Check Rule 2: any user? ✓ YES
→ Return "10% off"
```

## What Gets Sent to the Server?

**Short answer: Almost nothing.**

When you initialize, and once per poll interval:
```
SDK → CDN: "Has the rule set changed?" (a small file)
CDN → SDK: The rules JSON, only when it changed (then cached on the device)
```

When you call `GetFeatureValue()`:
```
No network call! Everything evaluated locally.
```

Schema discovery (paid plans), so the rule builder can offer your event and property names:
```
SDK → Server: event names, parameter names and example values it has not reported before
```
- Sent by about 1% of devices, and by at most 100 devices per app version. The other devices are told they are not needed and stop asking until the app version changes.
- At most once every 12 hours per device.
- Up to 20 example values per parameter or property. A value that looks like an email is sent as `[email]`, and long values are cut to 50 characters.
- No event history, and the device is identified only by an anonymous hash.

## Next Steps

- **[Rule Schema Reference](https://appfig.com/docs/rule-schema)** - All rule options and operators
- **[Testing Guide](https://appfig.com/docs/testing)** - Test your rules
