# MACH
## Why MACH
MACH (Modern Asynchronous C Hypermedia) is a declarative framework for building asynchronous web applications in C23.
* **No build configuration.** Compilation, hot reload, and hmr are handled by the framework. There are no build scripts, package managers, or ORMs to set up.
* **Memory, concurrency, and I/O managed by the framework.** Application code does not call `malloc`/`free` or manage threads, mutexes, or locks. Database queries run as prepared statements. Pipeline steps emit OpenTelemetry spans, logs, and errors automatically.
* **Durable tasks and events.** Both are persisted. If the process crashes, incomplete tasks resume at the step where they left off and undelivered events replay on the next boot.
* **Bundled modules.** SSE plus modules for Datastar, HTMX, Tailwind, SQLite, Postgres, MySQL, Redis/Valkey, DuckDB, and auth. Multi-tenant database support is built in.
---
## Table of Contents
* [Quick Start](#quick-start)
* [Philosophy](#philosophy)
* [Guide](#guide)
* [Reference](#reference)
* [Architecture](#architecture)
* [Tooling](#tooling)
* [License](#license)
---
## Quick Start
Everything runs in Docker; no other local dependencies are required.
```bash
mkdir myapp && cd myapp
wget https://docker.nightshadecoder.dev/mach/compose.yml
# Dev server on :3000, telemetry on :4000
# Includes file watching, auto compilation, hot code reloading, HMR
docker compose up
```
Create `main.c` with the example below. MACH watches for changes and hot-reloads on save. Use your own editor, or attach to the built-in TUI with `docker compose attach mach` for an integrated environment with editor, AI, LSP, and console.
```c
#include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template = "
Hello, world!
")
}
}
}
};
}
```
The `mach()` function returns a `config` struct that defines the application. The `home` resource maps `/` to a GET pipeline whose only step renders inline HTML. For a step-by-step walkthrough, see the [Guide](#guide).
---
## Philosophy
Applications are data transformations: data enters from sources, flows through business logic, and exits to the client. MACH keeps each piece standard. Data comes from raw SQL, HTTP fetch, and JSON rather than ORMs. Business logic is plain C. Output is HTML, CSS, and JS via Mustache templates. These pieces compose inside pipelines: ordered lists of steps that turn a request into a response.
Tooling is also kept standard (lldb for debugging, Playwright and Criterion for testing, OpenTelemetry for observability) and built in.
### Everything is a String
The web is largely text: HTTP, HTML, JSON, SQL. MACH takes this literally. The pipeline context stores and passes data as arena-backed strings; there is no intermediate parsing or serialization layer. Request parameters are not parsed into typed structs and objects are not serialized back to JSON. Data flows through the pipeline as strings, interpolated into SQL, templates, and URLs with `{{context_key}}`.
When business logic needs a specific C type, convert explicitly inside an `exec()` step.
### CLAD
MACH is organized around four principles.
* **(C)omposable:** small, independent steps chain into feature pipelines.
* **(L)ocality of Behavior:** the behavior of a unit of code is apparent from reading it. SQL, templates, and behavior for a feature live together rather than across separate model, view, and controller trees.
* **(A)utonomous:** modules are self-contained: own schemas, migrations, seeds, routes, UI, and logic. The compiler enforces strict boundaries.
* **(D)omain Based:** each module owns one slice of the app. A `todos` module defines everything related to todos and nothing else.
CLAD is influenced by:
* [Data Oriented Design](https://youtu.be/rX0ItVEVjHc)
* [A Philosophy of Software Design](https://youtu.be/bmSAYlu0NcY)
* [CUPID](https://youtu.be/cyZDLjLuQ9g)
* [Self-Contained Systems](https://youtu.be/Jjrencq8sUQ)
* [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour)
---
## Guide
A walkthrough that builds a working todo app, one concept at a time.
* [1. A Page](#1-a-page)
* [2. Show Data](#2-show-data)
* [3. Accept Input](#3-accept-input)
* [4. Nested Data](#4-nested-data)
* [5. Tasks](#5-tasks)
* [6. Modules and Events](#6-modules-and-events)
* [7. Calling APIs](#7-calling-apis)
* [8. External Assets](#8-external-assets)
### 1. A Page
Two resources, each with a GET pipeline. `{{url:todos}}` resolves to the target resource's URL at render time, so changing a URL pattern updates every link.
```c
#include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
"
""
)
}
}
}
};
}
```
Each resource names itself (`"home"`, `"todos"`) so other pages reference it by name, not by hard-coded path.
### 2. Show Data
Add a SQLite database with one migration and one seed, then read from it in the GET pipeline.
```diff
#include
+ #include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
Welcome
"
"My Todos"
""
)
}
},
{"todos", "/todos",
.get = {
+ query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"}),
render(.template =
""
"
My Todos
"
- "
Nothing yet.
"
+ "
{{#todos}}
{{title}}
{{/todos}}
"
""
)
}
}
- }
+ },
+
+ .databases = {{
+ .engine = sqlite_db,
+ .name = "todos_db",
+ .connect = "file:todos.db?mode=rwc",
+ .migrations = {
+ "CREATE TABLE todos ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "title TEXT NOT NULL"
+ ");"
+ },
+ .seeds = {"INSERT INTO todos(title) VALUES('Learn MACH');"}
+ }},
+
+ .modules = {sqlite}
};
}
```
`query` runs the SELECT and stores the rows under `todos` in pipeline context. `render` walks the section with `{{#todos}}...{{/todos}}`. Migrations run on the first connection.
### 3. Accept Input
Add a POST verb that validates a `title` parameter, inserts it, redirects back to GET (POST-redirect-GET), and re-renders the form with errors on validation failure.
```diff
#include
#include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
Welcome
"
"My Todos"
""
)
}
},
{"todos", "/todos",
.get = {
query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"}),
render(.template =
""
"
My Todos
"
"
{{#todos}}
{{title}}
{{/todos}}
"
+ ""
""
)
- }
+ },
+
+ .post = {
+ input({"title", .matches = m_not_empty}),
+ query({.db = "todos_db", .query = "insert into todos(title) values({{title}});"}),
+ redirect("todos")
+ },
+
+ .errors = {
+ {m_bad_request, {reroute("todos")}}
+ }
}
},
.databases = {{
.engine = sqlite_db,
.name = "todos_db",
.connect = "file:todos.db?mode=rwc",
.migrations = {
"CREATE TABLE todos ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT NOT NULL"
");"
},
.seeds = {"INSERT INTO todos(title) VALUES('Learn MACH');"}
}},
.modules = {sqlite}
};
}
```
The POST pipeline validates first; on success, the title is promoted from `input:title` to app scope. The interpolated `{{title}}` in the SQL is bound as a prepared-statement parameter, not spliced. `redirect("todos")` returns a 302 to `/todos`.
Validation failure raises `m_bad_request`. The resource-scoped error handler re-enters the GET pipeline with `reroute("todos")`, which runs the same pipeline in-process. The `input:` and `error:` scopes persist through the reroute, so `{{input:title}}` repopulates the field and `{{#error:title}}` renders the message.
`{{csrf:input}}` emits a hidden CSRF token input; MACH verifies it on every state-changing request automatically. See [Template Helpers](#template-helpers) and [redirect and reroute](#redirect-and-reroute).
### 4. Nested Data
Add a `/todos/:id` page that fetches a todo and its comments concurrently, nests the comments inside the todo record, and renders them together. Comments belong to the same domain as todos, so the new `comments` table is added as a migration on the existing `todos_db`.
```diff
#include
#include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
Welcome
"
"My Todos"
""
)
}
},
{"todos", "/todos",
.get = {
query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"}),
render(.template =
""
"
"
+ "{{/todo}}"
+ ""
+ )
+ }
+ }
},
.databases = {{
.engine = sqlite_db,
.name = "todos_db",
.connect = "file:todos.db?mode=rwc",
.migrations = {
"CREATE TABLE todos ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT NOT NULL"
- ");"
+ ");",
+ "CREATE TABLE comments ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "todo_id INTEGER NOT NULL REFERENCES todos(id),"
+ "body TEXT NOT NULL"
+ ");"
},
.seeds = {"INSERT INTO todos(title) VALUES('Learn MACH');"}
}},
.modules = {sqlite}
};
}
```
The two queries run concurrently under one `query()` call. `join()` lifts `comments` inside each todo record, so the template enters `{{#todo}}` first and reaches `{{#comments}}` from within. `.must_exist = true` raises `m_not_found` when the todo lookup returns zero rows, so an unknown `:id` returns a 404 rather than rendering an empty page.
### 5. Tasks
Tasks are named pipelines that run asynchronously on task reactors. Triggered on a cron schedule or enqueued from another pipeline with `task("name")`. Add a nightly task that records the current todo count into a `daily_stats` table, and re-run the same task from the POST pipeline so stats stay fresh after every write.
```diff
#include
#include
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
Welcome
"
"My Todos"
""
)
}
},
{"todos", "/todos",
.get = {
query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"}),
render(.template =
""
"
"
"{{/todo}}"
""
)
}
}
},
+ .tasks = {
+ {"record_daily_stats", {
+ query({.db = "todos_db", .query = "insert into daily_stats(todo_count) select count(*) from todos;"})
+ }, .cron = "0 0 * * *"}
+ },
.databases = {{
.engine = sqlite_db,
.name = "todos_db",
.connect = "file:todos.db?mode=rwc",
.migrations = {
"CREATE TABLE todos ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT NOT NULL"
");",
"CREATE TABLE comments ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"todo_id INTEGER NOT NULL REFERENCES todos(id),"
"body TEXT NOT NULL"
- ");"
+ ");",
+ "CREATE TABLE daily_stats ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
+ "todo_count INTEGER NOT NULL"
+ ");"
},
.seeds = {"INSERT INTO todos(title) VALUES('Learn MACH');"}
}},
.modules = {sqlite}
};
}
```
The same task definition is reused two ways: `.cron = "0 0 * * *"` runs it at midnight, and `task("record_daily_stats")` from the POST pipeline enqueues an on-demand run after each insert. Both invocations land on a task reactor, on separate cores from the request reactors that serve HTTP, so the POST returns immediately. To pass values from the calling context (a `user_id`, a `todo_id`), list them under `.accepts` on the task definition and reference them with `{{user_id}}` interpolation.
Tasks are durable: MACH checkpoints the context after each step, so a crash mid-task resumes at the failed step on the next boot. See [Task Pipelines](#task-pipelines).
### 6. Modules and Events
Features/Domains split into modules as the app grows; modules communicate through pub/sub events instead of calling each other directly. A module is a fully self-contained system: its own resources, databases, migrations, context, error and repair handlers, tasks, and event subscribers. `main.c` composes them and handles cross-cutting concerns.
This step extracts the todos logic into its own module and adds an `activity` module that logs an entry whenever a todo is created and exposes a page to view the log.
Modules are plain C files. Each defines a function returning `config` (for example, `config todos() { ... }`, `config activity() { ... }`), and `main.c` pulls them in with `#include` and registers them under `.modules`.
Directory layout after this step:
```
.
├── activity/
│ └── activity.c
├── todos/
│ └── todos.c
└── main.c
```
**`main.c`**: thin root that composes modules and handles cross-cutting concerns.
```c
#include
#include
#include "todos/todos.c"
#include "activity/activity.c"
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
render(.template =
""
"
Welcome
"
"My Todos · "
"Activity"
""
)
}
}
},
.modules = {todos, activity, sqlite}
};
}
```
**`todos/todos.c`**: the todos module, now a publisher.
```c
#include
#include
config todos(){
return (config) {
.name = "todos",
.publishes = {
{"todo_created", .with = {"title"}}
},
.resources = {
{"todos", "/todos",
.get = {
query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"}),
render(.template =
""
"
"
"{{/todo}}"
""
)
}
}
},
.tasks = {
{"record_daily_stats", {
query({.db = "todos_db", .query = "insert into daily_stats(todo_count) select count(*) from todos;"})
}, .cron = "0 0 * * *"}
},
.databases = {{
.engine = sqlite_db,
.name = "todos_db",
.connect = "file:todos.db?mode=rwc",
.migrations = {
"CREATE TABLE todos ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT NOT NULL"
");",
"CREATE TABLE comments ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"todo_id INTEGER NOT NULL REFERENCES todos(id),"
"body TEXT NOT NULL"
");",
"CREATE TABLE daily_stats ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
"todo_count INTEGER NOT NULL"
");"
},
.seeds = {"INSERT INTO todos(title) VALUES('Learn MACH');"}
}},
.modules = {sqlite}
};
}
```
**`activity/activity.c`**: the new subscriber: its own database, its own resource, its own event handler. Nothing references the todos module.
```c
#include
#include
config activity(){
return (config) {
.name = "activity",
.resources = {
{"activity", "/activity",
.get = {
query({.set_key = "activities", .db = "activity_db", .query = "select kind, ref, created_at from activities order by created_at desc;"}),
render(.template =
""
"
Activity
"
"
{{#activities}}"
"
{{created_at}}: {{kind}}, {{ref}}
"
"{{/activities}}
"
""
)
}
}
},
.events = {
{"todo_created", {
query({.db = "activity_db", .query = "insert into activities(kind, ref) values('created', {{title}});"})
}}
},
.databases = {{
.engine = sqlite_db,
.name = "activity_db",
.connect = "file:activity.db?mode=rwc",
.migrations = {
"CREATE TABLE activities ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"kind TEXT NOT NULL,"
"ref TEXT NOT NULL,"
"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
");"
}
}},
.modules = {sqlite}
};
}
```
Each module owns one slice of the app and can declare its own context, error and repair handlers, and nested modules. Neither references the other; they agree on the event name and payload only.
When the POST pipeline calls `emit("todo_created")`, MACH propagates `title` from the current context to every subscriber's pipeline. The `activity` module's `.events` entry runs with `title` available, writing the row to `activity_db`. Because `.publishes` is defined, MACH tracks delivery in a `mach_events` database; if the process crashes between emit and delivery the event replays on the next boot. Adding a third subscriber is a new file with an `.events` entry; `todos` doesn't change.
### 7. Calling APIs
Pipelines reach external HTTP services the same way they read from databases. `fetch()` makes one or more requests and stores responses in context; JSON is parsed into tables and records, with nested JSON becoming nested context tables. Multiple items in a single `fetch()` run **concurrently**, just like `query()`. Add a quote of the day and the current weather to the home page, pulled from two public APIs concurrently.
**`main.c`**
```diff
#include
#include
#include "todos/todos.c"
#include "activity/activity.c"
config mach(){
return (config) {
.resources = {
{"home", "/",
.get = {
+ fetch(
+ {"https://api.quotable.io/random", .set_key = "quote"},
+ {"https://api.weather.dev/now", .set_key = "weather"}
+ ),
render(.template =
""
"
"
+ "{{/quote}}"
"My Todos · "
"Activity"
""
)
}
}
},
.modules = {todos, activity, sqlite}
};
}
```
Both requests run concurrently under one `fetch()` call; `render()` runs once both responses are in context. JSON responses parse into context tables: Quotable's `{"author": "...", "content": "..."}` becomes a single-row table under `quote`. Templates enter `{{#quote}}` and `{{#weather}}` as they do for query results.
`fetch()` also supports POST/PUT/PATCH/DELETE, custom headers, JSON or text request bodies, and URLs with `{{interpolation}}`. See [fetch](#fetch).
### 8. External Assets
Once templates and SQL grow past a few lines, extract them into files and load them with `(asset){ #embed "..." }` in `.context`, then reference them by name from `render()` and `query()`. Each artifact lives in a file named for what it is, edited with native tooling, and syntax-highlighted on its own terms. Add a shared layout at the same time: one template holds the chrome and other pages extend it.
Directory layout after this step:
```
.
├── activity/
│ ├── activity.c
│ ├── activity.mustache.html
│ ├── create_activities_table.sql
│ ├── get_activities.sql
│ └── insert_activity.sql
├── static/
│ ├── home.mustache.html
│ └── layout.mustache.html
├── todos/
│ ├── create_todos_table.sql
│ ├── create_comments_table.sql
│ ├── create_daily_stats_table.sql
│ ├── seed_todos.sql
│ ├── get_todos.sql
│ ├── create_todo.sql
│ ├── get_todo.sql
│ ├── get_comments.sql
│ ├── record_daily_stats.sql
│ ├── todos.c
│ ├── todos_list.mustache.html
│ └── todo_detail.mustache.html
└── main.c
```
`static/` is not a module (no `.c` file). It's a plain directory for root-level templates that `main.c` references.
#### Root
**`static/layout.mustache.html`**: shared chrome with a `{{$content}}` block that child templates override.
```html
{{$content}}{{/content}}
```
**`static/home.mustache.html`**: extends `layout`.
```html
{{Welcome
{{#weather}}
{{/content}}
{{/layout}}
```
**`activity/insert_activity.sql`**
```sql
insert into activities(kind, ref) values('created', {{title}});
```
**`activity/activity.c`**: same extraction pattern.
```c
#include
#include
config activity(){
return (config) {
.name = "activity",
.resources = {
{"activity", "/activity",
.get = {
query({"get_activities", .set_key = "activities", .db = "activity_db"}),
render("activity")
}
}
},
.events = {
{"todo_created", {
query({"insert_activity", .db = "activity_db"})
}}
},
.context = {
{"activity", (asset){
#embed "activity.mustache.html"
}},
{"get_activities", (asset){
#embed "get_activities.sql"
}},
{"insert_activity", (asset){
#embed "insert_activity.sql"
}}
},
.databases = {{
.engine = sqlite_db,
.name = "activity_db",
.connect = "file:activity.db?mode=rwc",
.migrations = {
(asset){
#embed "create_activities_table.sql"
}
}
}},
.modules = {sqlite}
};
}
```
#### Template inheritance and partials
`{{name}}`: it inlines the named asset rendered against the current scope. This differs from unescaped interpolation (`{{{name}}}` or `{{&name}}`): `{{>name}}` runs Mustache on the asset so helpers and sections inside it resolve; the unescaped forms emit the value verbatim. Use `{{>name}}` for templates and `{{&name}}` for already-rendered HTML such as a sanitized blog body.
---
## Reference
* [Context](#context)
* [Databases](#databases)
* [Resource Pipelines](#resource-pipelines)
* [Template Helpers](#template-helpers)
* [Pipeline Steps](#pipeline-steps)
* [Imperative API](#imperative-api)
* [Conditionals](#conditionals)
* [Iteration](#iteration)
* [Error and Repair Pipelines](#error-and-repair-pipelines)
* [Event Pipelines](#event-pipelines)
* [Task Pipelines](#task-pipelines)
* [Modules and Composition](#modules-and-composition)
* [Module Reference](#module-reference)
* [Static Files](#static-files)
* [External Dependencies](#external-dependencies)
### Context
Pipelines read from and write to a shared, scoped key-value store that lives for the duration of one request. Every step draws inputs from context and writes outputs back to it.
`.context` seeds that store at the root with variables and assets available on every request. Templates and SQL stored here are referenced by name in `render()` and `query()`. Use `(asset){ #embed "file" }` to bake files into the binary at compile time. Docker secrets exposed to the container are also available in context.
The context uses three scopes: `input:xxx` for raw request parameters, `error:xxx` for validation/error data, and unprefixed names for app scope (query results, validated inputs, context variables). The `input()` step promotes values from the `input:` scope to app scope.
**Inline string value**: provide the value directly.
```c
.context = {{"site_name", "MACH App"}}
```
**`(asset){ #embed ... }`**: bake a file into the binary as a named asset.
```c
.context = {
{"layout", (asset){
#embed "layout.mustache.html"
}},
{"get_todos", (asset){
#embed "get_todos.sql"
}}
}
```
Combined:
```c
.context = {
{"site_name", "MACH App"},
{"version", "1.2.0"},
{"layout", (asset){
#embed "static/layout.mustache.html"
}},
{"home", (asset){
#embed "static/home.mustache.html"
}},
{"get_todos", (asset){
#embed "todos/get_todos.sql"
}},
{"create_todo", (asset){
#embed "todos/create_todo.sql"
}}
}
```

### Databases
Each `.databases` entry defines a data store. Migrations are forward-only and index-based: they run in array order, each applied once, with new migrations appended to the end. Seeds are idempotent and safe to re-run. Both are tracked in a `mach_meta` table.
Multi-tenant databases use `{{interpolation}}` in `.connect`. Connections are pooled with LRU eviction: active tenants stay warm, idle connections are reclaimed.
**`.engine`**: database engine constant, provided by a module.
```c
.engine = sqlite_db
```
**`.name`**: identifier referenced by `.db` in `query()`.
```c
.name = "todos_db"
```
**`.connect`**: engine-specific connection string. Supports `{{interpolation}}` for multi-tenancy.
```c
.connect = "file:{{user_id}}_todo.db?mode=rwc"
```
**`.migrations`**: array of SQL migration strings or assets, applied once each in order.
```c
.migrations = {
(asset){
#embed "create_todos_table.sql"
}
}
```
**`.seeds`**: array of idempotent seed statements, safe to re-run on every boot.
```c
.seeds = {"INSERT OR IGNORE INTO todos(id, title) VALUES(1, 'Hello');"}
```
Combined:
```c
.databases = {{
.engine = sqlite_db,
.name = "blog_db",
.connect = "file:{{user_id}}_blog.db?mode=rwc",
.migrations = {
"CREATE TABLE blogs ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT NOT NULL,"
"content TEXT NOT NULL"
");",
"CREATE TABLE comments ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"blog_id INTEGER NOT NULL REFERENCES blogs(id),"
"body TEXT NOT NULL"
");"
},
.seeds = {
"INSERT OR IGNORE INTO blogs(id, title, content) VALUES(1, 'Hello', 'First post');"
}
}}
```
**Engines:** `sqlite_db`, `postgres_db`, `mysql_db`, `redis_db`, `duckdb_db`

### Resource Pipelines
MACH is resource-based, not route-based. Each entry in `.resources` defines a named URL endpoint with HTTP verb pipelines. Resources are identified by name. `{{url:name}}`, `redirect()`, and `reroute()` all take just the resource name; any `:params` in the URL pattern are read from the current scope by matching key names. Path specificity is automatic: exact matches (`/todos/active`) beat parameterized matches (`/todos/:id`) regardless of definition order.
Clients select a verb via the request method, or by passing `http_method` as a query/form parameter. This lets HTML forms (limited to GET/POST) reach any verb, and gives SSE a connection path: `/todos?http_method=sse`.
**`.name` *(pos)***: resource identifier used by `{{url:name}}`, `redirect()`, and `reroute()`.
```c
{"todos", "/todos", .get = { ... }}
```
**`.url` *(pos)***: URL pattern. Supports `:params`.
```c
{"todo", "/todos/:id", .get = { ... }}
```
**`.steps` *(pos)***: shared steps that run before every verb pipeline on the resource.
```c
{"todo", "/todos/:id", {
input({"id", .matches = "^\\d+$", .message = "must be a number"})
}, .get = { ... }, .delete = { ... }}
```
**`.mime`**: default response content type for the resource.
```c
{"feed", "/feed.json", .mime = m_json, .get = { ... }}
```
**`.get` `.post` `.put` `.patch` `.delete`**: verb pipelines: ordered arrays of steps that transform a request into a response.
```c
{"todos", "/todos",
.get = { query({"get_todos", .set_key = "todos", .db = "db"}), render("todos") },
.post = { input({"title", .matches = m_not_empty}), redirect("todos") }
}
```
**`.sse`**: persistent SSE channel. First positional is the channel name; steps run on connect.
```c
{"todos", "/todos",
.sse = {"todos/{{user_id}}",
query({"get_todos", .set_key = "todos", .db = "db"}),
sse(.event = "initial", .data = {"{{todos}}"})
}
}
```
**`.errors` / `.repairs`**: resource-scoped error and repair pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines).
```c
{"todos", "/todos",
.post = { ... },
.errors = {{m_bad_request, {render("form")}}}
}
```
Combined:
```c
{"todo", "/todos/:id", {
input({"id", .matches = "^\\d+$", .message = "must be a number"})
},
.get = { query({"get_todo", .set_key = "todo", .db = "todos_db", .must_exist = true}),
render("todo") },
.patch = { input({"title", .matches = m_not_empty, .message = "required"}),
query({.db = "todos_db", .query = "update todos set title = {{title}} where id = {{id}};"}),
redirect("todo") },
.delete = { query({.db = "todos_db", .query = "delete from todos where id = {{id}};"}),
redirect("todos") },
.sse = {"todo/{{id}}", sse(.event = "ready") },
.errors = {{m_not_found, {render("404")}}}
}
```
**MIME types (for `.mime`):** `m_html`, `m_txt`, `m_sse`, `m_json`, `m_js`
### Template Helpers
Templates are Mustache. MACH supports the full Mustache base spec with one exception: dot notation. Use a section instead. `{{a.b}}` does not work; `{{#a}}{{b}}{{/a}}` does.
Supported base-spec features:
- **Interpolation**: `{{name}}` (HTML-escaped), `{{{name}}}` or `{{&name}}` (unescaped).
- **Sections**: `{{#name}}...{{/name}}` renders when truthy and iterates over arrays.
- **Inverted sections**: `{{^name}}...{{/name}}` renders when falsy or empty.
- **Comments**: `{{! ignored }}`.
- **Set delimiters**: `{{=<% %>=}}`.
- **Partials**: `{{>name}}` inlines the context asset named `name`, rendered against the current scope.
- **Layout inheritance**: `{{Total: ${{precision:total:2}}
")
```
**`{{input:field}}`**: raw, unvalidated request parameter from the `input` scope. Typically used to repopulate form fields after a validation error.
```c
render(.template = "")
```
**`{{error:field}}`**: truthy when `field` has an error. Used as a Mustache section to conditionally render markup.
```c
render(.template = "{{#error:title}}invalid{{/error:title}}")
```
**`{{error_message:field}}`**: human-readable message for a field error, from `input()`'s `.message` or from `error_set()`.
```c
render(.template = "{{error_message:title}}")
```
**`{{error_code:field}}`**: HTTP status code associated with a field error (e.g. `400`, `404`).
```c
render(.template = "
Code: {{error_code:title}}
")
```
**`{{url:name}}`**: resolve a resource name to its URL. `:params` in the URL pattern are read from the current scope by name; no positional args.
```c
render(.template =
"All" // /todos
"{{#todos}}{{title}}{{/todos}}" // /todos/{{id}} per row
"{{#todo}}{{title}}{{/todo}}" // /todos/{{id}} from a single record
)
```
**`{{asset:filename}}`**: resolve a file in `public/` to a cache-busted URL (content checksum + immutable cache headers). See [Static Files](#static-files).
```c
render(.template = "")
```
**`{{csrf:token}}`**: emit a CSRF token, for use in URL query strings. Generates a random hash, sets it on an httponly/secure/samesite cookie, and outputs the same value inline.
```c
render(.template = "Log out")
```
**`{{csrf:input}}`**: emit a hidden `` carrying a CSRF token, for use inside a `")
```
Combined:
```c
render(.template =
""
""
"{{#post}}"
"
{{title}}
"
"
Rating: {{precision:score:1}}/5
"
"
{{&body_html}}
"
"{{/post}}"
""
"Log out"
""
)
```
> **CSRF verification is automatic.** MACH checks that the incoming token (from the form field or query parameter) matches the value stored in the CSRF cookie and rejects mismatches with a 403. The cookie is httponly, secure, and samesite, so nothing beyond emitting `{{csrf:token}}` or `{{csrf:input}}` in the rendered response is required.
### Pipeline Steps
Steps are the units of work in a pipeline. Each receives the current context, acts on it, and passes control to the next. All steps accept `.if_context` and `.unless_context` for [conditional execution](#conditionals), and `.table_key` for concurrent fan-out across rows of a context table (see [Iteration](#iteration)).
> **Concurrency comes from multiple items inside one step, not from multiple steps in sequence.** `query({...}, {...})` runs both queries concurrently; two back-to-back `query({...})` steps run serially. The same applies to `fetch()` and to `.table_key` iteration.
* [input](#input)
* [query](#query)
* [join](#join)
* [fetch](#fetch)
* [exec](#exec)
* [emit](#emit)
* [task](#task)
* [sse](#sse)
* [render](#render)
* [headers and cookies](#headers-and-cookies)
* [redirect and reroute](#redirect-and-reroute)
* [nest](#nest)

#### input
Checks request parameters (query string, form body, URL params) against regex patterns. On success, each value is promoted from `input:name` to app scope. On failure, errors land in `error:name` and a `400 Bad Request` triggers the nearest [error/repair pipeline](#error-and-repair-pipelines). All validations in one call complete before the error fires, so all errors are available together for form re-rendering.
Built-in regex macros are defined in `mach.h`; define your own the same way: `#define m_zipcode "^\\d{5}$"`. For checks that don't fit a regex (uniqueness, cross-field rules, async lookups), follow `input()` with an `exec()` step that reads the value from context and calls `error_set()` on failure.
**`.param_key` *(pos)***: name of the parameter to validate.
```c
input({"title", .matches = "^\\S+$", .message = "required"})
```
**`.matches`**: regex pattern, or a built-in validator macro.
```c
input({"email", .matches = m_email, .message = "bad email"})
```
**`.message`**: human-readable error shown via `{{error_message:name}}`.
```c
input({"age", .matches = "^\\d+$", .message = "must be a number"})
```
**`.optional`**: skip validation when the parameter is absent.
```c
input({"filter", .optional = true, .matches = "^(active|done)$"})
```
**`.fallback`**: default value injected when the parameter is absent.
```c
input({"page", .fallback = "1", .matches = "^\\d+$"})
```
Combined:
```c
input(
{"email", .matches = m_email, .message = "must be a valid email"},
{"title", .matches = m_not_empty, .message = "cannot be empty"},
{"page", .fallback = "1", .matches = "^\\d+$", .message = "must be a number"},
{"filter", .optional = true, .matches = "^(active|done)$", .message = "must be 'active' or 'done'"},
{"username", .matches = m_username, .message = "must be alphanumeric"}
)
```
For checks beyond regex (uniqueness, cross-field rules, lookups), pair `input()` with `query()` and `exec()`:
```c
input({"username", .matches = m_username, .message = "must be alphanumeric"}),
query({.set_key = "existing", .db = "users_db", .query = "select 1 from users where username = {{username}};"}),
exec(^(){
auto rows = get("existing");
if (rows && table_count(rows) > 0)
error_set("username", (error){m_bad_request, "already taken"});
})
```
**Built-in validators:**
- Strings: `m_not_empty`, `m_alpha`, `m_alphanumeric`, `m_slug`, `m_no_html`
- Numbers: `m_integer`, `m_positive`, `m_float`, `m_percentage`
- Identity: `m_email`, `m_uuid`, `m_username`
- Dates & times: `m_date`, `m_time`, `m_datetime`
- Web: `m_url`, `m_ipv4`, `m_hex_color`
- Codes: `m_zipcode_us`, `m_phone_e164`, `m_cron`
- Security: `m_token`, `m_base64`
- Boolean: `m_boolean`, `m_yes_no`, `m_on_off`
#### query
Runs a database query. `.db` selects the database; `.set_key` stores the result in context as a table, even for single-row queries. SQL is either inlined with `.query` or referenced by name as the positional (loaded from `.context`). Multiple items in a single step run **concurrently**. Queries use prepared statements; interpolated `{{values}}` are bound, not spliced. For transactions, use `BEGIN`/`COMMIT`/`ROLLBACK` directly in your queries.
> **Positional asset name OR `.query`, not both.** Each item picks one:
> - ✅ `query({"get_todos", .set_key = "todos", .db = "todos_db"})`: SQL loaded by asset name from `.context`
> - ✅ `query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos;"})`: SQL inlined
> - ❌ `query({"get_todos", .set_key = "todos", .db = "todos_db", .query = "select ..."})`: combining the two is rejected
**`.template_key` *(pos)***: name of a SQL asset stored in `.context`. Mutually exclusive with `.query`.
```c
query({"get_todos", .set_key = "todos", .db = "todos_db"})
```
**`.query`**: inline SQL string. Supports `{{interpolation}}`, bound as parameters. Mutually exclusive with the positional asset name.
```c
query({.set_key = "todos", .db = "todos_db", .query = "select id, title from todos where user_id = {{user_id}};"})
```
**`.set_key`**: context key for the result table.
```c
query({.set_key = "active", .db = "db", .query = "select * from todos;"})
```
**`.db`**: name of the database, matching a `.databases` entry.
```c
query({.db = "todos_db", .query = "select 1;"})
```
**`.must_exist`**: when true, raise `404 Not Found` if the query returns zero rows. Default is false.
```c
query({"get_todo", .set_key = "todo", .db = "todos_db", .must_exist = true})
```
**`.if_context` / `.unless_context`** *(per item)*: conditionally include or skip individual queries while running the others concurrently.
```c
query(
{"get_todos", .set_key = "todos", .db = "db"},
{"get_urgent", .if_context = "show_urgent", .set_key = "u", .db = "db"}
)
```
Combined:
```c
query(
{"get_todos", .set_key = "todos", .db = "todos_db"},
{.set_key = "count", .db = "todos_db", .query = "select count(*) as n from todos where user_id = {{user_id}};"},
{.if_context = "show_urgent", .set_key = "urgent", .db = "todos_db", .query = "select id, title from todos where user_id = {{user_id}} and priority = 'high';"}
)
```
#### join
Nests records from one context table into each matching record of another, like a SQL JOIN performed in memory. Useful when records come from separate databases or queries and need to be combined. After the step, each outer record gains a new field holding its matched inner records.
**`.parent_key`**: outer table whose records receive nested children.
```c
.parent_key = "projects"
```
**`.field_key`**: field on the outer table to match against.
```c
.field_key = "id"
```
**`.child_key`**: inner table whose records get nested.
```c
.child_key = "todos"
```
**`.child_field_key`**: field on the inner table that points at the outer.
```c
.child_field_key = "project_id"
```
**`.join_field_key`**: new field on outer records holding the matched inner records.
```c
.join_field_key = "todos"
```
Combined:
```c
join(.parent_key = "projects", .field_key = "id", .child_key = "todos", .child_field_key = "project_id", .join_field_key = "todos")
```
**Full context example.** Concurrent `query()` → `join()` → `render()`: fetch parent and children from separate queries, then render them as one nested structure. Blog + comments, single database:
```c
{"blog", "/blogs/:id",
.get = {
input({"id", .matches = m_integer}),
// Fetch both concurrently: one query() call, two items
query(
{.set_key = "blog", .db = "blog_db", .query = "select id, title, content from blogs where id = {{id}};"},
{.set_key = "comments", .db = "blog_db", .query = "select id, blog_id, body from comments where blog_id = {{id}};"}
),
// Nest each comment into its matching blog record
join(.parent_key = "blog", .field_key = "id", .child_key = "comments", .child_field_key = "blog_id", .join_field_key = "comments"),
// Enter {{#blog}} first; after join(), comments lives INSIDE each blog record
render(.template =
""
"{{#blog}}"
"
{{title}}
"
"
{{content}}
"
"
Comments
"
"
{{#comments}}
{{body}}
{{/comments}}
"
"{{/blog}}"
""
)
}
}
```
Shape of the context at each step:
```
after query(): { blog: [{id, title, content}],
comments: [{id, blog_id, body}, ...] } // two sibling tables
after join(): { blog: [{id, title, content,
comments: [{id, blog_id, body}, ...]}] } // nested inside blog
```
#### fetch
Makes one or more HTTP requests and stores responses in context. JSON is parsed into tables and records (with nested tables for nested JSON); plain-text responses are stored as a string. Like `query()`, multiple items in a single step run **concurrently**, so a page can fan out to several services and join the results downstream.
**`.url` *(pos)***: request URL; supports `{{interpolation}}`.
```c
fetch({"https://api.weather.dev/forecast?city={{city}}", .set_key = "w"})
```
**`.set_key`**: context key for the response.
```c
fetch({"https://api.weather.dev/now", .set_key = "weather"})
```
**`.method`**: HTTP method. Defaults to `m_get`.
```c
fetch({"https://api.dev/charge", .set_key = "r", .method = m_post})
```
**`.headers`**: array of name/value pairs.
```c
fetch({"https://api.dev/me", .set_key = "r", .headers = {{"Authorization", "Bearer {{token}}"}}})
```
**`.json`**: context key serialized as the JSON request body.
```c
fetch({"https://api.dev/charge", .set_key = "receipt", .method = m_post, .json = "order"})
```
**`.text`**: context key sent as the plain-text request body.
```c
fetch({"https://api.dev/log", .set_key = "r", .method = m_post, .text = "raw_body"})
```
**`.if_context` / `.unless_context`** *(per item)*: conditionally include or skip individual requests while running the others concurrently.
```c
fetch(
{"https://api.weather.dev/now", .set_key = "weather"},
{"https://api.quotes.dev/random", .if_context = "show_quote", .set_key = "quote"}
)
```
Combined, single request:
```c
fetch({"https://api.payments.dev/charge",
.set_key = "receipt",
.method = m_post,
.headers = {
{"Authorization", "Bearer {{api_key}}"},
{"Idempotency-Key", "{{order_id}}"}
},
.json = "order"
})
```
Combined, concurrent fan-out:
```c
fetch(
{"https://api.weather.dev/now?city={{city}}", .set_key = "weather"},
{"https://api.news.dev/headlines?topic={{topic}}", .set_key = "news"},
{"https://api.quotes.dev/random", .set_key = "quote"}
)
```
**HTTP methods (for `.method`):** `m_get`, `m_post`, `m_put`, `m_patch`, `m_delete`, `m_sse_method`
#### exec
Calls a C function or block with access to the context via the Imperative API. `exec()` is where business logic and data shaping lives: enriching query results with computed fields, aggregating across rows, transforming data between steps, calling external C libraries, blocking I/O, CPU-heavy work. Execution is dispatched to the shared thread pool, which releases the reactor; the pipeline resumes on the original reactor when the call returns. To trigger an error/repair pipeline from inside, call `error_set()`.
**Block *(pos)***: inline block, for short logic specific to this pipeline. Here, attaching each challenger's opponent id so the template can render two voting forms with the right winner/loser pairing:
```c
exec(^(){
auto t = get("challengers");
record_set(table_get(t, 0), "opponent_id",
record_get(table_get(t, 1), "id"));
record_set(table_get(t, 1), "opponent_id",
record_get(table_get(t, 0), "id"));
})
```
**`.call`**: reference to a named C function, for logic reuse across pipelines.
```c
exec(.call = assign_opponents)
```
Inside `exec` blocks and functions, context, memory, errors, tables, and records are manipulated through the [Imperative API](#imperative-api).
#### emit
Triggers an internal pub/sub event. Subscribers in other modules react in their `.events` pipelines, with no direct dependency on the emitter. See [Event Pipelines](#event-pipelines).
**Event name *(pos)***: name of the event to publish.
```c
emit("todo_created")
```
#### task
Adds a named job to the task database; the calling pipeline continues immediately. Task reactors pick up queued jobs and execute their pipelines. See [Task Pipelines](#task-pipelines).
**Task name *(pos)***: name of a task defined in `.tasks`.
```c
task("recount_todos")
```
#### sse
Pushes a Server-Sent Event. With `.channel`, the event is broadcast to all clients on that channel. Without `.channel`, the event is returned directly to the requesting client. See [Resource Pipelines](#resource-pipelines).
**`.channel` *(pos)***: channel to broadcast on; supports `{{interpolation}}`.
```c
sse(.channel = "todos/{{user_id}}", .event = "new_todo", .data = {"{{todo}}"})
```
**`.event`**: SSE `event:` line value.
```c
sse(.event = "ping")
```
**`.data`**: array of strings, one per SSE `data:` line (multi-line data).
```c
sse(.event = "msg", .data = {"line one", "line two"})
```
**`.comment`**: SSE `:` comment line value, useful for keep-alives.
```c
sse(.comment = "keep-alive")
```
Combined:
```c
sse(
.channel = "todos/{{user_id}}",
.event = "todo_updated",
.data = {"id: {{todo_id}}", "title: {{title}}"},
.comment = "broadcast at {{timestamp}}"
)
```
#### render
Outputs a template using the current context. Templates are referenced by name from `.context` or inlined.
**`.template_key` *(pos)***: asset name in `.context`. The asset is a template.
```c
render("todos")
```
**`.template`**: inline template string.
```c
render(.template = "