commit 088a9de3607219e03c6a581d86d5c31dea4a561c Author: nightshade Date: Thu Jul 24 12:46:01 2025 -0500 MaCH repo diff --git a/00_hello_text/main.c b/00_hello_text/main.c new file mode 100644 index 0000000..8bc8d9e --- /dev/null +++ b/00_hello_text/main.c @@ -0,0 +1,13 @@ +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", .mime = mime_txt, + .get = { + render(.template= "hello") + } + } + } + }; +} diff --git a/01-multi-reactor-architecture.svg b/01-multi-reactor-architecture.svg new file mode 100644 index 0000000..8c145d1 --- /dev/null +++ b/01-multi-reactor-architecture.svg @@ -0,0 +1,155 @@ + + + + + + + + + + + + + + + + + + Multi-Reactor Architecture + + + request/task/cpu ratio configurable in compose.yml + + + + HTTP Clients + + + + + + + + + REQUEST REACTORS + + + + Core 0 + event loop + + pipeline + + + + Core 1 + event loop + + pipeline + + + + + + + + Core N + event loop + + pipeline + + + + TASK REACTORS + + + + Core + event loop + + cron / jobs + + + + Core + event loop + + cron / jobs + + + + + + + + Core + event loop + + cron / jobs + + + + mach_tasks + database + + + + + + + + SHARED THREAD POOL + remaining cores + + + work queue + + + + + + + + + + + + + + + + + + + + + Thread 1 + + + ... + + + Thread N + + + on complete, resumes pipeline on reactor + + + + + invoke() + + + + invoke() + + + + + task() + + + + task() + + diff --git a/01_hello_world_text/main.c b/01_hello_world_text/main.c new file mode 100644 index 0000000..7643d97 --- /dev/null +++ b/01_hello_world_text/main.c @@ -0,0 +1,18 @@ +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", .mime = mime_txt, + .get = { + validate({"name", + .validation = "^\\S{1,16}$", + .fallback = "world", + .message = "must be 1-16 characters, no spaces" + }), + render(.template = "Hello {{name}}") + } + } + } + }; +} diff --git a/02-request-pipeline-flow.svg b/02-request-pipeline-flow.svg new file mode 100644 index 0000000..0303b6f --- /dev/null +++ b/02-request-pipeline-flow.svg @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + POST /todos + + + .before + + + + session() + + + + + + + .post pipeline + + + + param() + validate title + + + + + + + + db() + INSERT todo + + + + + + + + emit() + todo_created + + + + + + + + redirect() + 302 → /todos + + + + PIPELINE CONTEXT + + + + user_id + ← session + + + title + ← param + + + todo + ← db .set + + + base_layout + ← .context + diff --git a/02_hello_world_html/main.c b/02_hello_world_html/main.c new file mode 100644 index 0000000..b78873c --- /dev/null +++ b/02_hello_world_html/main.c @@ -0,0 +1,25 @@ +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", + .get = { + validate({"name", + .validation = "^\\S{1,16}$", + .fallback = "world", + .message = "must be 1-16 characters, no spaces" + }), + render(.template = + "" + "" + "" + "

Hello {{name}}

" + "" + "" + ) + } + } + } + }; +} diff --git a/03-event-pub-sub.svg b/03-event-pub-sub.svg new file mode 100644 index 0000000..1bc924b --- /dev/null +++ b/03-event-pub-sub.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + todos module + .post pipeline: + param() → db() + → emit("todo_created") + → redirect("/todos") + + + .publishes + + todo_created → user_id, title + + + + Event Bus + + + + + + + + + activity module + .events: + "todo_created" → db(log.sql) + + + + + + + + + notifications module + .events: + "todo_created" → call(notify) + + + + + + + Modules are decoupled — publishers don't know about subscribers + diff --git a/03_hello_world_html_db/main.c b/03_hello_world_html_db/main.c new file mode 100644 index 0000000..7511d2b --- /dev/null +++ b/03_hello_world_html_db/main.c @@ -0,0 +1,48 @@ +#include +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", + .get = { + query({ + .set_key = "greeting", + .db = "hello_db", + .query = + "select name " + "from greetings " + "limit 1;" + }), + render(.template = + "" + "" + "{{#greeting}}" + "

Hello {{name}}

" + "{{/greeting}}" + "" + "" + ) + } + } + }, + + .databases = {{ + .engine = sqlite_db, + .name = "hello_db", + .connect = "file:hello.db?mode=rwc", + .migrations = { + "CREATE TABLE greetings (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL" + ");" + }, + .seeds = { + "INSERT INTO greetings(name)" + "VALUES('World');" + } + }}, + + .modules = {sqlite} + }; +} diff --git a/04-error-resolution.svg b/04-error-resolution.svg new file mode 100644 index 0000000..3fdde07 --- /dev/null +++ b/04-error-resolution.svg @@ -0,0 +1,46 @@ + + + + + + + + + Root Config + .errors = { 404 → render 404.html } + + + + + + Module Config + .errors = { ... } + + + + + + Route /todos/:id + .errors = { ... } + + + + ! + 404 raised in pipeline step + + + + + + + + + + no 404 handler → bubble up + + + + + + ✓ matched → render 404.html + diff --git a/04_todo/404.mustache.html b/04_todo/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/04_todo/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

not found

+ {{/body}} +{{/layout}} diff --git a/04_todo/5xx.mustache.html b/04_todo/5xx.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/04_todo/5xx.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

error

+ {{/body}} +{{/layout}} diff --git a/04_todo/about.mustache.html b/04_todo/about.mustache.html new file mode 100644 index 0000000..3b8b864 --- /dev/null +++ b/04_todo/about.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

about us

+ {{/body}} +{{/layout}} diff --git a/04_todo/contact.mustache.html b/04_todo/contact.mustache.html new file mode 100644 index 0000000..6ef1152 --- /dev/null +++ b/04_todo/contact.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

contact us

+ {{/body}} +{{/layout}} diff --git a/04_todo/create_todo.sql b/04_todo/create_todo.sql new file mode 100644 index 0000000..a0602fc --- /dev/null +++ b/04_todo/create_todo.sql @@ -0,0 +1,2 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}); diff --git a/04_todo/create_todos_table.sql b/04_todo/create_todos_table.sql new file mode 100644 index 0000000..e0249d1 --- /dev/null +++ b/04_todo/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/04_todo/delete_todo.sql b/04_todo/delete_todo.sql new file mode 100644 index 0000000..4c7b296 --- /dev/null +++ b/04_todo/delete_todo.sql @@ -0,0 +1,3 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}}; diff --git a/04_todo/get_todos.sql b/04_todo/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/04_todo/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/04_todo/home.mustache.html b/04_todo/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/04_todo/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

home

+ {{/body}} +{{/layout}} diff --git a/04_todo/layout.mustache.html b/04_todo/layout.mustache.html new file mode 100644 index 0000000..37b917a --- /dev/null +++ b/04_todo/layout.mustache.html @@ -0,0 +1,23 @@ + + + + + +

+ {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

+ + {{$body}} + {{/body}} + + diff --git a/04_todo/main.c b/04_todo/main.c new file mode 100644 index 0000000..a519eea --- /dev/null +++ b/04_todo/main.c @@ -0,0 +1,132 @@ +#include +#include +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", {session()}, + .get = { + render("home") + } + }, + + {"about", "/about", {session()}, + .get = { + render("about") + } + }, + + {"contact", "/contact", {session()}, + .get = { + render("contact") + } + }, + + {"todos", "/todos", {logged_in()}, + .get = { + query({"get_todos", + .set_key = "todos", + .db = "todos_db" + }), + render("todos") + }, + + .post = { + validate({"title", + .validation = "^\\S{1,16}$", + .message = "must be 1-16 characters, no spaces" + }), + query({"create_todo", + .db = "todos_db" + }), + redirect("todos") + } + }, + + {"todo", "/todos/:id", { + logged_in(), + validate({"id", + .validation = "^\\d{1,10}$", + .message = "must be between 1-9999999999" + })}, + + .patch = { + validate({"finished", + .optional = true, + .validation = "1", + .message = "must be 1" + }), + find({"update_todo", + .db = "todos_db" + }), + redirect("todos") + }, + + .delete = { + find({"delete_todo", + .db = "todos_db" + }), + redirect("todos") + } + } + }, + + .errors = { + {http_error, { + render("5xx") + }}, + + {http_not_found, { + render("404") + }} + }, + + .context = { + {"layout", (asset){ + #embed "layout.mustache.html" + }}, + {"home", (asset){ + #embed "home.mustache.html" + }}, + {"about", (asset){ + #embed "about.mustache.html" + }}, + {"contact", (asset){ + #embed "contact.mustache.html" + }}, + {"5xx", (asset){ + #embed "5xx.mustache.html" + }}, + {"404", (asset){ + #embed "404.mustache.html" + }}, + {"todos", (asset){ + #embed "todos.mustache.html" + }}, + {"get_todos", (asset){ + #embed "get_todos.sql" + }}, + {"create_todo", (asset){ + #embed "create_todo.sql" + }}, + {"update_todo", (asset){ + #embed "update_todo.sql" + }}, + {"delete_todo", (asset){ + #embed "delete_todo.sql" + }} + }, + + .databases = {{ + .engine = sqlite_db, + .name = "todos_db", + .connect = "file:{{user_id}}_todo.db?mode=rwc", + .migrations = {(asset){ + #embed "create_todos_table.sql" + }} + }}, + + .modules = {sqlite, session_auth} + }; +} diff --git a/04_todo/public/favicon.png b/04_todo/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/04_todo/todos.mustache.html b/04_todo/todos.mustache.html new file mode 100644 index 0000000..0b5b7e0 --- /dev/null +++ b/04_todo/todos.mustache.html @@ -0,0 +1,32 @@ +{{< layout}} + {{$body}} +
+ + +
+ {{^todos}} +

no todos

+ {{/todos}} + {{#todos}} + {{#.}} +
+
+ + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
+
+ + +
+
+ {{/.}} + {{/todos}} + {{/body}} +{{/layout}} diff --git a/04_todo/update_todo.sql b/04_todo/update_todo.sql new file mode 100644 index 0000000..e1d2850 --- /dev/null +++ b/04_todo/update_todo.sql @@ -0,0 +1,4 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}}; diff --git a/05-app-composition-tree.svg b/05-app-composition-tree.svg new file mode 100644 index 0000000..63cff21 --- /dev/null +++ b/05-app-composition-tree.svg @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + mach() — root + + + + + + + + + + + + + + sqlite_config() + + + todos_config() + + + auth_config() + + + + + + + + + + .databases + .resources + .events + + + .publishes + .context + .errors + + + First registration wins — root can override module defaults + diff --git a/05_todo_sse_datastar/404.mustache.html b/05_todo_sse_datastar/404.mustache.html new file mode 100644 index 0000000..f9fef41 --- /dev/null +++ b/05_todo_sse_datastar/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

not found

+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/5xx.mustache.html b/05_todo_sse_datastar/5xx.mustache.html new file mode 100644 index 0000000..75a79b4 --- /dev/null +++ b/05_todo_sse_datastar/5xx.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

error

+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/about.mustache.html b/05_todo_sse_datastar/about.mustache.html new file mode 100644 index 0000000..3b8b864 --- /dev/null +++ b/05_todo_sse_datastar/about.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

about us

+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/contact.mustache.html b/05_todo_sse_datastar/contact.mustache.html new file mode 100644 index 0000000..6ef1152 --- /dev/null +++ b/05_todo_sse_datastar/contact.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

contact us

+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/create_todo.sql b/05_todo_sse_datastar/create_todo.sql new file mode 100644 index 0000000..5193f91 --- /dev/null +++ b/05_todo_sse_datastar/create_todo.sql @@ -0,0 +1,3 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}) +returning id, title, finished; diff --git a/05_todo_sse_datastar/create_todos_table.sql b/05_todo_sse_datastar/create_todos_table.sql new file mode 100644 index 0000000..d7c962f --- /dev/null +++ b/05_todo_sse_datastar/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/05_todo_sse_datastar/delete_todo.sql b/05_todo_sse_datastar/delete_todo.sql new file mode 100644 index 0000000..44fda1f --- /dev/null +++ b/05_todo_sse_datastar/delete_todo.sql @@ -0,0 +1,4 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}} +returning id; diff --git a/05_todo_sse_datastar/get_todos.sql b/05_todo_sse_datastar/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/05_todo_sse_datastar/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/05_todo_sse_datastar/home.mustache.html b/05_todo_sse_datastar/home.mustache.html new file mode 100644 index 0000000..eb8e808 --- /dev/null +++ b/05_todo_sse_datastar/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

home

+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/layout.mustache.html b/05_todo_sse_datastar/layout.mustache.html new file mode 100644 index 0000000..7ad1e8e --- /dev/null +++ b/05_todo_sse_datastar/layout.mustache.html @@ -0,0 +1,25 @@ + + + + {{$head}} + {{/head}} + + +

+ {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

+ + {{$body}} + {{/body}} + + diff --git a/05_todo_sse_datastar/main.c b/05_todo_sse_datastar/main.c new file mode 100644 index 0000000..db6cb2c --- /dev/null +++ b/05_todo_sse_datastar/main.c @@ -0,0 +1,151 @@ +#include +#include +#include +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", {session()}, + .get = { + render("home") + } + }, + + {"about", "/about", {session()}, + .get = { + render("about") + } + }, + + {"contact", "/contact", {session()}, + .get = { + render("contact") + } + }, + + {"todos", "/todos", {logged_in()}, + .sse = {"todos:{{user_id}}"}, + + .get = { + query({"get_todos", + .set_key = "todos", + .db = "todos_db" + }), + render("todos") + }, + + .post = { + validate({"title", + .validation = "^\\S{1,16}$", + .message = "must be 1-16 characters, no spaces" + }), + query({"create_todo", + .set_key = "todo", + .db = "todos_db" + }), + ds_sse("todos:{{user_id}}", + .target = "todos", + .mode = mode_prepend, + .elements = {"todo"} + ) + } + }, + + {"todo", "/todos/:id", { + logged_in(), + validate({"id", + .validation = "^\\d{1,10}$", + .message = "must be between 1-9999999999" + })}, + + .patch = { + validate({"finished", + .optional = true, + .validation = "1", + .message = "must be 1" + }), + find({"update_todo", + .set_key = "todo", + .db = "todos_db" + }), + ds_sse("todos:{{user_id}}", + .target = "todo_{{id}}", + .mode = mode_replace, + .elements = {"todo"} + ) + }, + + .delete = { + find({"delete_todo", + .db = "todos_db" + }), + ds_sse("todos:{{user_id}}", + .target = "todo_{{id}}", + .mode = mode_remove + ) + } + } + }, + + .errors = { + {http_error, { + render("5xx") + }}, + + {http_not_found, { + render("404") + }} + }, + + .context = { + {"layout", (asset){ + #embed "layout.mustache.html" + }}, + {"home", (asset){ + #embed "home.mustache.html" + }}, + {"about", (asset){ + #embed "about.mustache.html" + }}, + {"contact", (asset){ + #embed "contact.mustache.html" + }}, + {"5xx", (asset){ + #embed "5xx.mustache.html" + }}, + {"404", (asset){ + #embed "404.mustache.html" + }}, + {"todos", (asset){ + #embed "todos.mustache.html" + }}, + {"todo", (asset){ + #embed "todo.mustache.html" + }}, + {"get_todos", (asset){ + #embed "get_todos.sql" + }}, + {"create_todo", (asset){ + #embed "create_todo.sql" + }}, + {"update_todo", (asset){ + #embed "update_todo.sql" + }}, + {"delete_todo", (asset){ + #embed "delete_todo.sql" + }} + }, + + .databases = {{ + .engine = sqlite_db, + .name = "todos_db", + .connect = "file:todo.db?mode=rwc", + .migrations = {(asset){ + #embed "create_todos_table.sql" + }} + }}, + + .modules = {sqlite, datastar, session_auth} + }; +} diff --git a/05_todo_sse_datastar/public/favicon.png b/05_todo_sse_datastar/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/05_todo_sse_datastar/todo.mustache.html b/05_todo_sse_datastar/todo.mustache.html new file mode 100644 index 0000000..8654107 --- /dev/null +++ b/05_todo_sse_datastar/todo.mustache.html @@ -0,0 +1,10 @@ +
+ {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
diff --git a/05_todo_sse_datastar/todos.mustache.html b/05_todo_sse_datastar/todos.mustache.html new file mode 100644 index 0000000..9699a9f --- /dev/null +++ b/05_todo_sse_datastar/todos.mustache.html @@ -0,0 +1,21 @@ +{{< layout}} + {{$head}} + {{> datastar_script }} + {{/head}} + {{$body}} + + +
+ {{^todos}} +

no todos

+ {{/todos}} + {{#todos}} + {{#.}} + {{> todo}} + {{/.}} + {{/todos}} +
+ {{/body}} +{{/layout}} diff --git a/05_todo_sse_datastar/update_todo.sql b/05_todo_sse_datastar/update_todo.sql new file mode 100644 index 0000000..1c67e44 --- /dev/null +++ b/05_todo_sse_datastar/update_todo.sql @@ -0,0 +1,5 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}} +returning id, title, finished; diff --git a/06-middleware-scoping.svg b/06-middleware-scoping.svg new file mode 100644 index 0000000..1d59cd5 --- /dev/null +++ b/06-middleware-scoping.svg @@ -0,0 +1,52 @@ + + + + + + + + + Global .before + session() + Global .after + call(log_request) + + + + Resource .before + logged_in() + Resource .after + + + + Route Pipeline — POST /todos + + + + param() + + + + + + db() + + + + + + emit() + + + + + + redirect() + + + Route .before runs first inside this scope + Route .after runs last inside this scope + + + Execution order: global .before → resource .before → route pipeline → resource .after → global .after + diff --git a/06_todo_events/activity/activity.c b/06_todo_events/activity/activity.c new file mode 100644 index 0000000..1ccfefb --- /dev/null +++ b/06_todo_events/activity/activity.c @@ -0,0 +1,52 @@ +#include +#include +#include + +config activity(){ + return (config) { + .name = "activity", + + .resources = { + {"activity", "/activity", {logged_in()}, + .get = { + query({"get_activities", + .set_key = "activity", + .db = "activity_db" + }), + render("activity") + } + } + }, + + .context = { + {"activity", (asset){ + #embed "activity.mustache.html" + }}, + {"get_activities", (asset){ + #embed "get_activities.sql" + }}, + {"insert_activity", (asset){ + #embed "insert_activity.sql" + }} + }, + + .events = { + {"todo_created", { + query({"insert_activity", + .db = "activity_db" + }) + }} + }, + + .databases = {{ + .name = "activity_db", + .engine = sqlite_db, + .connect = "file:activity.db?mode=rwc", + .migrations = {(asset){ + #embed "create_activity_table.sql" + }} + }}, + + .modules = {sqlite, session_auth} + }; +} diff --git a/06_todo_events/activity/activity.mustache.html b/06_todo_events/activity/activity.mustache.html new file mode 100644 index 0000000..fc76f48 --- /dev/null +++ b/06_todo_events/activity/activity.mustache.html @@ -0,0 +1,13 @@ +{{< layout}} + {{$body}} + {{^activity}} +

no activity

+ {{/activity}} + {{#activity}} +

activity

+ {{#.}} +

{{action}}: {{title}} ({{created_at}})

+ {{/.}} + {{/activity}} + {{/body}} +{{/layout}} diff --git a/06_todo_events/activity/create_activity_table.sql b/06_todo_events/activity/create_activity_table.sql new file mode 100644 index 0000000..51d198a --- /dev/null +++ b/06_todo_events/activity/create_activity_table.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS activity ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + action TEXT NOT NULL, + title TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_activity_user_id ON activity(user_id); diff --git a/06_todo_events/activity/get_activities.sql b/06_todo_events/activity/get_activities.sql new file mode 100644 index 0000000..b4a272d --- /dev/null +++ b/06_todo_events/activity/get_activities.sql @@ -0,0 +1,5 @@ +select action, title, created_at +from activity +where user_id = {{user_id}} +order by created_at desc +limit 50; diff --git a/06_todo_events/activity/insert_activity.sql b/06_todo_events/activity/insert_activity.sql new file mode 100644 index 0000000..70703c3 --- /dev/null +++ b/06_todo_events/activity/insert_activity.sql @@ -0,0 +1,2 @@ +insert into activity(user_id, action, title) +values({{user_id}}, 'created', {{title}}); diff --git a/06_todo_events/main.c b/06_todo_events/main.c new file mode 100644 index 0000000..bf1383b --- /dev/null +++ b/06_todo_events/main.c @@ -0,0 +1,43 @@ +#include +#include +#include "todos/todos.c" +#include "activity/activity.c" + +config mach(){ + return (config) { + .resources = { + {"home", "/", {session()}, + .get = { + render("home") + } + } + }, + + .errors = { + {http_error, { + render("5xx") + }}, + + {http_not_found, { + render("404") + }} + }, + + .context = { + {"layout", (asset){ + #embed "static/layout.mustache.html" + }}, + {"home", (asset){ + #embed "static/home.mustache.html" + }}, + {"5xx", (asset){ + #embed "static/5xx.mustache.html" + }}, + {"404", (asset){ + #embed "static/404.mustache.html" + }} + }, + + .modules = {todos, activity, session_auth} + }; +} diff --git a/06_todo_events/public/favicon.png b/06_todo_events/public/favicon.png new file mode 100644 index 0000000..e69de29 diff --git a/06_todo_events/static/404.mustache.html b/06_todo_events/static/404.mustache.html new file mode 100644 index 0000000..d4685b3 --- /dev/null +++ b/06_todo_events/static/404.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

not found

+ {{/body}} +{{/layout}}; diff --git a/06_todo_events/static/5xx.mustache.html b/06_todo_events/static/5xx.mustache.html new file mode 100644 index 0000000..1ed977c --- /dev/null +++ b/06_todo_events/static/5xx.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

error

+ {{/body}} +{{/layout}}; diff --git a/06_todo_events/static/home.mustache.html b/06_todo_events/static/home.mustache.html new file mode 100644 index 0000000..2fe6db9 --- /dev/null +++ b/06_todo_events/static/home.mustache.html @@ -0,0 +1,5 @@ +{{< layout}} + {{$body}} +

home

+ {{/body}} +{{/layout}}; diff --git a/06_todo_events/static/layout.mustache.html b/06_todo_events/static/layout.mustache.html new file mode 100644 index 0000000..4948201 --- /dev/null +++ b/06_todo_events/static/layout.mustache.html @@ -0,0 +1,20 @@ + + + + + +

+ {{^user}} + sign in + {{/user}} + {{#user}} + welcome, {{short_name}} + {{/user}} +

+ + {{$body}} + {{/body}} + + diff --git a/06_todo_events/todos/create_todo.sql b/06_todo_events/todos/create_todo.sql new file mode 100644 index 0000000..a0602fc --- /dev/null +++ b/06_todo_events/todos/create_todo.sql @@ -0,0 +1,2 @@ +insert into todos(user_id, title) +values({{user_id}}, {{title}}); diff --git a/06_todo_events/todos/create_todos_table.sql b/06_todo_events/todos/create_todos_table.sql new file mode 100644 index 0000000..e0249d1 --- /dev/null +++ b/06_todo_events/todos/create_todos_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + title TEXT NOT NULL, + finished INTEGER CHECK(finished IN (1)) +); +CREATE INDEX IF NOT EXISTS idx_todos_user_id ON todos(user_id); diff --git a/06_todo_events/todos/delete_todo.sql b/06_todo_events/todos/delete_todo.sql new file mode 100644 index 0000000..4c7b296 --- /dev/null +++ b/06_todo_events/todos/delete_todo.sql @@ -0,0 +1,3 @@ +delete from todos +where user_id = {{user_id}} + and id = {{id}}; diff --git a/06_todo_events/todos/get_todos.sql b/06_todo_events/todos/get_todos.sql new file mode 100644 index 0000000..ec59e5d --- /dev/null +++ b/06_todo_events/todos/get_todos.sql @@ -0,0 +1,3 @@ +select id, title, finished +from todos +where user_id = {{user_id}}; diff --git a/06_todo_events/todos/todos.c b/06_todo_events/todos/todos.c new file mode 100644 index 0000000..70cdb3d --- /dev/null +++ b/06_todo_events/todos/todos.c @@ -0,0 +1,98 @@ +#include +#include +#include + +config todos(){ + return (config) { + .name = "todos", + + .resources = { + {"todos", "/todos", {logged_in()}, + .get = { + query({"get_todos", + .set_key = "todos", + .db = "todos_db" + }), + render("todos") + }, + + .post = { + validate({"title", + .validation = "^\\S{1,16}$", + .message = "must be 1-16 characters, no spaces" + }), + query({"create_todo", + .db = "todos_db" + }), + emit("todo_created"), + redirect("todos") + } + }, + + {"todo", "/todos/:id", { + logged_in(), + validate({"id", + .validation = "^\\d{1,10}$", + .message = "must be between 1-9999999999" + })}, + + .patch = { + validate({"finished", + .optional = true, + .validation = "1", + .message = "must be 1" + }), + find({"update_todo", + .db = "todos_db" + }), + redirect("todos") + }, + + .delete = { + find({"delete_todo", + .db = "todos_db" + }), + redirect("todos") + } + } + }, + + .context = { + {"todos", (asset){ + #embed "todos.mustache.html" + }}, + {"get_todos", (asset){ + #embed "get_todos.sql" + }}, + {"create_todos", (asset){ + #embed "create_todo.sql" + }}, + {"update_todo", (asset){ + #embed "update_todo.sql" + }}, + {"delete_todo", (asset){ + #embed "delete_todo.sql" + }} + }, + + .publishes = { + {"todo_created", + .with = { + "user_id", + "title" + } + } + }, + + .databases = {{ + .engine = sqlite_db, + .name = "todos_db", + .connect = "file:todo.db?mode=rwc", + .migrations = {(asset){ + #embed "create_todos_table.sql" + }} + }}, + + .modules = {sqlite, session_auth} + }; +} diff --git a/06_todo_events/todos/todos.mustache.html b/06_todo_events/todos/todos.mustache.html new file mode 100644 index 0000000..0b5b7e0 --- /dev/null +++ b/06_todo_events/todos/todos.mustache.html @@ -0,0 +1,32 @@ +{{< layout}} + {{$body}} +
+ + +
+ {{^todos}} +

no todos

+ {{/todos}} + {{#todos}} + {{#.}} +
+
+ + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
+
+ + +
+
+ {{/.}} + {{/todos}} + {{/body}} +{{/layout}} diff --git a/06_todo_events/todos/update_todo.sql b/06_todo_events/todos/update_todo.sql new file mode 100644 index 0000000..e1d2850 --- /dev/null +++ b/06_todo_events/todos/update_todo.sql @@ -0,0 +1,4 @@ +update todos +set finished = {{finished}} +where user_id = {{user_id}} + and id = {{id}}; diff --git a/07-context-scoping.svg b/07-context-scoping.svg new file mode 100644 index 0000000..0dd81ea --- /dev/null +++ b/07-context-scoping.svg @@ -0,0 +1,50 @@ + + + + + + + + + Global .context + base_layout, site_name + + + + Resource .context + layout, sidebar + + + + Route Pipeline — GET /todos + + + + db() → todos + + + + + + call() → count + + + + + + render() + + + render() sees: base_layout, site_name, layout, sidebar, todos, count + Context merges top-down; first named registration wins + + + + + + + + + + Context cascades: global .context → resource .context → pipeline steps add to context → render() merges all + diff --git a/07_roundest_pokemon_htmx/README.md b/07_roundest_pokemon_htmx/README.md new file mode 100644 index 0000000..e958b0f --- /dev/null +++ b/07_roundest_pokemon_htmx/README.md @@ -0,0 +1 @@ +compare to https://github.com/t3dotgg/1app5stacks diff --git a/07_roundest_pokemon_htmx/create_pokemons_table.sql b/07_roundest_pokemon_htmx/create_pokemons_table.sql new file mode 100644 index 0000000..f820320 --- /dev/null +++ b/07_roundest_pokemon_htmx/create_pokemons_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS pokemons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + sprite TEXT NOT NULL, + wins INTEGER NOT NULL DEFAULT 0, + loses INTEGER NOT NULL DEFAULT 0 +); diff --git a/07_roundest_pokemon_htmx/get_challengers.sql b/07_roundest_pokemon_htmx/get_challengers.sql new file mode 100644 index 0000000..57f2514 --- /dev/null +++ b/07_roundest_pokemon_htmx/get_challengers.sql @@ -0,0 +1,4 @@ +select id, name, sprite +from pokemons +order by random() +limit 2; diff --git a/07_roundest_pokemon_htmx/get_results.sql b/07_roundest_pokemon_htmx/get_results.sql new file mode 100644 index 0000000..a4105ba --- /dev/null +++ b/07_roundest_pokemon_htmx/get_results.sql @@ -0,0 +1,5 @@ +select id, name, sprite, wins, loses, + cast(wins as real) / nullif(loses, 0) as ratio_of_wins_to_loses, + row_number() over (order by (cast(wins as real) / nullif(loses, 0)) desc) as rank +from pokemons +order by ratio_of_wins_to_loses desc; diff --git a/07_roundest_pokemon_htmx/home.mustache.html b/07_roundest_pokemon_htmx/home.mustache.html new file mode 100644 index 0000000..1484ccd --- /dev/null +++ b/07_roundest_pokemon_htmx/home.mustache.html @@ -0,0 +1,53 @@ + + + + Roundest (MaCH Version) + {{> htmx_script}} + {{> tailwind_script}} + + +
+ +
+ {{$body}} +
+

Vote for which is roundest

+
+ {{#challengers}} +
+
+ {{name}} +
+ #{{id}} +

{{name}}

+ + + +
+
+
+ {{/challengers}} +
+
+ {{/body}} +
+ +
+ + diff --git a/07_roundest_pokemon_htmx/main.c b/07_roundest_pokemon_htmx/main.c new file mode 100644 index 0000000..aaff388 --- /dev/null +++ b/07_roundest_pokemon_htmx/main.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include + +config mach(){ + return (config) { + .resources = { + {"home", "/", + .get = { + query({"get_challengers", + .set_key = "challengers", + .db = "pokemon_db" + }), + exec(^(){ + auto const t = get("challengers"); + auto const p0 = table_get(t, 0); + auto const p1 = table_get(t, 1); + record_set(p0, "opponent_id", record_get(p1, "id")); + record_set(p1, "opponent_id", record_get(p0, "id")); + }), + render("home") + }, + + .post = { + validate( + {"winner", + .validation = "^\\d{1,8}$", + .message = "must be 1-99999999" + }, + {"loser", + .validation = "^\\d{1,8}$", + .message = "must be 1-99999999" + } + ), + find({"vote", + .db = "pokemon_db" + }), + reroute("home") + } + }, + + {"result", "/results", + .get = { + query({"get_results", + .set_key = "results", + .db = "pokemon_db" + }), + render("results") + } + } + }, + + .context = { + {"home", (asset){ + #embed "home.mustache.html" + }}, + {"results", (asset){ + #embed "results.mustache.html" + }}, + {"get_challengers", (asset){ + #embed "get_challengers.sql" + }}, + {"vote", (asset){ + #embed "vote.sql" + }}, + {"get_results", (asset){ + #embed "get_results.sql" + }} + }, + + .databases = {{ + .name = "pokemon_db", + .engine = sqlite_db, + .connect = "file::memory:?cache=shared", + .migrations = {(asset){ + #embed "create_pokemons_table.sql" + }} + }}, + + .modules = {htmx, sqlite, tailwind} + }; +} diff --git a/07_roundest_pokemon_htmx/results.mustache.html b/07_roundest_pokemon_htmx/results.mustache.html new file mode 100644 index 0000000..5f729d6 --- /dev/null +++ b/07_roundest_pokemon_htmx/results.mustache.html @@ -0,0 +1,28 @@ +{{< home}} + {{$body}} +
+
+ {{#results}} +
+
+ {{rank}} +
+ {{name}} +
+
#{{id}}
+

{{name}}

+
+
+
+ {{ratio_of_wins_to_loses}} +
+
+ {{wins}}W - {{loses}}L +
+
+
+ {{/results}} +
+
+ {{/body}} +{{/home}} diff --git a/07_roundest_pokemon_htmx/vote.sql b/07_roundest_pokemon_htmx/vote.sql new file mode 100644 index 0000000..6ab1ae9 --- /dev/null +++ b/07_roundest_pokemon_htmx/vote.sql @@ -0,0 +1,8 @@ +begin transaction; +update pokemons + set wins = wins + 1 + where id = {{winner}}; +update pokemons + set loses = loses + 1 + where id = {{loser}}; +commit; diff --git a/08-sse-datastar-flow.svg b/08-sse-datastar-flow.svg new file mode 100644 index 0000000..47bd211 --- /dev/null +++ b/08-sse-datastar-flow.svg @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + SSE / Datastar — Real-Time Push + + + + + Client A + GET /todos + .sse channel connected + + + + + Client B + GET /todos + .sse channel connected + + + + Channel + todos/{{user_id}} + + + + + + + + subscribe + subscribe + + + + POST /todos — another client submits a form + + + + param() + + + + + + db() + + + + + + + datastar() / sse() + .channel = "todos/{{user_id}}" + + + + + + push to channel + + + + + + + + + broadcast + broadcast + + + + DATASTAR MODE + .target = "todos" + .mode = mode_prepend + + + Without .channel, events push directly to the requesting client + diff --git a/08_todo_tasks/main.c b/08_todo_tasks/main.c new file mode 100644 index 0000000..294e51f --- /dev/null +++ b/08_todo_tasks/main.c @@ -0,0 +1,300 @@ +#include +#include +#include + +config mach() { + return (config) { + + .resources = { + {"home", "/", + .get = { + reroute("todos") + } + }, + + {"todos", "/todos", + .get = { + query( + {.set_key = "todos", + .db = "todos_db", + .query = + "SELECT id, title, done, created_at " + "FROM todos ORDER BY created_at DESC;" + }, + {.set_key = "stats", + .db = "todos_db", + .query = + "SELECT total, done FROM stats WHERE id = 1;" + } + ), + render( + "" + "" + "MACH Tasks Demo" + "{{> tailwind_script}}" + "" + "" + "
" + "

Todos

" + "{{#stats}}" + "

" + "{{done}} of {{total}} done" + "

" + "{{/stats}}" + "
" + "" + "" + "
" + "{{#todos}}" + "
" + "
" + "" + "{{#done}}" + "" + "{{/done}}" + "{{^done}}" + "" + "{{/done}}" + "
" + "{{#done}}" + "{{title}}" + "{{/done}}" + "{{^done}}" + "{{title}}" + "{{/done}}" + "
" + "" + "" + "
" + "
" + "{{/todos}}" + "{{^todos}}" + "

No todos yet.

" + "{{/todos}}" + "" + "View worker activity log →" + "" + "
" + "" + "" + ) + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "Title cannot be empty" + }), + query({ + .db = "todos_db", + .query = + "INSERT INTO todos(title) VALUES({{title}});" + }), + query({"recount", + .db = "todos_db" + }), + task("log_created"), + redirect("todos") + } + }, + + {"todo", "/todos/:id", { + validate({"id", + .validation = validate_positive, + .message = "Invalid id" + })}, + + .put = { + query({ + .db = "todos_db", + .query = + "UPDATE todos " + "SET done = CASE WHEN done = 0 THEN 1 ELSE 0 END " + "WHERE id = {{id}};" + }), + query({"recount", + .db = "todos_db" + }), + task("log_toggled"), + redirect("todos") + }, + + .delete = { + query({ + .db = "todos_db", + .query = + "DELETE FROM todos WHERE id = {{id}};" + }), + query({"recount", + .db = "todos_db" + }), + task("log_deleted"), + redirect("todos") + } + }, + + {"activity", "/activity", + .get = { + query({ + .set_key = "logs", + .db = "todos_db", + .query = + "SELECT action, detail, ran_at " + "FROM activity_log ORDER BY ran_at DESC LIMIT 50;" + }), + render( + "" + "" + "Worker Activity" + "{{> tailwind_script}}" + "" + "" + "
" + "

Worker Activity

" + "

" + "Task executions from the worker reactor" + "

" + "" + "← Back to todos" + "" + "{{#logs}}" + "
" + "{{action}}" + "{{detail}}" + "{{ran_at}}" + "
" + "{{/logs}}" + "{{^logs}}" + "

No activity yet.

" + "{{/logs}}" + "
" + "" + "" + ) + } + } + }, + + .context = { + {"recount", + "UPDATE stats SET " + "total = (SELECT count(*) FROM todos)," + "done = (SELECT count(*) FROM todos WHERE done = 1)," + "updated_at = datetime('now') " + "WHERE id = 1;" + } + }, + + .errors = { + {http_bad_request, { + render( + "" + "" + "Error" + "{{> tailwind_script}}" + "" + "" + "
" + "

{{error_message:title}}

" + "← Back" + "
" + "" + "" + ) + }} + }, + + .tasks = { + {"log_created", { + query({ + .db = "todos_db", + .query = + "INSERT INTO activity_log(action, detail) " + "VALUES('created', 'added: {{title}}');" + })}, + .accepts = {"title"} + }, + + {"log_toggled", { + query({ + .db = "todos_db", + .query = + "INSERT INTO activity_log(action, detail) " + "VALUES('toggled', 'toggled todo #{{id}}');" + })}, + .accepts = {"id"} + }, + + {"log_deleted", { + query({ + .db = "todos_db", + .query = + "INSERT INTO activity_log(action, detail) " + "VALUES('deleted', 'removed todo #{{id}}');" + })}, + .accepts = {"id"} + }, + + {"cleanup_stale", { + query( + {.db = "todos_db", + .query = + "UPDATE todos SET done = 1 " + "WHERE done = 0 " + "AND created_at < datetime('now', '-1 hour');" + }, + {.db = "todos_db", + .query = + "INSERT INTO activity_log(action, detail) " + "VALUES('cron', 'auto-completed stale todos');" + } + )}, + .cron = "* * * * *" + } + }, + + .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," + "done INTEGER NOT NULL DEFAULT 0," + "created_at TEXT NOT NULL DEFAULT (datetime('now'))" + ");", + + "CREATE TABLE stats (" + "id INTEGER PRIMARY KEY CHECK (id = 1)," + "total INTEGER NOT NULL DEFAULT 0," + "done INTEGER NOT NULL DEFAULT 0," + "updated_at TEXT NOT NULL DEFAULT (datetime('now'))" + ");", + + "CREATE TABLE activity_log (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "action TEXT NOT NULL," + "detail TEXT," + "ran_at TEXT NOT NULL DEFAULT (datetime('now'))" + ");" + }, + .seeds = { + "INSERT INTO todos(title) VALUES" + "('Learn the MACH tasks API')," + "('Build something cool')," + "('Ship it');", + "INSERT INTO stats(total, done, updated_at) VALUES" + "(3, 0, datetime('now'));" + } + }}, + + .modules = {sqlite, tailwind} + }; +} diff --git a/09-database-multi-tenancy.svg b/09-database-multi-tenancy.svg new file mode 100644 index 0000000..b3ec758 --- /dev/null +++ b/09-database-multi-tenancy.svg @@ -0,0 +1,89 @@ + + + + + + + + + + + Database Multi-Tenancy + + + + .databases config + .connect = + "file:{{user_id}}_todo.db?mode=rwc" + + + + + + + + RUNTIME RESOLUTION + user_id from + pipeline context + + + + + Request: user_id = alice + + + + Request: user_id = bob + + + + Request: user_id = carol + + + + + + + + + + + + + + file: + alice + _todo.db + + + + file: + bob + _todo.db + + + + file: + carol + _todo.db + + + + + + + + + + + + + + + + + + + + One config, per-user databases — Mustache interpolation in .connect at runtime + diff --git a/10-boot-time-compilation.svg b/10-boot-time-compilation.svg new file mode 100644 index 0000000..c2a97c9 --- /dev/null +++ b/10-boot-time-compilation.svg @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + Boot-Time Compilation + + + + + config mach() + .includes + .databases + .resources + .events / .errors + + + + + + + + + Precompile + Compile pipelines + Compile templates + Prepare SQL statements + Build route table + + + + + + + + + Execution Graph + Pre-warmed pipelines + Optimized query plans + Compiled templates + Ready to serve + + + RUNS ONCE AT BOOT + RUNS ONCE AT BOOT + SERVES ALL REQUESTS + + + + Runtime: each request executes a pre-warmed pipeline + + + req → + + pipeline + + + → response + + req → + + pipeline + + + → response + + + Zero per-request compilation — config builds the graph, requests just execute it + diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8c11f71 --- /dev/null +++ b/README.md @@ -0,0 +1,3049 @@ +# 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 dependency wiring 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, introducing one MACH concept at a time. + +* [1. A Page](#1-a-page) +* [2. Show Data](#2-show-data) +* [3. Accept Input](#3-accept-input) +* [4. Handle Errors](#4-handle-errors) +* [5. Nested Data](#5-nested-data) +* [6. Tasks](#6-tasks) +* [7. Modules & Events](#7-modules--events) +* [8. Calling APIs](#8-calling-apis) +* [9. External Assets](#9-external-assets) +* [10. Final State](#10-final-state) + +### 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 = + "" + "

Welcome

" + "My Todos" + "" + ) + } + }, + + {"todos", "/todos", + .get = { + render(.template = + "" + "

My Todos

" + "

Nothing yet.

" + "" + ) + } + } + } + }; +} +``` + +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, and redirects back to GET (POST-redirect-GET). + +```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}}
" ++ "
" ++ "{{csrf:input}}" ++ "" ++ "" ++ "
" + "" + ) +- } ++ }, ++ ++ .post = { ++ validate({"title", ++ .validation = validate_not_empty, ++ .message = "title cannot be empty"}), ++ query({.db = "todos_db", ++ .query = "insert into todos(title) values({{title}});"}), ++ redirect("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`. + +`{{csrf:input}}` emits a hidden input carrying a CSRF token; on POST, MACH automatically verifies that the submitted token matches the one set on the cookie and rejects mismatches with a 403, so every state-changing form needs it. + +### 4. Handle Errors + +Validation failure raises `http_bad_request`. Add a resource-scoped error handler that re-enters the GET pipeline with `reroute("todos")`, and add error markup to the form template. + +```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}}
" + "
" + "{{csrf:input}}" + "" ++ "{{#error:title}}{{error_message:title}}{{/error:title}}" + "" + "
" + "" + ) + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({.db = "todos_db", + .query = "insert into todos(title) values({{title}});"}), + redirect("todos") +- } ++ }, ++ ++ .errors = { ++ {http_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} + }; + } +``` + +`reroute("todos")` re-enters the GET pipeline in-process, which already knows how to fetch todos and render the page. The `input:` and `error:` scopes persist through the reroute, so `{{input:title}}` repopulates the field and `{{#error:title}}` renders the message. See [redirect & reroute](#redirect--reroute). + +### 5. 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 = + "" + "

My Todos

" +- "
    {{#todos}}
  • {{title}}
  • {{/todos}}
" ++ "" + "
" + "{{csrf:input}}" + "" + "{{#error:title}}{{error_message:title}}{{/error:title}}" + "" + "
" + "" + ) + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({.db = "todos_db", + .query = "insert into todos(title) values({{title}});"}), + redirect("todos") + }, + + .errors = { + {http_bad_request, { reroute("todos") }} + } +- } ++ }, ++ ++ {"todo", "/todos/:id", ++ .get = { ++ validate({"id", .validation = validate_integer, ++ .message = "must be an integer"}), ++ query( ++ {.set_key = "todo", .db = "todos_db", ++ .query = "select id, title from todos where id = {{id}};"}, ++ {.set_key = "comments", .db = "todos_db", ++ .query = "select id, todo_id, body from comments where todo_id = {{id}};"} ++ ), ++ join( ++ .target_table_key = "todo", ++ .target_field_key = "id", ++ .nested_table_key = "comments", ++ .nested_field_key = "todo_id", ++ .target_join_field_key = "comments" ++ ), ++ render(.template = ++ "" ++ "{{#todo}}" ++ "

{{title}}

" ++ "

Comments

" ++ "
    {{#comments}}
  • {{body}}
  • {{/comments}}
" ++ "{{/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 in parallel under one `query()` call. `join()` lifts `comments` inside each todo record, so the template enters `{{#todo}}` first and reaches `{{#comments}}` from within. + +### 6. 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 = + "" + "

My Todos

" + "" + "
" + "{{csrf:input}}" + "" + "{{#error:title}}{{error_message:title}}{{/error:title}}" + "" + "
" + "" + ) + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({.db = "todos_db", + .query = "insert into todos(title) values({{title}});"}), ++ task("record_daily_stats"), + redirect("todos") + }, + + .errors = { + {http_bad_request, { reroute("todos") }} + } + }, + + {"todo", "/todos/:id", + .get = { + validate({"id", .validation = validate_integer, + .message = "must be an integer"}), + query( + {.set_key = "todo", .db = "todos_db", + .query = "select id, title from todos where id = {{id}};"}, + {.set_key = "comments", .db = "todos_db", + .query = "select id, todo_id, body from comments where todo_id = {{id}};"} + ), + join( + .target_table_key = "todo", + .target_field_key = "id", + .nested_table_key = "comments", + .nested_field_key = "todo_id", + .target_join_field_key = "comments" + ), + render(.template = + "" + "{{#todo}}" + "

{{title}}

" + "

Comments

" + "
    {{#comments}}
  • {{body}}
  • {{/comments}}
" + "{{/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). + +### 7. Modules & 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 = + "" + "

My Todos

" + "" + "
" + "{{csrf:input}}" + "" + "{{#error:title}}{{error_message:title}}{{/error:title}}" + "" + "
" + "" + ) + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({.db = "todos_db", + .query = "insert into todos(title) values({{title}});"}), + task("record_daily_stats"), + emit("todo_created"), + redirect("todos") + }, + + .errors = { + {http_bad_request, { reroute("todos") }} + } + }, + + {"todo", "/todos/:id", + .get = { + validate({"id", .validation = validate_integer, + .message = "must be an integer"}), + query( + {.set_key = "todo", .db = "todos_db", + .query = "select id, title from todos where id = {{id}};"}, + {.set_key = "comments", .db = "todos_db", + .query = "select id, todo_id, body from comments where todo_id = {{id}};"} + ), + join( + .target_table_key = "todo", + .target_field_key = "id", + .nested_table_key = "comments", + .nested_field_key = "todo_id", + .target_join_field_key = "comments" + ), + render(.template = + "" + "{{#todo}}" + "

{{title}}

" + "

Comments

" + "
    {{#comments}}
  • {{body}}
  • {{/comments}}
" + "{{/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. `todos` owns the todos domain (resources, database, publisher contract, scheduled task); `activity` owns activity (its resource, database, subscriber). Both can also declare their own context, error and repair handlers, and nested modules. Neither references the other. They only agree on the event name and payload. + +When the POST pipeline in `todos` 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, so 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; the `todos` module doesn't change. + +### 8. 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 in parallel. + +**`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 = + "" + "

Welcome

" ++ "{{#weather}}" ++ "

{{city}}: {{precision:temp_c:0}}°C, {{conditions}}

" ++ "{{/weather}}" ++ "{{#quote}}" ++ "
{{content}}, {{author}}
" ++ "{{/quote}}" + "My Todos · " + "Activity" + "" + ) + } + } + }, + + .modules = {todos, activity, sqlite} + }; + } +``` + +Both requests run in parallel under one `fetch()` call, then control passes to `render()` once both responses are in context. The Quotable API returns `{"author": "...", "content": "..."}`, which MACH parses into a single-row table under `quote`; the weather response lands under `weather` the same way. The template enters each section with `{{#quote}}` and `{{#weather}}` to read its fields, the same way it does for query results. + +`fetch()` also supports POST/PUT/PATCH/DELETE, custom headers, JSON or text request bodies, and URLs with `{{interpolation}}`. See [fetch](#fetch). + +### 9. 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()`, `query()`, and `find()`. Each artifact lives in a file named for what it is, edited with native tooling (Mustache-aware HTML editors, SQL formatters), and syntax-highlighted on its own terms. Apply throughout: the root, the todos module, and the activity module. + +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 +├── 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/home.mustache.html`** + +```html + +

Welcome

+ {{#weather}} +

{{city}}: {{precision:temp_c:0}}°C, {{conditions}}

+ {{/weather}} + {{#quote}} +
{{content}}, {{author}}
+ {{/quote}} + My Todos · Activity + +``` + +**`main.c`**: references the home template by name; the `fetch()` step from the previous section is unchanged. + +```c +#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("home") + } + } + }, + + .context = { + {"home", (asset){ + #embed "static/home.mustache.html" + }} + }, + + .modules = {todos, activity, sqlite} + }; +} +``` + +#### Todos module + +**`todos/todos_list.mustache.html`** + +```html + +

My Todos

+ +
+ {{csrf:input}} + + {{#error:title}}{{error_message:title}}{{/error:title}} + +
+ +``` + +**`todos/get_todos.sql`**: and similarly for each other SQL file. + +```sql +select id, title from todos; +``` + +**`todos/create_todo.sql`** + +```sql +insert into todos(title) values({{title}}); +``` + +SQL `{{interpolation}}` works the same as inline: bound as prepared parameters, never spliced. Migration files are plain `CREATE TABLE` statements, one per file. `todos/todo_detail.mustache.html` holds the detail-page template from step 5. + +**`todos/todos.c`**: pipelines now reference assets by name; `.context` lists every asset the module uses. + +```c +#include +#include + +config todos(){ + return (config){ + .name = "todos", + + .publishes = { + {"todo_created", .with = {"title"}} + }, + + .resources = { + {"todos", "/todos", + .get = { + query({"get_todos", .set_key = "todos", .db = "todos_db"}), + render("todos_list") + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({"create_todo", .db = "todos_db"}), + task("record_daily_stats"), + emit("todo_created"), + redirect("todos") + }, + + .errors = { + {http_bad_request, { reroute("todos") }} + } + }, + + {"todo", "/todos/:id", + .get = { + validate({"id", .validation = validate_integer, + .message = "must be an integer"}), + query( + {"get_todo", .set_key = "todo", .db = "todos_db"}, + {"get_comments", .set_key = "comments", .db = "todos_db"} + ), + join( + .target_table_key = "todo", + .target_field_key = "id", + .nested_table_key = "comments", + .nested_field_key = "todo_id", + .target_join_field_key = "comments" + ), + render("todo_detail") + } + } + }, + + .tasks = { + {"record_daily_stats", { + query({"record_daily_stats", .db = "todos_db"}) + }, .cron = "0 0 * * *"} + }, + + .context = { + {"todos_list", (asset){ + #embed "todos_list.mustache.html" + }}, + {"todo_detail", (asset){ + #embed "todo_detail.mustache.html" + }}, + {"get_todos", (asset){ + #embed "get_todos.sql" + }}, + {"create_todo", (asset){ + #embed "create_todo.sql" + }}, + {"get_todo", (asset){ + #embed "get_todo.sql" + }}, + {"get_comments", (asset){ + #embed "get_comments.sql" + }}, + {"record_daily_stats", (asset){ + #embed "record_daily_stats.sql" + }} + }, + + .databases = {{ + .engine = sqlite_db, + .name = "todos_db", + .connect = "file:todos.db?mode=rwc", + .migrations = { + (asset){ + #embed "create_todos_table.sql" + }, + (asset){ + #embed "create_comments_table.sql" + }, + (asset){ + #embed "create_daily_stats_table.sql" + } + }, + .seeds = { + (asset){ + #embed "seed_todos.sql" + } + } + }}, + + .modules = {sqlite} + }; +} +``` + +#### Activity module + +**`activity/activity.mustache.html`** + +```html + +

Activity

+
    {{#activities}} +
  • {{created_at}}: {{kind}}, {{ref}}
  • + {{/activities}}
+ +``` + +**`activity/insert_activity.sql`**: the event handler's insert, now a named asset. + +```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} + }; +} +``` + +The pipeline shape is unchanged; only where the strings live has moved. Each `render()`, `query()`, and `find()` step takes an asset name as its positional argument; MACH resolves it against `.context` top-down from the root at boot time (root wins on name conflicts). `.migrations` and `.seeds` accept assets directly, which is why entries now read `(asset){ #embed "..." }` instead of quoted SQL. Templates are still Mustache; SQL still supports `{{interpolation}}` bound as prepared parameters. + +#### Sharing layout with partials + +Each page template above repeats the same `...` chrome and its own variant of a top nav. Mustache layout inheritance pulls the shared structure into one template that the others extend. + +**`static/layout.mustache.html`**: the shared chrome, with a `{{$content}}` block that child templates override. + +```html + + +
{{$content}}{{/content}}
+ +``` + +Register it once at the root so every module can use it. + +```c +.context = { + {"home", (asset){ + #embed "static/home.mustache.html" + }}, + {"layout", (asset){ + #embed "static/layout.mustache.html" + }} +} +``` + +Each page now extends `layout` and supplies its own `{{$content}}`. + +**`static/home.mustache.html`** + +```html +{{Welcome + {{#weather}} +

{{city}}: {{precision:temp_c:0}}°C, {{conditions}}

+ {{/weather}} + {{#quote}} +
{{content}}, {{author}}
+ {{/quote}} + {{/content}} +{{/layout}} +``` + +**`todos/todos_list.mustache.html`** + +```html +{{My Todos + +
+ {{csrf:input}} + + {{#error:title}}{{error_message:title}}{{/error:title}} + +
+ {{/content}} +{{/layout}} +``` + +`{{name}}` instead. 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 with no further processing. Use `{{>name}}` for templates and `{{&name}}` for already-rendered HTML such as a sanitized blog body. + +### 10. Final State + +After all nine concept steps, the project is a small but complete app: a home page with a quote and weather pulled concurrently, a todos module with list and detail pages plus a daily stats cron, and an activity module that subscribes to todo events. Three `.c` files, two databases, one shared layout. + +``` +. +├── todos/ # todos module +│ ├── todos.c # config todos() { resources, db, events, tasks } +│ ├── todos_list.mustache.html # extends layout, lists todos + form +│ ├── todo_detail.mustache.html # one todo with comments +│ ├── create_todos_table.sql # migrations +│ ├── create_comments_table.sql +│ ├── create_daily_stats_table.sql +│ ├── seed_todos.sql # seeds +│ ├── get_todos.sql # queries +│ ├── get_todo.sql +│ ├── get_comments.sql +│ ├── create_todo.sql +│ └── record_daily_stats.sql +├── activity/ # activity module +│ ├── activity.c # config activity() { resource, db, events } +│ ├── activity.mustache.html +│ ├── create_activities_table.sql +│ ├── get_activities.sql +│ └── insert_activity.sql +├── static/ # root-level templates +│ ├── layout.mustache.html # shared chrome with {{$content}} block +│ └── home.mustache.html # home page extending layout +├── public/ # served as-is +│ └── favicon.png +└── main.c # registers modules, declares root resources and context +``` + +**`main.c`**: registers both modules, defines the home resource, embeds the root templates. +```c +#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("home") + } + } + }, + .context = { + {"home", (asset){ + #embed "static/home.mustache.html" + }}, + {"layout", (asset){ + #embed "static/layout.mustache.html" + }} + }, + .modules = {todos, activity, sqlite} + }; +} +``` + +**`todos/todos.c`**: full CRUD on todos, comments via join, validation, error reroute, daily stats cron, publishes `todo_created`. +```c +#include +#include + +config todos(){ + return (config){ + .name = "todos", + + .publishes = { + {"todo_created", .with = {"title"}} + }, + + .resources = { + {"todos", "/todos", + .get = { + query({"get_todos", .set_key = "todos", .db = "todos_db"}), + render("todos_list") + }, + + .post = { + validate({"title", + .validation = validate_not_empty, + .message = "title cannot be empty"}), + query({"create_todo", .db = "todos_db"}), + task("record_daily_stats"), + emit("todo_created"), + redirect("todos") + }, + + .errors = { + {http_bad_request, { reroute("todos") }} + } + }, + + {"todo", "/todos/:id", + .get = { + validate({"id", .validation = validate_integer, + .message = "must be an integer"}), + query( + {"get_todo", .set_key = "todo", .db = "todos_db"}, + {"get_comments", .set_key = "comments", .db = "todos_db"} + ), + join( + .target_table_key = "todo", + .target_field_key = "id", + .nested_table_key = "comments", + .nested_field_key = "todo_id", + .target_join_field_key = "comments" + ), + render("todo_detail") + } + } + }, + + .tasks = { + {"record_daily_stats", { + query({"record_daily_stats", .db = "todos_db"}) + }, .cron = "0 0 * * *"} + }, + + .context = { + {"todos_list", (asset){ + #embed "todos_list.mustache.html" + }}, + {"todo_detail", (asset){ + #embed "todo_detail.mustache.html" + }}, + {"get_todos", (asset){ + #embed "get_todos.sql" + }}, + {"create_todo", (asset){ + #embed "create_todo.sql" + }}, + {"get_todo", (asset){ + #embed "get_todo.sql" + }}, + {"get_comments", (asset){ + #embed "get_comments.sql" + }}, + {"record_daily_stats", (asset){ + #embed "record_daily_stats.sql" + }} + }, + + .databases = {{ + .engine = sqlite_db, + .name = "todos_db", + .connect = "file:todos.db?mode=rwc", + .migrations = { + (asset){ + #embed "create_todos_table.sql" + }, + (asset){ + #embed "create_comments_table.sql" + }, + (asset){ + #embed "create_daily_stats_table.sql" + } + }, + .seeds = { + (asset){ + #embed "seed_todos.sql" + } + } + }}, + + .modules = {sqlite} + }; +} +``` + +**`activity/activity.c`**: subscribes to `todo_created`, owns its own database. +```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} + }; +} +``` + +That covers the basic shape of a MACH app: resources route requests, pipelines transform them, error handlers recover, joins compose nested views from separate queries, tasks handle background work, events decouple modules, external assets let templates and SQL live alongside the code that uses them, and `fetch()` brings in external HTTP data. See [Modules & Composition](#modules--composition) for more on module boundaries. + +--- + +## Reference + +Each subsection describes one piece of the framework and lists every option it accepts with a minimal snippet. + +* [Context](#context) +* [Databases](#databases) +* [Resource Pipelines](#resource-pipelines) +* [Template Helpers](#template-helpers) +* [Pipeline Steps](#pipeline-steps) +* [Imperative API](#imperative-api) +* [Conditionals](#conditionals) +* [Error and Repair Pipelines](#error-and-repair-pipelines) +* [Event Pipelines](#event-pipelines) +* [Task Pipelines](#task-pipelines) +* [Modules & Composition](#modules--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()`, `query()`, and `find()`. 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). `validate()` bridges `input:` 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" + }} +} +``` + +![Context Scoping](./07-context-scoping.svg) + +### 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()` and `find()`. +```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` + +![Database Multi-Tenancy](./09-database-multi-tenancy.svg) + +### 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()` take a `name[:arg1:arg2...]` identifier; positional args fill the `:params` of the URL pattern in order. Path specificity is automatic: exact matches (`/todos/active`) beat parameterized matches (`/todos/:id`) regardless of definition order. + +> **`{{url:name}}` with URL params.** Args after the name are positional, colon-separated, literals or context keys: +> - ✅ `{{url:todo:5}}` resolves to `/todos/5` +> - ✅ `{{url:todo:id}}` reads `id` from current scope (useful inside `{{#todos}}...{{/todos}}` where each iteration has its own `id`) +> - ✅ `{{url:org_todo:acme:5}}` fills multiple `:params` in URL-pattern order (e.g. `/orgs/:org/todos/:id`) + +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", { + validate({"id", .validation = "^\\d+$", .message = "must be a number"}) +}, .get = { ... }, .delete = { ... }} +``` + +**`.mime`**: default response content type for the resource. +```c +{"feed", "/feed.json", .mime = mime_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 = { validate({"title", .validation = validate_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 = {{http_bad_request, { render("form") }}} +} +``` + +Combined: +```c +{"todo", "/todos/:id", { + validate({"id", .validation = "^\\d+$", .message = "must be a number"}) +}, + .mime = mime_html, + .get = { find({"get_todo", .set_key = "todo", .db = "todos_db"}), + render("todo") }, + .patch = { validate({"title", .validation = validate_not_empty, .message = "required"}), + query({.db = "todos_db", + .query = "update todos set title = {{title}} where id = {{id}};"}), + redirect("todo:{{id}}") }, + .delete = { query({.db = "todos_db", + .query = "delete from todos where id = {{id}};"}), + redirect("todos") }, + .sse = {"todo/{{id}}", sse(.event = "ready") }, + .errors = {{http_not_found, { render("404") }}} +} +``` + +**MIME types (for `.mime`):** `mime_html`, `mime_txt`, `mime_sse`, `mime_json`, `mime_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**: `{{All" // /todos + "Item 5" // /todos/5 + "From context" // /todos/{{id}} +) +``` + +**`{{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 `
`. Same cookie-setting behavior as `{{csrf:token}}`. +```c +render(.template = "{{csrf:input}}
") +``` + +Combined: +```c +render(.template = + "" + "
" + "{{#post}}" + "

{{title}}

" + "

Rating: {{precision:score:1}}/5

" + "
{{&body_html}}
" + "{{/post}}" + "
" + "{{csrf:input}}" + "" + "{{#error:body}}{{error_message:body}}{{/error:body}}" + "" + "
" + "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. + +* [validate](#validate) +* [find & query](#find--query) +* [join](#join) +* [fetch](#fetch) +* [exec](#exec) +* [emit](#emit) +* [task](#task) +* [sse](#sse) +* [render](#render) +* [headers & cookies](#headers--cookies) +* [redirect & reroute](#redirect--reroute) +* [nest](#nest) + +![Request Pipeline Flow](./02-request-pipeline-flow.svg) + +#### validate + +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 validate_zipcode "^\\d{5}$"`. + +**`.param_key` *(pos)***: name of the parameter to validate. +```c +validate({"title", .validation = "^\\S+$", .message = "required"}) +``` + +**`.validation`**: regex pattern, or a built-in validator macro. +```c +validate({"email", .validation = validate_email, .message = "bad email"}) +``` + +**`.message`**: human-readable error shown via `{{error_message:name}}`. +```c +validate({"age", .validation = "^\\d+$", .message = "must be a number"}) +``` + +**`.optional`**: skip validation when the parameter is absent. +```c +validate({"filter", .optional = true, .validation = "^(active|done)$"}) +``` + +**`.fallback`**: default value injected when the parameter is absent. +```c +validate({"page", .fallback = "1", .validation = "^\\d+$"}) +``` + +Combined: +```c +validate( + {"email", .validation = validate_email, .message = "must be a valid email"}, + {"title", .validation = validate_not_empty, .message = "cannot be empty"}, + {"page", .fallback = "1", + .validation = "^\\d+$", .message = "must be a number"}, + {"filter", .optional = true, + .validation = "^(active|done)$", .message = "must be 'active' or 'done'"} +) +``` + +**Built-in validators:** +- Strings: `validate_not_empty`, `validate_alpha`, `validate_alphanumeric`, `validate_slug`, `validate_no_html` +- Numbers: `validate_integer`, `validate_positive`, `validate_float`, `validate_percentage` +- Identity: `validate_email`, `validate_uuid`, `validate_username` +- Dates & times: `validate_date`, `validate_time`, `validate_datetime` +- Web: `validate_url`, `validate_ipv4`, `validate_hex_color` +- Codes: `validate_zipcode_us`, `validate_phone_e164`, `validate_cron` +- Security: `validate_no_sqli`, `validate_token`, `validate_base64` +- Boolean: `validate_boolean`, `validate_yes_no`, `validate_on_off` + +#### find & query + +Both run database queries. `.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. + +The only difference between the two: `find()` raises `404 Not Found` on zero rows; `query()` does not. + +> **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 + +> **Concurrency = multiple items in one step, not multiple steps.** `query({...}, {...})` runs both queries in parallel. Two back-to-back `query({...})` steps run serially. + +**`.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;"}) +``` + +**`.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. + +**`.target_table_key`**: outer table whose records receive nested children. +```c +.target_table_key = "projects" +``` + +**`.target_field_key`**: field on the outer table to match against. +```c +.target_field_key = "id" +``` + +**`.nested_table_key`**: inner table whose records get nested. +```c +.nested_table_key = "todos" +``` + +**`.nested_field_key`**: field on the inner table that points at the outer. +```c +.nested_field_key = "project_id" +``` + +**`.target_join_field_key`**: new field on outer records holding the matched inner records. +```c +.target_join_field_key = "todos" +``` + +Combined: +```c +join( + .target_table_key = "projects", + .target_field_key = "id", + .nested_table_key = "todos", + .nested_field_key = "project_id", + .target_join_field_key = "todos" +) +``` + +**Full context example.** A common pattern is 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 = { + validate({"id", .validation = validate_integer, .message = "must be an 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( + .target_table_key = "blog", + .target_field_key = "id", + .nested_table_key = "comments", + .nested_field_key = "blog_id", + .target_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 in parallel and join the results downstream. + +> **Concurrency = multiple items in one step, not multiple steps.** `fetch({...}, {...})` runs both requests in parallel. Two back-to-back `fetch({...})` steps run serially. + +**`.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 `http_get`. +```c +fetch({"https://api.dev/charge", .set_key = "r", .method = http_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 = http_post, .json = "order"}) +``` + +**`.text`**: context key sent as the plain-text request body. +```c +fetch({"https://api.dev/log", .set_key = "r", + .method = http_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 = http_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`):** `http_get`, `http_post`, `http_put`, `http_patch`, `http_delete`, `http_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 = "

{{site_name}}

") // {{site_name}} from .context +``` + +**`.status`**: HTTP response status (defaults to `http_ok`). +```c +render("not_found", .status = http_not_found) +``` + +**`.mime`**: override the response content type. +```c +render("plain", .mime = mime_txt) +``` + +**`.engine`**: template engine. Accepts `mustache` (default) or `mdm` for Markdown-with-Mustache. Additional engined can be added with modules. +```c +render(.engine = mdm, .template = "# Welcome, {{user_name}}") +``` + +**`.json_table_key`**: context table to serialize as the JSON response. Sets `application/json`; nested tables produce nested JSON. +```c +render(.json_table_key = "todos") +``` + +**HTTP statuses (for `.status`):** `http_ok` (200), `http_created` (201), `http_redirect` (302), `http_bad_request` (400), `http_not_authorized` (401), `http_not_found` (404), `http_error` (500) + +**MIME types (for `.mime`):** `mime_html`, `mime_txt`, `mime_sse`, `mime_json`, `mime_js` + +#### headers & cookies + +Set HTTP response headers and cookies declaratively. Both accept an array of name/value pairs; values support `{{interpolation}}`. + +**Pairs *(pos)***: array of `{name, value}` entries. +```c +headers({{"X-Request-Id", "{{request_id}}"}}) +``` +```c +cookies({{"session", "{{session_id}}"}}) +``` + +Combined: +```c +headers({ + {"X-Request-Id", "{{request_id}}"}, + {"Cache-Control", "no-store"} +}), +cookies({ + {"session", "{{session_id}}"}, + {"theme", "{{theme}}"} +}) +``` + +#### redirect & reroute + +`redirect()` returns a 302 to the client, causing the browser to navigate. `reroute()` re-enters the router server-side, executing another resource's pipeline within the same request. Both take a **resource identifier** in the same `name[:arg1:arg2...]` format as `{{url:name}}`: colon-separated positional args that fill the target's `:params`. Args can be literals or context keys, and support `{{interpolation}}`. + +**Resource identifier *(pos)***: target resource name, plus positional args for any `:params`. +```c +redirect("todos") // 302 to /todos (bare resource, no args) +redirect("todo:5") // 302 to /todos/5 (literal id) +redirect("todo:{{id}}") // 302 to /todos/5 (id from context) +redirect("org_todo:acme:5") // 302 to /orgs/acme/todos/5 (multi-arg) +reroute("todo:{{id}}") // run that pipeline in-process +``` + +#### nest + +Groups multiple steps into a single composite step. Useful when applying one `.if_context`/`.unless_context` to several steps, to avoid repeating the condition on each. + +**`.steps` *(pos)***: array of steps that run as a unit. +```c +nest({query({...}), emit("urgent_todo"), render("urgent")}) +``` + +**`.if_context` / `.unless_context`**: condition applied to the whole group. +```c +nest({query({...}), emit("urgent_todo"), render("urgent")}, + .if_context = "is_urgent") +``` + +### Imperative API + +Functions called from `exec()` blocks and `.call` functions to read and write context, allocate memory, raise errors, and manipulate tables and records. + +* [context](#context-1) +* [memory](#memory) +* [errors](#errors-1) +* [tables](#tables) +* [records](#records) + +#### context + +Read, write, and test context keys, and resolve `{{interpolation}}` against the current scope. + +**`get(name)`**: returns the value stored under `name`, or `nullptr` if absent. The returned pointer is whatever was stored: a `string` for scalars, a `table` for query and fetch results. +```c +auto todos = get("todos"); +``` + +**`set(name, value)`**: writes `value` to `name`, exposing it to downstream steps and to templates. +```c +set("is_urgent", "1"); +``` + +**`has(name)`**: returns true when `name` exists in the current scope. +```c +if (has("user_id")) { ... } +``` + +**`format(fmt)`**: returns `fmt` with `{{name}}` interpolations resolved against the current context. Same scopes and helpers as templates. +```c +string greeting = format("Hello, {{user_name}}"); +``` + +Combined: +```c +exec(^(){ + auto rows = get("todos"); + if (table_count(rows) > 5) { + set("is_urgent", "1"); + set("banner", format("{{user_name}} has more than 5 open todos")); + } +}) +``` + +#### memory + +Pipeline-arena allocation and deferred cleanup of foreign pointers. Both clear when the request completes. + +**`allocate(bytes)`**: returns a buffer from the pipeline arena. Reclaimed automatically on request completion. +```c +char *buf = allocate(256); +``` + +**`defer_free(ptr)`**: schedules `free()` for a pointer returned by an external library. Runs when the arena is released. +```c +char *out = third_party_alloc(256); +defer_free(out); +``` + +Combined: +```c +exec(^(){ + char *url = allocate(512); + build_signed_url(url, 512, get("path")); + set("signed_url", url); + + char *raw = third_party_render_md(get("markdown")); + defer_free(raw); + set("html", raw); +}) +``` + +#### errors + +Raise field-scoped errors from inside `exec()` to trigger error/repair pipelines. The keys land in the `error:name` scope, visible to templates as `{{error:name}}`, `{{error_code:name}}`, and `{{error_message:name}}`. + +**`error_set(name, err)`**: associates an error with `name` and triggers the nearest [error or repair pipeline](#error-and-repair-pipelines). +```c +error_set("token", (error){ http_bad_request, "token has expired" }); +``` + +**`error_get(name)`**: returns the `error` previously set on `name`. +```c +error e = error_get("token"); +``` + +**`error_has(name)`**: returns true when `name` has an error. +```c +if (error_has("token")) { ... } +``` + +Combined: +```c +exec(^(){ + string token = get("token"); + if (!token || strlen(token) < 16) { + error_set("token", (error){ + http_bad_request, + "token must be at least 16 characters" + }); + } +}) +``` + +#### tables + +Tables are ordered collections of records, the shape `query()` produces and `fetch()` parses JSON into. Use these to build derived results. + +**`table_new()`**: returns an empty table in the pipeline arena. +```c +table t = table_new(); +``` + +**`table_count(t)`**: number of records in `t`. +```c +int n = table_count(get("todos")); +``` + +**`table_get(t, i)`**: record at index `i`, or `nullptr` if out of range. +```c +record first = table_get(get("todos"), 0); +``` + +**`table_add(t, r)`**: appends `r` to `t`. +```c +table_add(t, record_new()); +``` + +**`table_remove(t, r)`**: removes record `r` from `t`. +```c +table_remove(t, r); +``` + +**`table_remove_at(t, i)`**: removes the record at index `i`. +```c +table_remove_at(t, 0); +``` + +Combined: +```c +exec(^(){ + table source = get("raw_users"); + table active = table_new(); + for (int i = 0; i < table_count(source); i++) { + record u = table_get(source, i); + string status = record_get(u, "status"); + if (status && strcmp(status, "active") == 0) { + table_add(active, u); + } + } + set("active_users", active); +}) +``` + +#### records + +Records are name-value bags, the shape of one row from `query()` or one object from `fetch()`. All values are strings, in keeping with [Everything is a String](#everything-is-a-string). + +**`record_new()`**: returns an empty record in the pipeline arena. +```c +record r = record_new(); +``` + +**`record_get(r, name)`**: string value of `name`, or `nullptr` if absent. +```c +string title = record_get(r, "title"); +``` + +**`record_set(r, name, value)`**: writes `value` to `name` on `r`. +```c +record_set(r, "title", "New title"); +``` + +**`record_remove(r, name)`**: removes `name` from `r`. +```c +record_remove(r, "draft"); +``` + +Combined: +```c +exec(^(){ + table todos = get("todos"); + for (int i = 0; i < table_count(todos); i++) { + record t = table_get(todos, i); + string title = record_get(t, "title"); + if (title && strlen(title) > 40) { + record_set(t, "is_long", "1"); + } + } +}) +``` + +### Conditionals + +Every step accepts `.if_context` and `.unless_context`, which name a context variable. They work for any context value: validated inputs, query results, framework flags such as `is_htmx`, or flags set from `exec()`. + +**`.if_context`**: context key. Step runs only when the value is present. +```c +render("fragment", .if_context = "is_htmx") +``` + +**`.unless_context`**: context key. Step runs only when the value is absent. +```c +render("full_page", .unless_context = "is_htmx") +``` + +For multi-state branching, set context flags from `exec()`, then key downstream steps off them: + +```c +exec(.call = classify_todo), +render("urgent_confirmation", .if_context = "is_urgent"), +render("standard_confirmation", .unless_context = "is_urgent") +``` + +### Error and Repair Pipelines + +When a pipeline step fails, execution halts and MACH searches for a handler bottom-up: resource, then module, then root. Errors are terminal: the handler sends a response and ends the request. Repairs are resumable: they fix the context and resume the original pipeline at the step after the failure. If no matching repair is found, resolution falls through to errors. Unhandled errors fall through to MACH's internal handler, which renders the error message as `text/plain` with the error code as the HTTP status, and surfaces in the TUI console and telemetry. + +The `error` scope is shared across `validate()` failures and `error_set()` calls: `{{error:name}}`, `{{error_code:name}}`, `{{error_message:name}}`. The raw input value remains available in `input:name` for re-rendering forms. + +**`.errors`**: terminal handlers keyed by error code. +```c +.errors = { + {http_not_found, { render("404") }}, + {http_bad_request, { render("form") }} +} +``` + +**`.repairs`**: resumable handlers keyed by error code. +```c +.repairs = { + {http_not_authorized, { exec(.call = refresh_session_token) }} +} +``` + +Combined: +```c +.errors = { + {http_not_found, { render("404") }}, + {http_bad_request, { render("form") }}, + {http_error, { render("500") }} +}, +.repairs = { + {http_not_authorized, { exec(.call = refresh_session_token) }} +} +``` + +**Built-in error codes:** `http_ok` (200), `http_created` (201), `http_redirect` (302), `http_bad_request` (400), `http_not_authorized` (401), `http_not_found` (404), `http_error` (500). Any integer works; the `http_*` constants are convenience names. Define your own for domain-specific errors, e.g. `#define err_quota_exceeded 723`. + +![Error Resolution](./04-error-resolution.svg) + +### Event Pipelines + +Internal pub/sub for cross-module communication. The publisher does not know who listens; the subscriber does not know who emits. Adding a subscriber means adding a new module with an `.events` entry, with no changes to the publisher. + +Events are durable by default. When `.publishes` is defined anywhere in the app, MACH creates a `mach_events` database to track delivery. If the process crashes, undelivered events are replayed on the next boot. + +**`.publishes`**: outbound event contracts. `.event` is the name; `.with` lists context keys to pass along. +```c +.publishes = { + {"todo_created", .with = {"user_id", "title"}} +} +``` + +**`.events`**: subscriber pipelines keyed by event name. +```c +.events = { + {"todo_created", { + query({"insert_activity", .db = "activity_db"}) + }} +} +``` + +**`.errors` / `.repairs`** *(per subscriber)*: each `.events` entry can declare its own handlers, resolved with the same bottom-up search as resource pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +.events = { + {"todo_created", { + query({"insert_activity", .db = "activity_db"}) + }, .errors = {{http_error, { exec(.call = log_subscriber_failure) }}}} +} +``` + +Combined: +```c +// todos/todos.c: publisher +config todos(){ + return (config){ + .name = "todos", + .publishes = { + {"todo_created", .with = {"user_id", "title"}}, + {"todo_deleted", .with = {"user_id", "todo_id"}} + }, + .resources = { + {"todos", "/todos", + .post = { + validate({"title", .validation = validate_not_empty}), + query({"insert_todo", .db = "todos_db"}), + emit("todo_created"), + redirect("todos") + } + } + } + }; +} + +// activity/activity.c: subscriber +config activity(){ + return (config){ + .name = "activity", + .events = { + {"todo_created", { + query({.db = "activity_db", + .query = "insert into activities(kind, user_id, ref) " + "values('created', {{user_id}}, {{title}});"}) + }}, + {"todo_deleted", { + query({.db = "activity_db", + .query = "insert into activities(kind, user_id, ref) " + "values('deleted', {{user_id}}, {{todo_id}});"}) + }} + } + }; +} +``` + +![Event Pub/Sub](./03-event-pub-sub.svg) + +### Task Pipelines + +Tasks are named pipelines that run asynchronously on task reactors. Fire-and-forget: the calling pipeline continues immediately. Defined at the module or root level. Triggered on demand with `task("name")` or on a schedule via `.cron`. Tasks can enqueue more tasks via `task()`. + +Tasks are durable: when `.tasks` is defined, MACH creates a `mach_tasks` database and checkpoints the context after each step. A crash mid-task resumes at the step where it left off on the next boot. + +**`.name` *(pos)***: task identifier, called via `task("name")`. +```c +.tasks = { + {"recount_todos", { query({.db = "db", .query = "update users set ..."}) }} +} +``` + +**`.accepts`**: context keys to pull from the caller into the task. +```c +{"recount_todos", { + query({.db = "db", .query = "update users set todo_count = ... where id = {{user_id}};"}) +}, .accepts = {"user_id"}} +``` + +**`.cron`**: standard cron schedule for recurring tasks (no caller required). +```c +{"daily_digest", { + query({.db = "db", .query = "insert into digest_reports ..."}) +}, .cron = "0 8 * * *"} +``` + +**Steps *(pos)***: the task's pipeline body, the second positional brace block, before any designated fields. +```c +{"name", { query({...}), emit("done"), task("followup") }, .accepts = {...}} +``` + +**`.errors` / `.repairs`** *(per task)*: each task can declare its own handlers, resolved with the same bottom-up search as resource pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +{"send_invoice", { + fetch({"https://api.billing.dev/invoices/{{invoice_id}}", .set_key = "inv"}) +}, .repairs = {{http_not_authorized, { exec(.call = refresh_billing_token) }}}} +``` + +Combined: +```c +.tasks = { + // on-demand: enqueued via task("recount_todos") + {"recount_todos", { + query({.db = "todos_db", + .query = "update users set todo_count = " + "(select count(*) from todos where user_id = users.id) " + "where id = {{user_id}};"}) + }, .accepts = {"user_id"}}, + + // recurring: runs on schedule, no caller + {"daily_digest", { + query({.db = "todos_db", + .query = "insert into digest_reports(generated_at) values(now());"}), + emit("digest_ready") + }, .cron = "0 8 * * *"} +} +``` + +### Modules & Composition + +Every MACH app and module returns a `config` struct. The root `main.c` must define a function named `mach()`; modules define their own functions with any name and register them in `.modules` by bare function reference. A module owns its own resources, databases, migrations, templates, and event contracts. + +When the root and a module both define something with the same name, resolution depends on the kind. Context variables and databases resolve **top-down** from the root, so the **root wins**. Error and repair handlers resolve **bottom-up** from the resource (resource → module → root), so the **innermost handler wins**. Modules don't call each other directly; they communicate through pub/sub events. + +**`.name`**: module identifier. +```c +config todos(){ return (config){ .name = "todos", /* resources, databases, ... */ }; } +``` + +**`.modules`**: other modules to compose into this one (root or nested). +```c +.modules = {todos, activity, sqlite, session_auth} +``` + +**Complete module file.** A module returns a `config` with the same shape as the root app (`.resources`, `.databases`, `.events`, etc.), plus a `.name` for identity. Resource fields like `.url`, `.mime`, `.get` are not top-level config fields; they belong inside entries of `.resources`. A `blogs/blogs.c`: + +```c +#include +#include + +config blogs(){ + return (config){ + .name = "blogs", + .resources = { + {"blog", "/blogs/:id", + .get = { /* validate → query → join → render; see `join` worked example */ } + } + }, + .databases = {{ + .engine = sqlite_db, + .name = "blog_db", + .connect = "file:blogs.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" + ");" + } + }} + }; +} +``` + +Bring the module into scope by `#include`ing its `.c` file from `main.c`, then register it with `.modules = {blogs, sqlite}`. The module's resources and databases are merged into the app tree at registration. +```c +// main.c +#include +#include "blogs/blogs.c" + +config mach(){ return (config){ .modules = {blogs, sqlite} }; } +``` + +A typical project layout: +``` +├── todos/ # todos module +│ ├── todos.c # config todos() { ... } +│ ├── todos.mustache.html +│ ├── create_todos_table.sql +│ └── get_todos.sql +├── activity/ # activity module +│ └── activity.c +├── static/ # root-level templates (not a module) +│ ├── layout.mustache.html +│ └── home.mustache.html +├── public/ # static files, served directly +│ └── favicon.png +└── main.c # registers modules +``` + +**Bundled modules (add the initializer to `.modules` to use):** `sqlite`, `postgres`, `mysql`, `redis`, `duckdb`, `htmx`, `datastar`, `tailwind`, `session_auth`. See [Module Reference](#module-reference) for what each one provides. + +![App Composition Tree](./05-app-composition-tree.svg) +![Middleware Scoping](./06-middleware-scoping.svg) + +### Module Reference + +* [htmx](#htmx) +* [datastar](#datastar) +* [tailwind](#tailwind) +* [session_auth](#session_auth) +* [Database engines](#database-engines-sqlite-postgres-mysql-redis-duckdb) + +#### htmx + +Brings [HTMX](https://htmx.org) support to MACH apps: server-rendered partial updates, history, request indicators, all driven by HTML attributes on the elements that need them. + +**Partial:** `{{>htmx}}`, the script tag for the HTMX runtime, served through MACH. Include in ``. + +**Context flags:** +- `is_htmx`: true when the request has the `HX-Request` header. Pair with `.if_context = "is_htmx"` to send fragments to HTMX requests and full pages to direct loads. + +**Example.** A SPA-feel app with no pipeline branching: `hx-boost='true'` on `` makes every `` and `
` inside use AJAX navigation, swapping body content instead of full page reloads. Boosted requests come through the normal pipelines. +```c +render(.template = + "" + "{{>htmx}}" + "" + "" + "
...
" + "" + "") +``` + +For HTMX attributes (`hx-boost`, `hx-target`, `hx-swap`, etc.), see the [HTMX docs](https://htmx.org/docs/). + +#### datastar + +Brings [Datastar](https://data-star.dev) support: hypermedia-driven reactive frontend where the server pushes DOM updates and reactive signal state over SSE. + +**Partial:** `{{>datastar}}`, the script tag for the Datastar runtime, served through MACH. Include in ``. + +**Context flags:** +- `is_ds`: true when the request originates from the Datastar client. Pair with `.if_context = "is_ds"` to send Datastar SSE events back to Datastar requests and full pages to direct loads. + +**Steps:** +- `ds_sse(...)`: combines SSE with Datastar-formatted events targeting specific elements. Without a channel the event goes to the requesting client; with one it broadcasts. + +`ds_sse` fields: + +**`.channel` *(pos)***: broadcast channel; supports `{{interpolation}}`. +```c +ds_sse("todos/{{user_id}}", .target = "todos", .elements = {"todo"}) +``` + +**`.target`**: DOM element id for the update. +```c +ds_sse(.target = "todos", .elements = {"todo_row"}) +``` + +**`.mode`**: fragment insertion mode for the rendered DOM fragment. +```c +ds_sse(.target = "todos", .mode = mode_prepend, .elements = {"todo_row"}) +``` + +**`.elements`**: a `render_config` for the DOM fragment (positional is the asset name, supports `.template`, `.engine`, etc.). +```c +ds_sse(.target = "row", .elements = {"todo_row"}) +``` + +**`.signals`**: JSON string used to update Datastar's reactive client state without touching the DOM. +```c +ds_sse(.signals = "{\"count\": {{count}}}") +``` + +**`.js`**: JavaScript snippet evaluated on the client. +```c +ds_sse(.js = "console.log('updated')") +``` + +**Types:** `ds_mode` enum with values `mode_outer`, `mode_inner`, `mode_replace`, `mode_prepend`, `mode_append`, `mode_before`, `mode_after`, `mode_remove`. + +**Example.** Append a new todo row to the live list across all clients on the channel: +```c +.post = { + validate({"title", .validation = validate_not_empty}), + query({.set_key = "new_todo", .db = "todos_db", + .query = "insert into todos(title) values({{title}}) returning id, title;"}), + ds_sse("todos", + .target = "#todo-list", + .mode = mode_append, + .elements = {.template = "{{#new_todo}}
  • {{title}}
  • {{/new_todo}}"}), + redirect("todos") +} +``` + +![SSE / Datastar Flow](./08-sse-datastar-flow.svg) + +For Datastar attributes, signals, and the wire-format SSE events that `ds_sse` produces, see the [Datastar reference](https://data-star.dev/reference) and specifically [SSE Events](https://data-star.dev/reference/sse_events). + +#### tailwind + +Brings [Tailwind CSS](https://tailwindcss.com) to MACH apps. + +**Partial:** `{{>tailwind}}`, the standard Tailwind CDN runtime, served through MACH. Include in ``. + +**Example.** +```c +render(.template = + "" + "{{>tailwind}}" + "" + "

    Welcome

    " + "" + "") +``` + +For utility classes and configuration, see the [Tailwind docs](https://tailwindcss.com/docs). + +#### session_auth + +Adds session-based authentication: cookie-backed sessions, login/logout/signup actions, a guard step that redirects unauthenticated users to the login page, and a step that loads the full user record into context. + +**Steps:** +- `logged_in()`: guard that redirects to the `login` resource when there's no active session. When there is one, sets `user_id` in context. Drop into a resource's shared `.steps` slot to gate the whole resource. +- `session()`: takes `user_id` from context and loads the full user record into context as `user`, including `id`, `full_name`, `short_name`. Run after `logged_in()` when verb pipelines need user details beyond just the id; skip it when only `user_id` is needed. +- `login()`, `logout()`, `signup()`: available for custom auth flows where you want to handle the action yourself. Most apps don't need these; `session_auth` provides `/login`, `/logout`, and `/signup` resources internally. + +The login page's template is whatever asset is registered under the name `login` in `.context`. Override it to use your own form. + +**Example.** A protected dashboard with full user info available: +```c +{"dashboard", "/dashboard", {logged_in(), session()}, + .get = { + render(.template = "{{#user}}

    Welcome, {{full_name}}

    {{/user}}") + } +} +``` + +For a resource that only needs the user id, drop `session()` and use just `logged_in()`: +```c +{"my_todos", "/me/todos", {logged_in()}, + .get = { + query({.set_key = "todos", .db = "todos_db", + .query = "select id, title from todos where user_id = {{user_id}};"}), + render("todos") + } +} +``` + +To customize the login page, register your own template under the name `login` in `.context`. The form posts to `/login`, where `session_auth`'s internal handler validates and authenticates. + +**`static/login.mustache.html`** +```html + +

    Sign in

    + + {{csrf:input}} + + {{#error:username}}{{error_message:username}}{{/error:username}} + + {{#error:password}}{{error_message:password}}{{/error:password}} + +
    + +``` + +```c +.context = { + {"login", (asset){ + #embed "static/login.mustache.html" + }} +} +``` + +Schema for users and sessions is created automatically on first boot. + +#### Database engines (sqlite, postgres, mysql, redis, duckdb) + +Each engine module enables one `_db` constant for use in `.databases.engine`, and registering the module is required for any database that uses it. MACH wraps each engine's native driver, so connection strings are passed through verbatim and accept whatever the underlying driver accepts. + +| Module | Engine constant | Docs | +|-----------|-----------------|------| +| `sqlite` | `sqlite_db` | [SQLite](https://sqlite.org/docs.html) | +| `postgres`| `postgres_db` | [PostgreSQL](https://www.postgresql.org/docs/) | +| `mysql` | `mysql_db` | [MySQL](https://dev.mysql.com/doc/) | +| `redis` | `redis_db` | [Redis](https://redis.io/docs/) | +| `duckdb` | `duckdb_db` | [DuckDB](https://duckdb.org/docs/) | + +Connection strings support `{{interpolation}}` for multi-tenant setups (see [Databases](#databases)). + +**Example.** Same shape regardless of engine; only `.engine`, `.connect`, and the registered module change: +```c +.databases = {{ + .engine = postgres_db, + .name = "blog_db", + .connect = "postgres://user:pass@localhost:5432/blog", + .migrations = { "CREATE TABLE posts (...);" } +}}, +.modules = {postgres} +``` + +### Static Files + +Files in `public/` at the project root are served directly. Use it for images, fonts, pre-built CSS/JS, and other assets that don't need to be embedded in the binary. Reference them with `{{asset:filename}}`, which resolves to a URL with a content checksum and immutable cache headers. + +**`public/` directory**: drop in static files; they are served at the root URL space. +``` +public/ +├── favicon.png +├── logo.png +└── styles.css +``` + +**`{{asset:filename}}`**: cache-busting helper for use inside templates. +```html + + + +``` + +### External Dependencies + +MACH expects a containerized development environment: write standard C23 against the MACH APIs, no local toolchain required. Two ways to bring in third-party C libraries, plus two helpers for bridging foreign memory back to the arena. + +**`/vendor` directory**: drop headers and libraries (`.so`, `.a`) here; the auto-compiler discovers, includes, and links them. +``` +/vendor/ +├── libsodium.h +└── libsodium.so +``` + +**Custom `Dockerfile`**: inherit from the MACH base image and `apt-get install` system dependencies; reference it from `compose.yml`. +```dockerfile +FROM mach:latest +RUN apt-get update && apt-get install -y libsodium-dev +``` + +**`allocate(bytes)`**: provides a buffer from the pipeline arena, reclaimed on request completion. +```c +char *buf = allocate(256); +``` + +**`defer_free(ptr)`**: schedules cleanup for pointers returned by external libraries (e.g. via `malloc`); runs when the arena is released. +```c +char *out = third_party_alloc(256); +defer_free(out); +``` + +--- + +## Architecture +How MACH compiles, executes, and protects an application at runtime. + +* [Data-Oriented Pipelines](#data-oriented-pipelines) +* [Multi-Reactor Architecture](#multi-reactor-architecture) +* [Safe by Default](#safe-by-default) +* [String Interpolation](#string-interpolation) + +### Data-Oriented Pipelines + +The `mach()` function runs once at boot. The returned `config` is processed into an execution graph with precompiled pipelines, queries, and templates. Each incoming request then executes its matching pipeline as a sequence of pre-warmed steps. + +![Boot-Time Compilation](./10-boot-time-compilation.svg) + +### Multi-Reactor Architecture + +MACH runs two types of reactors backed by a shared thread pool. The request/task/cpu ratio can be set in `compose.yml`. + +- **Request reactors** handle HTTP traffic; each gets its own dedicated CPU core and event loop. +- **Task reactors** handle background work; each gets its own dedicated core, monitors the task database for pending and incomplete tasks, and processes cron schedules. +- **Shared thread pool** handles CPU-bound and blocking I/O work on the remaining cores. + +When any reactor's pipeline executes an `exec()` step, the work is dispatched to the shared thread pool, which releases the reactor. When the call completes, the pipeline resumes on the original reactor. The `task()` step adds jobs to the task database, where they are picked up by task reactors. Tasks can call `task()` themselves to enqueue additional work. + +Application code does not manage threads, mutexes, or locks. The architecture isolates request state to the pipeline's context. + +![Multi-Reactor Architecture](./01-multi-reactor-architecture.svg) + +### Safe by Default + +MACH prevents common C and web vulnerabilities at the framework level. + +#### Memory Safety + +Each reactor maintains a pool of arena allocators. When a request arrives, the pipeline is assigned an arena, and all allocations draw from it. When the pipeline completes, the arena is cleared and returned to the pool. Application code does not call `malloc` or `free`, which avoids leaks, double-frees, and use-after-free. + +All framework data structures (tables, records, strings) enforce bounds checking. Out-of-bounds reads and missing context values return `nullptr` rather than faulting. Pipelines that exceed their memory limit (default 5MB, configurable in `compose.yml`) abort with a 500, mitigating OOM denial-of-service. + +#### SQL Injection Prevention + +Interpolations such as `{{user_id}}` inside `query()` or `find()` are bound as parameters in prepared statements, preventing SQL injection at the framework level. + +#### XSS Prevention + +The `render()` step auto-escapes context values in Mustache templates, so malicious input is rendered as text. Raw HTML requires explicit opt-in via Mustache's standard unescape syntax: `{{{field}}}` or `{{&field}}`. + +### String Interpolation + +Any string (SQL queries, URLs, connection strings, templates) can reference values from the context with `{{context_key}}`. The same scopes described in [Context](#context) apply everywhere interpolation is used. + +--- + +## Tooling + +* [Development Environment](#development-environment) +* [Introspection](#introspection) +* [Testing](#testing) +* [Debugging](#debugging) +* [Deployment](#deployment) +* [Observability](#observability) +* [Project Management](#project-management) +* [Built With](#built-with) + +### Development Environment +Built-in TUI editor with HMR, LSP support, integrated source control, and a topology-aware AI assistant. The AI uses the `app_info` command to inspect the full application topology (routes, pipelines, database schemas, event contracts, and module boundaries), so it reasons about the application's actual execution graph rather than just source text. + +### Introspection +```bash +app_info # view topology +app_info resources # list all resources +app_info pipelines # inspect pipelines +app_info events # view pub/sub map +app_info databases # inspect schemas +``` + +### Testing +Built-in test runners for unit and end-to-end testing; no external framework setup required. +```bash +unit_tests # fast, criterion-based tests +e2e_tests # playwright-powered browser tests +``` + +### Debugging +Built-in debugging with pipeline-aware commands. Halt on individual pipeline steps, step through execution, and inspect the full pipeline context including nested tables and records. +```bash +app_debug # interactive debugger in the TUI +``` + +### Deployment +MACH deploys as a standard Docker container. It does not terminate TLS; production deployments place MACH behind a reverse proxy or load balancer (Nginx, Caddy, AWS ALB) to handle HTTPS. +```bash +app_build # outputs slim, optimized production Docker image +``` + +### Observability +Each pipeline step emits OpenTelemetry spans. Logs, traces, errors, and auto-profiling are visualized on the telemetry server at port 4000. No manual instrumentation required. + +### Project Management +MACH ships with integrated project infrastructure: source control, issue tracking, wiki, forum, and a project website. + +### Built With + +| | | +|---|---| +| [C23](https://en.cppreference.com/w/c/23) | Language standard | +| [Docker](https://www.docker.com/) | Development environment, production images, stack orchestration | +| [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) / [libuv](https://libuv.org/) | HTTP server, event loops, async I/O, file watching, shared thread pool | +| [Mustach](https://gitlab.com/jobol/mustach) | Templating and string interpolation | +| [Jansson](https://github.com/akheron/jansson) | JSON parsing and generation | +| [curl](https://curl.se/) | HTTP client for fetch steps | +| [Fossil](https://fossil-scm.org/) | Source control, wiki, forum, issue tracker, project site | +| [Fresh](https://getfresh.dev/) | TUI editor | +| [clangd](https://clangd.llvm.org/) | Language server | +| [LLDB](https://lldb.llvm.org/) | Debugger | +| [Criterion](https://github.com/Snaipe/Criterion) | Unit testing | +| [Playwright](https://playwright.dev/) | End-to-end testing | +| [SigNoz](https://signoz.io/) + [OpenTelemetry](https://opentelemetry.io/) | APM, traces, logs, errors, dashboards | +| [Open Code](https://opencode.ai/) | AI assistant with custom agent and skill files | + +--- + +## License + +MACH is licensed under the [LGPL](./LICENSE).