From 608bd9f36e6f0136c3f5f40b689531fae44f9d52 Mon Sep 17 00:00:00 2001 From: nightshade Date: Thu, 24 Jul 2025 12:46:01 -0500 Subject: [PATCH] MaCH repo --- 00_hello_text/main.c | 10 + 01-multi-reactor-architecture.svg | 155 ++ 01_hello_world_text/main.c | 11 + 02-request-pipeline-flow.svg | 95 + 02_hello_world_html/main.c | 18 + 03-event-pub-sub.svg | 66 + .../create_hello_world_table.sql | 4 + 03_hello_world_html_db/get_hello_world.sql | 3 + .../hello_world.mustache.html | 7 + 03_hello_world_html_db/main.c | 18 + 03_hello_world_html_db/seed_hello_world.sql | 2 + 04-error-resolution.svg | 46 + 04_todo/404.mustache.html | 5 + 04_todo/5xx.mustache.html | 5 + 04_todo/about.mustache.html | 5 + 04_todo/contact.mustache.html | 5 + 04_todo/create_todo.sql | 2 + 04_todo/create_todos_table.sql | 7 + 04_todo/delete_todo.sql | 3 + 04_todo/get_todos.sql | 3 + 04_todo/home.mustache.html | 5 + 04_todo/layout.mustache.html | 23 + 04_todo/main.c | 54 + 04_todo/public/favicon.png | 0 04_todo/todos.mustache.html | 30 + 04_todo/update_todo.sql | 4 + 05-app-composition-tree.svg | 58 + 05_todo_sse_datastar/404.mustache.html | 5 + 05_todo_sse_datastar/5xx.mustache.html | 5 + 05_todo_sse_datastar/about.mustache.html | 5 + 05_todo_sse_datastar/contact.mustache.html | 5 + 05_todo_sse_datastar/create_todo.sql | 3 + 05_todo_sse_datastar/create_todos_table.sql | 7 + 05_todo_sse_datastar/delete_todo.sql | 4 + 05_todo_sse_datastar/get_todos.sql | 3 + 05_todo_sse_datastar/home.mustache.html | 5 + 05_todo_sse_datastar/layout.mustache.html | 25 + 05_todo_sse_datastar/main.c | 56 + 05_todo_sse_datastar/public/favicon.png | 0 05_todo_sse_datastar/todo.mustache.html | 3 + 05_todo_sse_datastar/todo_item.mustache.html | 10 + 05_todo_sse_datastar/todos.mustache.html | 19 + 05_todo_sse_datastar/update_todo.sql | 5 + 06-middleware-scoping.svg | 52 + 06_todo_events/activity/activity.c | 25 + .../activity/activity.mustache.html | 13 + .../activity/create_activity_table.sql | 8 + 06_todo_events/activity/get_activities.sql | 5 + 06_todo_events/activity/insert_activity.sql | 2 + 06_todo_events/main.c | 12 + 06_todo_events/public/favicon.png | 0 06_todo_events/static/404.mustache.html | 5 + 06_todo_events/static/5xx.mustache.html | 5 + 06_todo_events/static/home.mustache.html | 5 + 06_todo_events/static/layout.mustache.html | 20 + 06_todo_events/todos/create_todo.sql | 2 + 06_todo_events/todos/create_todos_table.sql | 7 + 06_todo_events/todos/delete_todo.sql | 3 + 06_todo_events/todos/get_todos.sql | 3 + 06_todo_events/todos/todos.c | 44 + 06_todo_events/todos/todos.mustache.html | 30 + 06_todo_events/todos/update_todo.sql | 4 + 07_roundest_pokemon_htmx/README.md | 1 + .../create_pokemons_table.sql | 7 + 07_roundest_pokemon_htmx/get_challengers.sql | 4 + 07_roundest_pokemon_htmx/get_results.sql | 5 + 07_roundest_pokemon_htmx/home.mustache.html | 53 + 07_roundest_pokemon_htmx/main.c | 41 + .../results.mustache.html | 28 + 07_roundest_pokemon_htmx/vote.sql | 8 + 08-sse-datastar-flow.svg | 96 + 09-database-multi-tenancy.svg | 89 + 10-boot-time-compilation.svg | 82 + COPYING | 674 +++++ COPYING.LESSER | 165 ++ LICENSE | 165 ++ README.md | 2199 +++++++++++++++++ 77 files changed, 4666 insertions(+) create mode 100644 00_hello_text/main.c create mode 100644 01-multi-reactor-architecture.svg create mode 100644 01_hello_world_text/main.c create mode 100644 02-request-pipeline-flow.svg create mode 100644 02_hello_world_html/main.c create mode 100644 03-event-pub-sub.svg create mode 100644 03_hello_world_html_db/create_hello_world_table.sql create mode 100644 03_hello_world_html_db/get_hello_world.sql create mode 100644 03_hello_world_html_db/hello_world.mustache.html create mode 100644 03_hello_world_html_db/main.c create mode 100644 03_hello_world_html_db/seed_hello_world.sql create mode 100644 04-error-resolution.svg create mode 100644 04_todo/404.mustache.html create mode 100644 04_todo/5xx.mustache.html create mode 100644 04_todo/about.mustache.html create mode 100644 04_todo/contact.mustache.html create mode 100644 04_todo/create_todo.sql create mode 100644 04_todo/create_todos_table.sql create mode 100644 04_todo/delete_todo.sql create mode 100644 04_todo/get_todos.sql create mode 100644 04_todo/home.mustache.html create mode 100644 04_todo/layout.mustache.html create mode 100644 04_todo/main.c create mode 100644 04_todo/public/favicon.png create mode 100644 04_todo/todos.mustache.html create mode 100644 04_todo/update_todo.sql create mode 100644 05-app-composition-tree.svg create mode 100644 05_todo_sse_datastar/404.mustache.html create mode 100644 05_todo_sse_datastar/5xx.mustache.html create mode 100644 05_todo_sse_datastar/about.mustache.html create mode 100644 05_todo_sse_datastar/contact.mustache.html create mode 100644 05_todo_sse_datastar/create_todo.sql create mode 100644 05_todo_sse_datastar/create_todos_table.sql create mode 100644 05_todo_sse_datastar/delete_todo.sql create mode 100644 05_todo_sse_datastar/get_todos.sql create mode 100644 05_todo_sse_datastar/home.mustache.html create mode 100644 05_todo_sse_datastar/layout.mustache.html create mode 100644 05_todo_sse_datastar/main.c create mode 100644 05_todo_sse_datastar/public/favicon.png create mode 100644 05_todo_sse_datastar/todo.mustache.html create mode 100644 05_todo_sse_datastar/todo_item.mustache.html create mode 100644 05_todo_sse_datastar/todos.mustache.html create mode 100644 05_todo_sse_datastar/update_todo.sql create mode 100644 06-middleware-scoping.svg create mode 100644 06_todo_events/activity/activity.c create mode 100644 06_todo_events/activity/activity.mustache.html create mode 100644 06_todo_events/activity/create_activity_table.sql create mode 100644 06_todo_events/activity/get_activities.sql create mode 100644 06_todo_events/activity/insert_activity.sql create mode 100644 06_todo_events/main.c create mode 100644 06_todo_events/public/favicon.png create mode 100644 06_todo_events/static/404.mustache.html create mode 100644 06_todo_events/static/5xx.mustache.html create mode 100644 06_todo_events/static/home.mustache.html create mode 100644 06_todo_events/static/layout.mustache.html create mode 100644 06_todo_events/todos/create_todo.sql create mode 100644 06_todo_events/todos/create_todos_table.sql create mode 100644 06_todo_events/todos/delete_todo.sql create mode 100644 06_todo_events/todos/get_todos.sql create mode 100644 06_todo_events/todos/todos.c create mode 100644 06_todo_events/todos/todos.mustache.html create mode 100644 06_todo_events/todos/update_todo.sql create mode 100644 07_roundest_pokemon_htmx/README.md create mode 100644 07_roundest_pokemon_htmx/create_pokemons_table.sql create mode 100644 07_roundest_pokemon_htmx/get_challengers.sql create mode 100644 07_roundest_pokemon_htmx/get_results.sql create mode 100644 07_roundest_pokemon_htmx/home.mustache.html create mode 100644 07_roundest_pokemon_htmx/main.c create mode 100644 07_roundest_pokemon_htmx/results.mustache.html create mode 100644 07_roundest_pokemon_htmx/vote.sql create mode 100644 08-sse-datastar-flow.svg create mode 100644 09-database-multi-tenancy.svg create mode 100644 10-boot-time-compilation.svg create mode 100644 COPYING create mode 100644 COPYING.LESSER create mode 100644 LICENSE create mode 100644 README.md diff --git a/00_hello_text/main.c b/00_hello_text/main.c new file mode 100644 index 0000000..81448ad --- /dev/null +++ b/00_hello_text/main.c @@ -0,0 +1,10 @@ +#include + +mach(main){ + context("greeting", "hello world"); + resource("home", "/", .mime = m_txt, + .get = { + mustache("greeting") + } + ); +} 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..e354642 --- /dev/null +++ b/01_hello_world_text/main.c @@ -0,0 +1,11 @@ +#include + +mach(main){ + context("greeting", "hello {{name}}"); + resource("home", "/", .mime = m_txt, + .get = { + input({"name", .fallback = "world"}), + mustache("greeting") + } + ); +} 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..3e04d06 --- /dev/null +++ b/02_hello_world_html/main.c @@ -0,0 +1,18 @@ +#include + +mach(main){ + context("greeting", + "" + "" + "" + "

Hello {{name}}

" + "" + "" + ); + resource("home", "/", + .get = { + input({"name", .fallback = "world"}), + mustache("greeting") + } + ); +} 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/create_hello_world_table.sql b/03_hello_world_html_db/create_hello_world_table.sql new file mode 100644 index 0000000..cfebf30 --- /dev/null +++ b/03_hello_world_html_db/create_hello_world_table.sql @@ -0,0 +1,4 @@ +CREATE TABLE greetings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL +); diff --git a/03_hello_world_html_db/get_hello_world.sql b/03_hello_world_html_db/get_hello_world.sql new file mode 100644 index 0000000..4295826 --- /dev/null +++ b/03_hello_world_html_db/get_hello_world.sql @@ -0,0 +1,3 @@ +select name +from greetings +limit 1; diff --git a/03_hello_world_html_db/hello_world.mustache.html b/03_hello_world_html_db/hello_world.mustache.html new file mode 100644 index 0000000..07ba98c --- /dev/null +++ b/03_hello_world_html_db/hello_world.mustache.html @@ -0,0 +1,7 @@ + + + {{#hello_world_data}} +

Hello {{name}}

+ {{/hello_world_data}} + + diff --git a/03_hello_world_html_db/main.c b/03_hello_world_html_db/main.c new file mode 100644 index 0000000..94f0a3d --- /dev/null +++ b/03_hello_world_html_db/main.c @@ -0,0 +1,18 @@ +#include +#include + +mach(main){ + sqlite_database( + .name = "hello_db", + .connect = "file:hello.db?mode=rwc", + .migrations = {"create_hello_world_table"}, + .seeds = {"seed_hello_world"} + ); + + resource("home", "/", + .get = { + sqlite_query({"hello_db", "get_hello_world", "hello_world_data"}), + mustache("hello_world") + } + ); +} diff --git a/03_hello_world_html_db/seed_hello_world.sql b/03_hello_world_html_db/seed_hello_world.sql new file mode 100644 index 0000000..d6886f2 --- /dev/null +++ b/03_hello_world_html_db/seed_hello_world.sql @@ -0,0 +1,2 @@ +INSERT INTO greetings(name) +VALUES('World'); 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..d7fa872 --- /dev/null +++ b/04_todo/main.c @@ -0,0 +1,54 @@ +#include +#include +#include + +mach(main){ + middleware(session()); + + sqlite_database( + .name ="todos_db", + .connect = "file:{{user_id}}_todo.db?mode=rwc", + .migrations = {"create_todos_table"} + ); + + resource("home", "/", + .get = {mustache("home")} + ); + + resource("about", "/about", + .get = {mustache("about")} + ); + + resource("contact", "/contact", + .get = {mustache("contact")} + ); + + resource("todos", "/todos", + .all = {logged_in()}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), + redirect("todos") + } + ); + + resource("todo", "/todos/:id", + .all = { + logged_in(), + input({"id", m_positive}) + }, + .patch = { + input({"finished", "1", "must be 1", .optional = true,}), + sqlite_query({"todos_db", "update_todo"}), + redirect("todos") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo"}), + redirect("todos") + } + ); +} 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..f366890 --- /dev/null +++ b/04_todo/todos.mustache.html @@ -0,0 +1,30 @@ +{{< layout}} + {{$body}} +
+ + +
+ {{^todos_data}} +

no todos

+ {{/todos_data}} + {{#todos_data}} +
+
+ + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
+
+ + +
+
+ {{/todos_data}} + {{/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..1e55b17 --- /dev/null +++ b/05_todo_sse_datastar/main.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +mach(main){ + middleware(session()); + + sqlite_database( + .name = "todos_db", + .connect = "file:todo.db?mode=rwc", + .migrations = {"create_todos_table"} + ); + + resource("home", "/", + .get = {mustache("home")} + ); + + resource("about", "/about", + .get = {mustache("about")} + ); + + resource("contact", "/contact", + .get = {mustache("contact")} + ); + + resource("todos", "/todos", + .all = {logged_in()}, + .sse = {"todos:{{user_id}}"}, + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo", "todo_data", .must_exist = true}), + datastar_sse("todos:{{user_id}}", .target = "todos", .mode = mode_prepend, .elements = {"todo"}) + } + ); + + resource("todo", "/todos/:id", + .all = { + logged_in(), + input({"id", m_positive}) + }, + .patch = { + input({"finished", "1", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo", "todo_data", .must_exist = true}), + datastar_sse("todos:{{user_id}}", .target = "todo_{{id}}", .mode = mode_replace, .elements = {"todo"}) + }, + .delete = { + sqlite_query({"todos_db", "delete_todo", .must_exist = true}), + datastar_sse("todos:{{user_id}}", .target = "todo_{{id}}", .mode = mode_remove) + } + ); +} 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..a0bc20c --- /dev/null +++ b/05_todo_sse_datastar/todo.mustache.html @@ -0,0 +1,3 @@ +{{#todo_data}} + {{> todo_item}} +{{/todo_data}} diff --git a/05_todo_sse_datastar/todo_item.mustache.html b/05_todo_sse_datastar/todo_item.mustache.html new file mode 100644 index 0000000..dd6588e --- /dev/null +++ b/05_todo_sse_datastar/todo_item.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..f64cfce --- /dev/null +++ b/05_todo_sse_datastar/todos.mustache.html @@ -0,0 +1,19 @@ +{{< layout}} + {{$head}} + {{> datastar }} + {{/head}} + {{$body}} + + +
+ {{^todos_data}} +

no todos

+ {{/todos_data}} + {{#todos_data}} + {{> todo_item}} + {{/todos_data}} +
+ {{/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..dea71e4 --- /dev/null +++ b/06_todo_events/activity/activity.c @@ -0,0 +1,25 @@ +#include +#include +#include +#include + +mach(activity){ + middleware(logged_in(), session()); + + sqlite_database( + .name = "activity_db", + .connect = "file:activity.db?mode=rwc", + .migrations = {"create_activity_table"} + ); + + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) + }); + + resource("activity", "/activity", + .get = { + sqlite_query({"activity_db", "get_activities", "activity"}), + mustache("activity") + } + ); +} 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..2921759 --- /dev/null +++ b/06_todo_events/main.c @@ -0,0 +1,12 @@ +#include +#include +#include "todos/todos.c" +#include "activity/activity.c" + +mach(main){ + middleware(session()); + + resource("home", "/", + .get = {mustache("home")} + ); +} 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..3962499 --- /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..9d3edc2 --- /dev/null +++ b/06_todo_events/todos/todos.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include + +mach(todos){ + middleware(logged_in(), session()); + + sqlite_database( + .name = "todos_db", + .connect = "file:todo.db?mode=rwc", + .migrations = {"create_todos_table"} + ); + + publish("todo_created", + .with = {"user_id", "title"} + ); + + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), + emit("todo_created"), + redirect("todos") + } + ); + + resource("todo", "/todos/:id", + .all = {input({"id", m_positive})}, + .patch = { + input({"finished", "1", "must be 1", .optional = true}), + sqlite_query({"todos_db", "update_todo"}), + redirect("todos") + }, + .delete = { + sqlite_query({"todos_db", "delete_todo"}), + redirect("todos") + } + ); +} diff --git a/06_todo_events/todos/todos.mustache.html b/06_todo_events/todos/todos.mustache.html new file mode 100644 index 0000000..f366890 --- /dev/null +++ b/06_todo_events/todos/todos.mustache.html @@ -0,0 +1,30 @@ +{{< layout}} + {{$body}} +
+ + +
+ {{^todos_data}} +

no todos

+ {{/todos_data}} + {{#todos_data}} +
+
+ + {{^finished}} + + {{/finished}} + {{#finished}} + + {{/finished}} + {{title}} + +
+
+ + +
+
+ {{/todos_data}} + {{/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_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..2642392 --- /dev/null +++ b/07_roundest_pokemon_htmx/home.mustache.html @@ -0,0 +1,53 @@ + + + + Roundest (MaCH Version) + {{> htmx }} + {{> tailwind }} + + +
+ +
+ {{$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..0749a6d --- /dev/null +++ b/07_roundest_pokemon_htmx/main.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +mach(main){ + sqlite_database( + .name = "pokemon_db", + .connect = "file::memory:?cache=shared", + .migrations = {"create_pokemons_table"} + ); + + resource("home", "/", + .get = { + sqlite_query({"pokemon_db", "get_challengers", "challengers"}), + 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")); + }), + mustache("home") + }, + .post = { + input( + {"winner", m_positive}, + {"loser", m_positive} + ), + sqlite_query({"pokemon_db", "vote"}), + reroute("home") + } + ); + + resource("result", "/results", + .get = { + sqlite_query({"pokemon_db", "get_results", "results"}), + mustache("results") + } + ); +} 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/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..a90d86d --- /dev/null +++ b/README.md @@ -0,0 +1,2199 @@ + +# MACH + +## Why MACH + +MACH (Modern Asynchronous C Hypermedia) is a declarative framework for building asynchronous web applications in C23. + +* **No build configuration.** Compilation, hot code reloading, and HMR are handled by the framework. No build scripts, package managers, or ORMs. SQL and HTML assets are discovered automatically. +* **Memory, concurrency, and I/O managed by the framework.** Application code does not call `malloc`/`free` or manage threads, mutexes, or locks. Queries run as prepared statements. Pipeline steps emit OpenTelemetry spans, logs, and errors automatically. +* **Durable tasks and events.** Both are persisted. After a crash, incomplete tasks resume at the step where they stopped and undelivered events replay on the next boot. +* **Bundled modules.** 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) +* [Built With](#built-with) +* [License](#license) + +--- + +## Quick Start + +Everything runs in Docker. No other local dependencies. + +```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 editor, AI, LSP, and console. + +```c +#include + +mach(){ + context("hello", "

Hello, world!

"); + resource("home", "/", .get = {mustache("hello")}); +} +``` + +`mach()` runs once at boot and declares the application. `context()` registers a named template inline; `resource()` declares the `home` endpoint mapping `/` to a GET pipeline that renders that template. See the [Guide](#guide) for a step-by-step walkthrough. + +--- + +## Philosophy + +An application is a data transformation: input arrives, gets transformed, leaves as output. MACH is a thin pipeline wrapper around that path. + +All assets and toolimg are standard: raw SQL, JSON, Markdown, and HTML/CSS/JS via Mustache templates, business logic is plain C, lldb for debugging, Playwright and Criterion for testing, OpenTelemetry for observability, OpenCode for AI. MACH arranges these into pipelines: ordered lists of steps that turn a request into a response. + +### Everything is a String + +The web is text: HTTP, HTML, JSON, SQL. The pipeline context stores and passes data as strings. There is no intermediate parsing or serialization layer. Strings are interpolated into SQL, templates, and URLs with `{{context_key}}`. + +### CLAD + +Four principles: + +* **(C)omposable:** small, independent steps chain into feature pipelines. +* **(L)ocality of Behavior:** behavior is apparent from reading the code. SQL, templates, and logic for a feature live together, not spread across model, view, and controller trees. +* **(A)utonomous:** modules are self-contained: own schemas, migrations, seeds, routes, UI, and logic. The compiler enforces boundaries. +* **(D)omain Based:** each module owns one slice of the app. A `todos` module defines everything related to todos and nothing else. + +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 + +Builds a todo app one concept at a time. See the [Reference](#reference) for full options on each step, helper, and field. MACH discovers assets automatically and seeds each into the context of the module that owns it, based on file location (see [Assets](#assets)). + +* [1. Pages and Templates](#1-pages-and-templates) +* [2. Show Data](#2-show-data) +* [3. Accept Input](#3-accept-input) +* [4. Nested Data](#4-nested-data) +* [5. Tasks](#5-tasks) +* [6. Modules and Events](#6-modules-and-events) +* [7. Calling APIs](#7-calling-apis) + +### 1. Pages and Templates + +Each `resource(...)` declares a named URL endpoint; each verb pipeline is a list of steps. `mustache("home")` renders the template asset `home`, which is the file `home.mustache.html`. Reference resources by name with `{{url:...}}`. + +Both pages share a layout, so `home` doubles as the layout: it declares the nav and a `{{$body}}` block whose default is the welcome page. The `todos` page extends it with `{{ + + +
{{$body}}

Welcome

{{/body}}
+ + +``` + +**`todos.mustache.html`** +```html +{{My Todos +

Nothing yet.

+ {{/body}} +{{/home}} +``` + +**`main.c`** +```c +#include + +mach(){ + resource("home", "/", .get = {mustache("home")}); + resource("todos", "/todos", .get = {mustache("todos")}); +} +``` + +See [Resource Pipelines](#resource-pipelines) and [Templates](#templates). + +### 2. Show Data + +Bring in SQLite with `#include `, declare a database with `sqlite_database(...)`, and read with `sqlite_query()`. SQL files are assets like templates: `get_todos.sql` becomes the asset `get_todos`. + +Three new SQL files: + +**`create_todos_table.sql`** +```sql +CREATE TABLE todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL +); +``` + +**`seed_todos.sql`** +```sql +INSERT INTO todos(title) VALUES('Learn MACH'); +``` + +**`get_todos.sql`** +```sql +select id, title from todos; +``` + +Render the rows MACH stores under `todos_data`: + +**`todos.mustache.html`** +```diff + {{My Todos +-

Nothing yet.

++
    {{#todos_data}}
  • {{title}}
  • {{/todos_data}}
+ {{/body}} + {{/home}} +``` + +Wire up the module, database, and query: + +**`main.c`** +```diff + #include ++#include + + mach(){ ++ sqlite_database( ++ "todos_db", ++ "file:todos.db?mode=rwc", ++ {"create_todos_table"}, ++ {"seed_todos"} ++ ); ++ + resource("home", "/", .get = {mustache("home")}); +- resource("todos", "/todos", .get = {mustache("todos")}); ++ ++ resource("todos", "/todos", ++ .get = { ++ sqlite_query({"todos_db", "get_todos", "todos_data"}), ++ mustache("todos") ++ } ++ ); + } +``` + +Query parameters: database name, SQL asset, context key for the result table (`todos_data`). The template walks the result with `{{#todos_data}}...{{/todos_data}}`. Migrations and seeds run on first connection. See [Databases](#databases) and [query](#query). + +### 3. Accept Input + +Add a `.post` verb that validates, inserts, and redirects (POST-redirect-GET). A resource-scoped `.errors` handler re-renders the form on validation failure. + +**`create_todo.sql`** +```sql +insert into todos(title) values({{title}}); +``` + +Add the form, repopulating the field and showing the error after a failed submit: + +**`todos.mustache.html`** +```diff + {{My Todos +
    {{#todos_data}}
  • {{title}}
  • {{/todos_data}}
++
++ {{csrf:input}} ++ ++ {{#error:title}}{{error_message:title}}{{/error:title}} ++ ++
+ {{/body}} + {{/home}} +``` + +Add a `.post` verb and an `.errors` handler: + +**`main.c`** +```diff + #include + #include + + mach(){ + sqlite_database( + "todos_db", + "file:todos.db?mode=rwc", + {"create_todos_table"}, + {"seed_todos"} + ); + + resource("home", "/", .get = {mustache("home")}); + + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") +- } ++ }, ++ .post = { ++ input({"title", m_not_empty}), ++ sqlite_query({"todos_db", "create_todo"}), ++ redirect("todos") ++ }, ++ .errors = { ++ {m_bad_request, {reroute("todos")}} ++ } + ); + } +``` + +`input()` validates and promotes `title` to app scope; the `{{title}}` in `create_todo.sql` binds as a prepared-statement parameter. On failure, `m_bad_request` triggers the handler, which `reroute`s back into the GET pipeline in-process. The `input:` and `error:` scopes survive the reroute, so the form repopulates with `{{input:title}}` and shows `{{error_message:title}}`. See [input](#input), [Error and Repair Pipelines](#error-and-repair-pipelines), and [redirect and reroute](#redirect-and-reroute). + +### 4. Nested Data + +A `/todos/:id` page fetches a todo and its comments concurrently, then nests the comments inside the todo with `join()`. + +Three new SQL files and one new template: + +**`create_comments_table.sql`** +```sql +CREATE TABLE comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + todo_id INTEGER NOT NULL REFERENCES todos(id), + body TEXT NOT NULL +); +``` + +**`get_todo.sql`** +```sql +select id, title from todos where id = {{id}}; +``` + +**`get_comments.sql`** +```sql +select id, todo_id, body from comments where todo_id = {{id}}; +``` + +Enter `{{#todo_data}}` first; after the join, `comments` lives inside each todo record: + +**`todo.mustache.html`** +```html +{{{{title}} +

Comments

+
    {{#comments}}
  • {{body}}
  • {{/comments}}
+ {{/todo_data}} + {{/body}} +{{/home}} +``` + +Link each list item to its detail page. `{{url:todo}}` resolves to the `todo` resource's pattern (`/todos/:id`) and fills `:id` from the current row, so no argument is needed: + +**`todos.mustache.html`** +```diff + {{My Todos +-
    {{#todos_data}}
  • {{title}}
  • {{/todos_data}}
++ +
+ {{csrf:input}} + + {{#error:title}}{{error_message:title}}{{/error:title}} + +
+ {{/body}} + {{/home}} +``` + +Register the migration and add a `todo` resource: + +**`main.c`** +```diff + #include + #include + + mach(){ + sqlite_database( + "todos_db", + "file:todos.db?mode=rwc", +- {"create_todos_table"}, ++ {"create_todos_table", "create_comments_table"}, + {"seed_todos"} + ); + + resource("home", "/", .get = {mustache("home")}); + + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), + redirect("todos") + }, + .errors = { + {m_bad_request, {reroute("todos")}} + } + ); ++ ++ resource("todo", "/todos/:id", ++ .get = { ++ input({"id", m_integer}), ++ sqlite_query( ++ {"todos_db", "get_todo", "todo_data", .must_exist = true}, ++ {"todos_db", "get_comments", "comments"} ++ ), ++ join("todo_data", "id", "comments", "todo_id"), ++ mustache("todo") ++ } ++ ); + } +``` + +Both queries in one `sqlite_query()` call run concurrently. `join()` lifts `comments` inside each `todo_data` record, so the template reaches `{{#comments}}` from within `{{#todo_data}}`. `.must_exist = true` returns 404 when the id matches nothing. See [join](#join) and [query](#query). + +### 5. Tasks + +A task is a named pipeline that runs off the request path on a task reactor. Define it once with optional `.cron`; enqueue on-demand runs with `run("name")`. + +Two new SQL files: + +**`create_daily_stats_table.sql`** +```sql +CREATE TABLE daily_stats ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + todo_count INTEGER NOT NULL +); +``` + +**`record_daily_stats.sql`** +```sql +insert into daily_stats(todo_count) select count(*) from todos; +``` + +Register the migration, define the task, enqueue it from the POST: + +**`main.c`** +```diff + #include + #include ++#include + + mach(){ + sqlite_database( + "todos_db", + "file:todos.db?mode=rwc", +- {"create_todos_table", "create_comments_table"}, ++ {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + {"seed_todos"} + ); + ++ task("record_daily_stats", { ++ sqlite_query({"todos_db", "record_daily_stats"}) ++ }, .cron = "0 0 * * *"); ++ + resource("home", "/", .get = {mustache("home")}); + + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), ++ run("record_daily_stats"), + redirect("todos") + }, + .errors = { + {m_bad_request, {reroute("todos")}} + } + ); + + resource("todo", "/todos/:id", + .get = { + input({"id", m_integer}), + sqlite_query( + {"todos_db", "get_todo", "todo_data", .must_exist = true}, + {"todos_db", "get_comments", "comments"} + ), + join("todo_data", "id", "comments", "todo_id"), + mustache("todo") + } + ); + } +``` + +`.cron` and `run("record_daily_stats")` both run the task on a task reactor, off the request reactors, so the POST returns immediately. Tasks are durable: a crash mid-task resumes on the next boot. To hand values to a task, list them under `.accepts`. See [Task Pipelines](#task-pipelines). + +### 6. Modules and Events + +Split features into modules that talk through pub/sub events. A module is a folder with a matching `.c` file (`todos/todos.c`) declaring `module(todos){ ... }`, which registers the module's resources, databases, tasks, and subscribers. Assets in the folder belong to the module. `main.c` composes modules by `#include`ing each `.c` file; the include is all that is needed. + +This step moves todos into its own module and adds an `activity` module that records an entry whenever a todo is created. Move the todos assets into `todos/`, add the new `activity/` folder, leave `home` (the shared layout) at the root: + +``` +. +├── todos/ +│ ├── todos.c +│ ├── todos.mustache.html +│ ├── todo.mustache.html +│ ├── create_todos_table.sql +│ ├── seed_todos.sql +│ ├── get_todos.sql +│ ├── get_todo.sql +│ ├── get_comments.sql +│ └── create_todo.sql +├── activity/ +│ ├── activity.c +│ ├── activity.mustache.html +│ ├── create_activity_table.sql +│ ├── get_activities.sql +│ └── insert_activity.sql +├── home.mustache.html +└── main.c +``` + +`main.c` collapses to a thin composer: + +**`main.c`** +```diff + #include +-#include +-#include ++#include "todos/todos.c" ++#include "activity/activity.c" + + mach(){ +- sqlite_database( +- "todos_db", +- "file:todos.db?mode=rwc", +- {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, +- {"seed_todos"} +- ); +- +- task("record_daily_stats", { +- sqlite_query({"todos_db", "record_daily_stats"}) +- }, .cron = "0 0 * * *"); +- + resource("home", "/", .get = {mustache("home")}); +- +- resource("todos", "/todos", +- .get = { +- sqlite_query({"todos_db", "get_todos", "todos_data"}), +- mustache("todos") +- }, +- .post = { +- input({"title", m_not_empty}), +- sqlite_query({"todos_db", "create_todo"}), +- run("record_daily_stats"), +- redirect("todos") +- }, +- .errors = { +- {m_bad_request, {reroute("todos")}} +- } +- ); +- +- resource("todo", "/todos/:id", +- .get = { +- input({"id", m_integer}), +- sqlite_query( +- {"todos_db", "get_todo", "todo_data", .must_exist = true}, +- {"todos_db", "get_comments", "comments"} +- ), +- join("todo_data", "id", "comments", "todo_id"), +- mustache("todo") +- } +- ); + } +``` + +Add an Activity link to the shared nav: + +**`home.mustache.html`** +```diff + + +- ++ +
{{$body}}

Welcome

{{/body}}
+ + +``` + +The todos logic moves into the module unchanged, gaining a `publish()` and an `emit()` step. Both todo resources come along: + +**`todos/todos.c`** +```c +#include +#include +#include +#include + +module(todos){ + sqlite_database( + "todos_db", + "file:todos.db?mode=rwc", + {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + {"seed_todos"} + ); + + publish("todo_created", .with = {"title"}); + + task("record_daily_stats", { + sqlite_query({"todos_db", "record_daily_stats"}) + }, .cron = "0 0 * * *"); + + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos") + }, + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), + run("record_daily_stats"), + emit("todo_created"), + redirect("todos") + }, + .errors = { + {m_bad_request, {reroute("todos")}} + } + ); + + resource("todo", "/todos/:id", + .get = { + input({"id", m_integer}), + sqlite_query( + {"todos_db", "get_todo", "todo_data", .must_exist = true}, + {"todos_db", "get_comments", "comments"} + ), + join("todo_data", "id", "comments", "todo_id"), + mustache("todo") + } + ); +} +``` + +The `activity` module owns its own table, query, template, and subscriber. Nothing in it references the todos module: + +**`activity/create_activity_table.sql`** +```sql +CREATE TABLE activities ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + ref TEXT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +**`activity/insert_activity.sql`** +```sql +insert into activities(kind, ref) values('created', {{title}}); +``` + +**`activity/get_activities.sql`** +```sql +select kind, ref, created_at from activities order by created_at desc; +``` + +**`activity/activity.mustache.html`** +```html +{{Activity +
    {{#activities}}
  • {{kind}}: {{ref}} ({{created_at}})
  • {{/activities}}
+ {{/body}} +{{/home}} +``` + +**`activity/activity.c`** +```c +#include +#include +#include + +module(activity){ + sqlite_database( + "activity_db", + "file:activity.db?mode=rwc", + {"create_activity_table"} + ); + + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) + }); + + resource("activity", "/activity", + .get = { + sqlite_query({"activity_db", "get_activities", "activities"}), + mustache("activity") + } + ); +} +``` + +When the POST calls `emit("todo_created")`, MACH propagates the keys named in `publish(...).with` (`title`) to every subscriber. The `activity` module writes its row with no direct link to the publisher. Events are durable: undelivered ones replay after a crash. Adding a third subscriber is a new file with its own `subscribe(...)`; the publisher does not change. See [Modules and Composition](#modules-and-composition) and [Event Pipelines](#event-pipelines). + +### 7. Calling APIs + +`fetch()` calls external HTTP services like a query calls a database. JSON parses into context tables; multiple items in one `fetch()` run concurrently. + +Show the responses on the home page: + +**`home.mustache.html`** +```diff + + + +-
{{$body}}

Welcome

{{/body}}
++
{{$body}} ++

Welcome

++ {{#weather}}

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

{{/weather}} ++ {{#quote}}
{{content}}, {{author}}
{{/quote}} ++ {{/body}}
+ + +``` + +Fetch both services concurrently before rendering: + +**`main.c`** +```diff + #include + #include "todos/todos.c" + #include "activity/activity.c" + + mach(){ +- resource("home", "/", .get = {mustache("home")}); ++ resource("home", "/", ++ .get = { ++ fetch( ++ {"https://api.quotes.dev/random", "quote"}, ++ {"https://api.weather.dev/now", "weather"} ++ ), ++ mustache("home") ++ } ++ ); + } +``` + +Both requests run concurrently under one `fetch()` call. The JSON parses into context tables the template walks with `{{#quote}}` and `{{#weather}}`. `fetch()` also supports other verbs, headers, request bodies, and interpolated URLs. See [fetch](#fetch). + +--- +## Reference + +* [Context](#context) +* [Templates](#templates) +* [Assets](#assets) +* [Databases](#databases) +* [Resource Pipelines](#resource-pipelines) +* [Pipeline Steps](#pipeline-steps) +* [Imperative API](#imperative-api) +* [Conditionals](#conditionals) +* [Iteration](#iteration) +* [Error and Repair Pipelines](#error-and-repair-pipelines) +* [Event Pipelines](#event-pipelines) +* [Task Pipelines](#task-pipelines) +* [Modules and Composition](#modules-and-composition) +* [Module Reference](#module-reference) +* [Static Files](#static-files) +* [External Dependencies](#external-dependencies) + +### Context + +Pipelines read from and write to a shared, scoped key-value store that lives for one request. Every step draws inputs from context and writes outputs back. + +Three scopes: `input:xxx` for raw request parameters, `error:xxx` for validation/error data, and unprefixed names for app scope (query results, validated inputs, computed values). `input()` promotes values from `input:` to app scope. + +### Templates + +MACH uses Mustache and MDM (Mustache + Markdown) templates. The full Mustache base spec is supported except dot notation: `{{a.b}}` does not work; use `{{#a}}{{b}}{{/a}}`. + +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 asset `name`, rendered against the current scope. +- **Layout inheritance**: `{{Total: ${{precision:total:2}}

+``` + +**`{{input:field}}`**: raw, unvalidated request parameter from the `input` scope. Used to repopulate form fields after a validation error. +```html + +``` + +**`{{error:field}}`**: truthy when `field` has an error. Used as a Mustache section to conditionally render markup. +```html +{{#error:title}}invalid{{/error:title}} +``` + +**`{{error_message:field}}`**: human-readable message for a field error, from `input()`'s message or from `error_set()`. +```html +{{error_message:title}} +``` + +**`{{error_code:field}}`**: HTTP status code associated with a field error (e.g. `400`, `404`). +```html +

Code: {{error_code:title}}

+``` + +**`{{url:name}}`**: resolve a resource name to its URL. `:params` in the URL pattern are read from the current scope by name. +```html +All +{{#todos_data}}{{title}}{{/todos_data}} +{{#todo}}{{title}}{{/todo}} +``` + +**`{{asset:filename}}`**: resolve a file in `public/` to a cache-busted URL (content checksum + immutable cache headers). See [Static Files](#static-files). +```html + +``` + +**`{{csrf:token}}`**: emit a CSRF token for URL query strings. Generates a random hash, sets it on an httponly/secure/samesite cookie, outputs the same value inline. +```html +Log out +``` + +**`{{csrf:input}}`**: emit a hidden `` carrying a CSRF token, for `
` use. Same cookie behavior as `{{csrf:token}}`. +```html +{{csrf:input}}
+``` + +--- + +### Assets + +Every non-`.c` file is an asset. Assets are embedded into the binary at compile time and loaded into context at startup under their name, in the module they belong to, as if `context(name, contents)` had been called there. Common types are Mustache templates (`*.mustache.html`), Markdown (`*.md`), and SQL (`*.sql`); the rule is general. + +An asset's name is the filename's basename (the part before the first dot). `get_todos.sql` seeds `get_todos`, `todos.mustache.html` seeds `todos`, `home.md` seeds `home`. Steps read these like any other context value: `mustache("todos")`, `sqlite_query({"todos_db", "get_todos", "todos_data"})`, and `.migrations`/`.seeds` entries (`{"create_todos_table"}`). + +`mustache()`, `mdm()`, and the engine `*_query()` steps read a string from context by key and interpret it as a template or SQL. The step interprets whatever is under the key when it runs. + +`context(name, value)` does the same seeding from a string instead of a file. Useful for content too small to warrant its own file: +```c +context("hello", "

Hello, world!

"); // then mustache("hello") +context("ping", "select 1"); // then sqlite_query({"db", "ping"}) +``` + +An asset is seeded into the module whose folder it sits in. A folder is a module when it contains a matching `.c` file (so `todos/` is a module when `todos/todos.c` exists); folders without one are organizational and pass their files up to the enclosing module. The project root is the `main` module. Walking up from a file's location, it seeds in the nearest module folder: + +``` +. +├── main.c # the "main" module (root) +├── home.mustache.html # → main, todos +├── partials/ +│ └── footer.mustache.html # → main (partials/ has no partials.c), todos +└── todos/ + ├── todos.c # the "todos" module + ├── todos.mustache.html # → todos + └── detail/ + └── todo.mustache.html # → todos (detail/ has no detail.c) +``` + +### Databases + +Each database engine is a module: `#include` its header (e.g. `#include `) to activate it, then register one or more databases with `_database(...)`. Migrations and seeds are forward-only and index-based: they run in array order, each applied once, with new ones appended to the end. Both are tracked in a `mach_meta` table. + +Multi-tenant databases use `{{interpolation}}` in `.connect`. Connections are pooled with LRU eviction. + +**`.name`**: identifier referenced by the first value of `query()` steps. +```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 entries, applied once each in order. Each entry is a context key holding the SQL. +```c +.migrations = {"create_todos_table", "create_comments_table"} +``` + +**`.seeds`**: array of SQL seed entries, applied once each in order. Each entry is a context key holding the SQL. +```c +.seeds = {"seed_todos"} +``` + +Combined: +```c +#include + +sqlite_database( + "blog_db", + "file:{{user_id}}_blog.db?mode=rwc", + {"create_blogs_table", "create_comments_table"}, + {"seed_blogs"} +); +``` + +**Engine include / query / register:** `#include ` + `sqlite_query()` + `sqlite_database()`, and likewise `postgres_*`, `mysql_*`, `redis_*`, `duckdb_*`. + +![Database Multi-Tenancy](./09-database-multi-tenancy.svg) + +### Resource Pipelines + +MACH is resource-based, not route-based. Each `resource(...)` defines a named URL endpoint with HTTP verb pipelines. `{{url:name}}`, `redirect()`, and `reroute()` all take only the resource name; `:params` are read from the current scope by matching key names. Path specificity is automatic: exact matches (`/todos/active`) take priority over parameterized matches (`/todos/:id`) regardless of definition order. + +Clients select a verb via the request method, or by passing `http_method` as a query/form parameter. This lets HTML forms (limited to GET/POST) reach any verb, and gives SSE a connection path: `/todos?http_method=sse`. + +**Resource name *(by order)***: identifier used by `{{url:name}}`, `redirect()`, and `reroute()`. +```c +resource("todos", "/todos", .get = { ... }); +``` + +**URL pattern *(by order)***: URL pattern. Supports `:params`. +```c +resource("todo", "/todos/:id", .get = { ... }); +``` + +**`.all`**: shared steps that run before every verb pipeline on the resource. +```c +resource("todo", "/todos/:id", + .all = { input({"id", m_integer, "must be a number"}) }, + .get = { ... }, + .delete = { ... } +); +``` + +**`.mime`**: default response content type. Values: `m_html`, `m_txt`, `m_sse`, `m_json`, `m_js` (default `m_html`). +```c +resource("feed", "/feed.json", .mime = m_json, .get = { ... }); +``` + +**`.get` `.post` `.put` `.patch` `.delete`**: verb pipelines: ordered arrays of steps that transform a request into a response. +```c +resource("todos", "/todos", + .get = { sqlite_query({"db", "get_todos", "todos_data"}), mustache("todos") }, + .post = { input({"title", m_not_empty}), redirect("todos") } +); +``` + +**`.sse`**: persistent SSE channel. The first value is the channel name (supports `{{interpolation}}`); any remaining steps run on connect. +```c +resource("todos", "/todos", + .sse = {"todos:{{user_id}}", + sqlite_query({"db", "get_todos", "todos_data"}), + sse(.event = "initial", .data = {"{{todos_data}}"}) + } +); +``` + +**`.errors` / `.repairs`**: resource-scoped error and repair pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +resource("todos", "/todos", + .post = { ... }, + .errors = {{m_bad_request, {mustache("form")}}} +); +``` + +Combined: +```c +resource("todo", "/todos/:id", + .all = { input({"id", m_positive, "must be a number"}) }, + .get = { sqlite_query({"todos_db", "get_todo", "todo", .must_exist = true}), + mustache("todo") }, + .patch = { input({"title", m_not_empty, "required"}), + sqlite_query({"todos_db", "update_todo"}), + redirect("todo") }, + .delete = { sqlite_query({"todos_db", "delete_todo"}), + redirect("todos") }, + .sse = {"todo:{{id}}", sse(.event = "ready") }, + .errors = {{m_not_found, {mustache("404")}}} +); +``` + +![Request Pipeline Flow](./02-request-pipeline-flow.svg) + +### Pipeline Steps + +Steps are the units of work in a pipeline. Each receives the current context, acts on it, passes control to the next. All steps accept `.if_context`/`.unless_context` for [conditional execution](#conditionals), and `.table_key` for concurrent fan-out across rows of a context table (see [Iteration](#iteration)). + +* [input](#input) +* [query](#query) +* [join](#join) +* [fetch](#fetch) +* [exec and worker](#exec-and-worker) +* [emit](#emit) +* [run](#run) +* [sse](#sse) +* [render](#render) +* [headers and cookies](#headers-and-cookies) +* [redirect and reroute](#redirect-and-reroute) +* [nest](#nest) + +#### input + +Checks request parameters (query string, form body, URL params) against regex patterns. On success, each value is promoted from `input:name` to app scope. On failure, errors land in `error:name` and a `400 Bad Request` triggers the nearest [error/repair pipeline](#error-and-repair-pipelines). All validations in one call complete before the error fires, so all errors are available together for form re-rendering. + +Built-in regex macros are defined in `mach.h`; define your own the same way: `#define m_zipcode "^\\d{5}$"`. + +**`.param_key` *(by order)***: name of the parameter to validate. +```c +input({"title", "^\\S+$", "required"}) +``` + +**`.matches` *(by order)***: regex pattern, or a built-in validator macro. +```c +input({"email", m_email, "bad email"}) +``` + +**`.message` *(by order)***: human-readable error shown via `{{error_message:name}}`. +```c +input({"age", m_integer, "must be a number"}) +``` + +**`.optional`**: skip validation when the parameter is absent. +```c +input({"filter", "^(active|done)$", .optional = true}) +``` + +**`.fallback`**: default value injected when the parameter is absent. +```c +input({"page", m_integer, .fallback = "1"}) +``` + +Combined: +```c +input( + {"email", m_email, "must be a valid email"}, + {"title", m_not_empty, "cannot be empty"}, + {"page", m_integer, "must be a number", .fallback = "1"}, + {"filter", "^(active|done)$", "must be 'active' or 'done'", .optional = true}, + {"username", m_username, "must be alphanumeric"} +) +``` + +For checks beyond regex (uniqueness, cross-field rules, lookups), pair `input()` with a query and `exec()`: +```c +input({"username", m_username, "must be alphanumeric"}), +sqlite_query({"users_db", "find_username", "existing"}), +exec(^(){ + auto rows = get("existing"); + if (rows && table_count(rows) > 0) + error_set("username", (error){m_bad_request, "already taken"}); +}) +``` + +**Built-in validators:** +- Strings: `m_not_empty`, `m_alpha`, `m_alphanumeric`, `m_slug`, `m_no_html` +- Numbers: `m_integer`, `m_positive`, `m_float`, `m_percentage` +- Identity: `m_email`, `m_uuid`, `m_username` +- Dates & times: `m_date`, `m_time`, `m_datetime` +- Web: `m_url`, `m_ipv4`, `m_hex_color` +- Codes: `m_zipcode_us`, `m_phone_e164`, `m_cron` +- Security: `m_token`, `m_base64` +- Boolean: `m_boolean`, `m_yes_no`, `m_on_off` + +#### query + +Each engine provides its own query step: `sqlite_query()`, `postgres_query()`, `mysql_query()`, `redis_query()`, `duckdb_query()`. All share the same `query_config` shape. By order: first value is the database `.name`, second is the context key holding the SQL, third is the `.set_key` for the result table (even single-row results are tables). Multiple items in one step run **concurrently**. Queries use prepared statements; interpolated `{{values}}` are bound, not spliced. For transactions, put `BEGIN`/`COMMIT`/`ROLLBACK` in the SQL. + +**`.db` *(by order)***: database name, matching the name a `_database(...)` was registered with. +```c +sqlite_query({"todos_db", "get_todos", "todos_data"}) +``` + +**`.query` *(by order)***: context key holding the SQL to run. +```c +sqlite_query({"todos_db", "get_todos", "todos_data"}) +``` + +**`.set_key` *(by order)***: context key for the result table. Optional; omit when the result isn't needed (e.g. an insert without `RETURNING`). +```c +sqlite_query({"todos_db", "create_todo"}) // no result captured +sqlite_query({"todos_db", "get_todos", "todos_data"}) // result under "todos_data" +``` + +**`.must_exist`**: when true, raise `404 Not Found` if the query affects/returns zero rows. Default false. +```c +sqlite_query({"todos_db", "get_todo", "todo", .must_exist = true}) +``` + +**`.if_context` / `.unless_context`** *(per item)*: conditionally include or skip individual queries while running the others concurrently. +```c +sqlite_query( + {"db", "get_todos", "todos_data"}, + {"db", "get_urgent", "urgent", .if_context = "show_urgent"} +) +``` + +Combined: +```c +sqlite_query( + {"todos_db", "get_todos", "todos_data"}, + {"todos_db", "get_todo", "todo", .must_exist = true}, + {"todos_db", "get_urgent", "urgent", .if_context = "show_urgent"} +) +``` + +#### join + +Nests records from one context table into each matching record of another, like a SQL JOIN in memory. Useful when records come from separate databases or queries. After the step, each outer record gains a new field holding its matched inner records. + +**`.parent_key`**: outer table whose records receive nested children. +```c +.parent_key = "projects" +``` + +**`.field_key`**: field on the outer table to match against. +```c +.field_key = "id" +``` + +**`.child_key`**: inner table whose records get nested. +```c +.child_key = "todos" +``` + +**`.child_field_key`**: field on the inner table that points at the outer. +```c +.child_field_key = "project_id" +``` + +**`.join_field_key`**: new field on outer records holding the matched inner records. (defaults to `.child_key`) +```c +.join_field_key = "todos" +``` + +Combined: +```c +join("projects", "id", "todos", "project_id") +``` + +**Full context example.** Concurrent query → `join()` → `mustache()`: fetch parent and children from separate queries, render as one nested structure. Blog + comments, single database: + +**`blog.mustache.html`** +```html +
+ {{#blog}} +

{{title}}

+
{{content}}
+

Comments

+
    {{#comments}}
  • {{body}}
  • {{/comments}}
+ {{/blog}} +
+``` + +```c +resource("blog", "/blogs/:id", + .get = { + input({"id", m_integer}), + + // Fetch both concurrently: one query() call, two items + sqlite_query( + {"blog_db", "get_blog", "blog"}, + {"blog_db", "get_comments", "comments"} + ), + + // Nest each comment into its matching blog record + join("blog", "id", "comments", "blog_id"), + + // Enter {{#blog}} first; after join(), comments lives INSIDE each blog record + mustache("blog") + } +); +``` + +Context shape 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 parses into tables and records (nested tables for nested JSON); plain-text responses are stored as strings. Like `query()`, multiple items in one step run **concurrently**. + +**`.url` *(by order)***: request URL; supports `{{interpolation}}`. +```c +fetch({"https://api.weather.dev/forecast?city={{city}}", "w"}) +``` + +**`.set_key`**: context key for the response. +```c +fetch({"https://api.weather.dev/now", "weather"}) +``` + +**`.method`**: HTTP method. Defaults to `m_get`. Values: `m_get`, `m_post`, `m_put`, `m_patch`, `m_delete`, `m_sse_method`. +```c +fetch({"https://api.dev/charge", "r", m_post}) +``` + +**`.headers`**: array of name/value pairs. +```c +fetch({"https://api.dev/me", "r", .headers = {{"Authorization", "Bearer {{token}}"}}}) +``` + +**`.json`**: context key serialized as the JSON request body. +```c +fetch({"https://api.dev/charge", "receipt", m_post, "order"}) +``` + +**`.text`**: context key sent as the plain-text request body. +```c +fetch({"https://api.dev/log", "r", m_post, .text = "raw_body"}) +``` + +**`.if_context` / `.unless_context`** *(per item)*: conditionally include or skip individual requests while running others concurrently. +```c +fetch( + {"https://api.weather.dev/now", "weather"}, + {"https://api.quotes.dev/random", "quote", .if_context = "show_quote"} +) +``` + +Combined, single request: +```c +fetch({"https://api.payments.dev/charge", + "receipt", + m_post, + "order", + { + {"Authorization", "Bearer {{api_key}}"}, + {"Idempotency-Key", "{{order_id}}"} + } +}) +``` + +Combined, concurrent fan-out: +```c +fetch( + {"https://api.weather.dev/now?city={{city}}", "weather"}, + {"https://api.news.dev/headlines?topic={{topic}}", "news"}, + {"https://api.quotes.dev/random", "quote"} +) +``` + +#### exec and worker + +`exec()` calls a C function or block with access to context via the [Imperative API](#imperative-api). It is where business logic and data shaping lives: enriching query results, aggregating, transforming data between steps, setting flags for [conditional](#conditionals) downstream steps. Call `error_set()` to trigger an error/repair pipeline. + +`worker()` takes the same configuration as `exec()` but is for blocking or CPU-bound work: external C libraries, blocking I/O, heavy computation. The work is dispatched to the shared thread pool, releasing the reactor; the pipeline resumes on the original reactor when the call returns. Use `worker()` when the body would stall a request reactor. + +**Block *(by order)***: 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 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")); +}) +``` + +**`.call`**: reference to a named C function, for logic reuse across pipelines. +```c +exec(.call = assign_opponents) +``` + +Inside blocks and `.call` 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 `subscribe()` pipelines, with no direct dependency on the emitter. See [Event Pipelines](#event-pipelines). + +**Event name *(by order)***: name of the event to publish. +```c +emit("todo_created") +``` + +#### run + +Adds a named job to the task database; the calling pipeline continues immediately. Task reactors pick up queued jobs and execute their pipelines. The task must be defined elsewhere with `task(name, { ... })`. See [Task Pipelines](#task-pipelines). + +**Task name *(by order)***: name of a defined task. +```c +run("record_daily_stats") +``` + +#### sse + +Pushes a Server-Sent Event. With `.channel`, the event broadcasts to all clients on that channel. Without it, the event returns to the requesting client. See [Resource Pipelines](#resource-pipelines). + +**`.channel` *(by order)***: channel to broadcast on; supports `{{interpolation}}`. +```c +sse("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("todos:{{user_id}}", + .event = "todo_updated", + .data = {"id: {{todo_id}}", "title: {{title}}"}, + .comment = "broadcast at {{timestamp}}" +) +``` + +#### render + +Outputs a template using the current context. `mustache()` renders Mustache; `mdm()` renders Markdown-with-Mustache; `json()` renders JSON. All take the same `render_config`. + +**`.context_key` *(by order)***: key of the context value to render. The value is the template string itself. +```c +mustache("todos") +``` + +**`.status`**: HTTP response status (default `m_ok`). Values: `m_ok` (200), `m_created` (201), `m_redirect` (302), `m_bad_request` (400), `m_not_authorized` (401), `m_not_found` (404), `m_error` (500). +```c +mustache("not_found", .status = m_not_found) +``` + +**`.mime`**: override the response content type. Values: `m_html`, `m_txt`, `m_sse`, `m_json`, `m_js`. +```c +mustache("plain", .mime = m_txt) +``` + +JSON: +```c +json("todos") +``` + +Markdown-with-Mustache: +```c +context("welcome", "# Welcome, {{user_name}}"); +mdm("welcome") +``` + +#### headers and cookies + +Set HTTP response headers and cookies declaratively. Both accept an array of name/value pairs; values support `{{interpolation}}`. + +**Pairs *(by order)***: 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 and 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 only the target resource name. `:params` in the target's URL pattern are read from the current context by matching key names. + +**Resource name *(by order)***: target resource name. Required `:params` are read from context by name. +```c +redirect("todos") // 302 to /todos +redirect("todo") // 302 to /todos/{{id}}, id read from context +redirect("org_todo") // 302 to /orgs/{{org}}/todos/{{id}}, org and id read from context +reroute("todo") // run that pipeline in-process, id read from context +``` + +#### nest + +Groups multiple steps into a single composite step. Useful when applying one `.if_context`/`.unless_context` to several steps without repeating it. + +**`.steps` *(by order)***: array of steps that run as a unit. +```c +nest({sqlite_query({...}), emit("urgent_todo"), mustache("urgent")}) +``` + +**`.if_context` / `.unless_context`**: condition applied to the whole group. +```c +nest({sqlite_query({...}), emit("urgent_todo"), mustache("urgent")}, + .if_context = "is_urgent") +``` + +--- + +### Imperative API + +Functions called from `exec()`/`worker()` 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) +* [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 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 +auto 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 +auto buf = allocate(256); +``` + +**`defer_free(ptr)`**: schedules `free()` for a pointer returned by an external library. Runs when the arena is released. +```c +auto out = third_party_alloc(256); +defer_free(out); +``` + +Combined: +```c +worker(^(){ + auto url = allocate(512); + build_signed_url(url, 512, get("path")); + set("signed_url", url); + + auto raw = third_party_render_md(get("markdown")); + defer_free(raw); + set("html", raw); +}) +``` + +#### errors + +Raise field-scoped errors from `exec()` to trigger error/repair pipelines. 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){ m_bad_request, "token has expired" }); +``` + +**`error_get(name)`**: returns the `error` previously set on `name`. +```c +auto e = error_get("token"); +``` + +**`error_has(name)`**: returns true when `name` has an error. +```c +if (error_has("token")) { ... } +``` + +Combined: +```c +exec(^(){ + auto token = get("token"); + if (!token || strlen(token) < 16) { + error_set("token", (error){ + m_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 +auto t = table_new(); +``` + +**`table_count(t)`**: number of records in `t`. +```c +auto n = table_count(get("todos")); +``` + +**`table_get(t, i)`**: record at index `i`, or `nullptr` if out of range. +```c +auto 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(^(){ + auto source = get("raw_users"); + auto active = table_new(); + for (int i = 0; i < table_count(source); i++) { + auto u = table_get(source, i); + auto 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; see [Everything is a String](#everything-is-a-string). + +**`record_new()`**: returns an empty record in the pipeline arena. +```c +auto r = record_new(); +``` + +**`record_get(r, name)`**: string value of `name`, or `nullptr` if absent. +```c +auto 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(^(){ + auto todos = get("todos"); + for (int i = 0; i < table_count(todos); i++) { + auto t = table_get(todos, i); + auto 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`, naming a context variable. They work for any context value: validated inputs, query results, framework flags like `is_htmx`, or flags set from `exec()`. + +**`.if_context`**: context key. Step runs only when the value is present. +```c +mustache("fragment", .if_context = "is_htmx") +``` + +**`.unless_context`**: context key. Step runs only when the value is absent. +```c +mustache("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), +mustache("urgent_confirmation", .if_context = "is_urgent"), +mustache("standard_confirmation", .unless_context = "is_urgent") +``` + +### Iteration + +`.table_key` names a context table to iterate over. The step runs once per row with that row's fields in scope; all rows run **concurrently**, like multiple items in `query()` or `fetch()`. With a `.set_key`, results are collected into a table aligned with the input, one entry per row. + +**`.table_key`**: name of a context table to iterate over. +```c +// One request per row in `users`, all concurrent. +// Responses collected into `profiles`, aligned with `users`. +fetch({"https://api.users.dev/{{id}}", "profiles", .table_key = "users"}) +``` + +Use `.table_key` for per-row work that doesn't fit a single query or request (e.g. external APIs without bulk endpoints). + +### Error and Repair Pipelines + +When a step fails, execution halts and MACH looks for a handler matching the error code. It checks the resource's own `.errors`/`.repairs` first, then the `error()`/`repair()` handlers in that resource's module, and uses the first match. A resource handler overrides the module's for the same code. + +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. Repairs resolve first; if no matching repair is found, resolution falls through to errors. Unhandled errors fall through to MACH's internal handler, which looks for a context template named after the error code, otherwise 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 `input()` failures and `error_set()` calls: `{{error:name}}`, `{{error_code:name}}`, `{{error_message:name}}`. The raw input value remains in `input:name` for re-rendering forms. + +**Resource-scoped (`.errors` / `.repairs` fields):** +```c +resource("todos", "/todos", + .post = { ... }, + .errors = { + {m_not_found, {mustache("404")}}, + {m_bad_request, {mustache("form")}} + }, + .repairs = { + {m_not_authorized, {exec(.call = refresh_session_token)}} + } +); +``` + +**Module-scoped (`error()` / `repair()` calls):** +```c +module(todos){ + error(m_error, {mustache("5xx")}); + error(m_not_found, {mustache("404")}); + repair(m_not_authorized, {exec(.call = refresh_session_token)}); + // ... resources ... +} +``` + +**Built-in error codes:** `m_bad_request` (400), `m_not_authorized` (401), `m_not_found` (404), `m_error` (500). Any integer works; the `m_*` 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 a `subscribe(...)` call; the publisher does not change. Activate with `#include ` in any module that publishes or subscribes. + +Events are durable. When a publisher is declared, MACH creates a `mach_events` database to track delivery. If the process crashes, undelivered events replay on the next boot. + +**`publish(event, .with = {...})`**: declares an outbound event contract. First value is the event name; `.with` lists context keys to pass along. +```c +publish("todo_created", .with = {"user_id", "title"}); +``` + +**`subscribe(event, { steps })`**: registers a subscriber pipeline keyed by event name. +```c +subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) +}); +``` + +**`emit(event)`**: a pipeline step that fires the event (see [emit](#emit)). +```c +emit("todo_created") +``` + +**`.errors` / `.repairs`** *(per subscriber)*: each `subscribe(...)` can declare its own handlers, resolved the same way as resource pipelines (the subscriber's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +subscribe("todo_created", { + sqlite_query({"activity_db", "insert_activity"}) +}, .errors = {{m_error, {exec(.call = log_subscriber_failure)}}}); +``` + +Combined: +```c +// todos/todos.c: publisher +module(todos){ + publish("todo_created", .with = {"user_id", "title"}); + publish("todo_deleted", .with = {"user_id", "todo_id"}); + + resource("todos", "/todos", + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "insert_todo"}), + emit("todo_created"), + redirect("todos") + } + ); +} + +// activity/activity.c: subscriber +module(activity){ + subscribe("todo_created", { + sqlite_query({"activity_db", "insert_created_activity"}) + }); + subscribe("todo_deleted", { + sqlite_query({"activity_db", "insert_deleted_activity"}) + }); +} +``` + +![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 module or root scope. Triggered on demand with `run("name")` or on a schedule via `.cron`. Tasks can enqueue more tasks. + +Registered with `task(name, { pipeline }, ...)`: name, pipeline body, optional `.cron`/`.accepts`. Registration and enqueuing are separate: `task(...)` defines, `run("name")` ([enqueue step](#run)) enqueues. + +Tasks are durable: MACH creates a `mach_tasks` database and checkpoints context after each step. A crash mid-task resumes at the step where it stopped on the next boot. + +**Task name *(by order)***: task identifier, enqueued via `run("name")`. +```c +task("recount", { + sqlite_query({"db", "recount_todos"}) +}); +``` + +**Pipeline *(by order)***: the task's pipeline body, a brace block. +```c +task("name", { sqlite_query({...}), emit("done"), run("followup") }); +``` + +**`.accepts`**: context keys to pull from the caller into the task. +```c +task("recount_todos", { + sqlite_query({"db", "recount"}) +}, .accepts = {"user_id"}); +``` + +**`.cron`**: standard cron schedule for recurring tasks (no caller required). +```c +task("daily_digest", { + sqlite_query({"db", "digest"}) +}, .cron = "0 8 * * *"); +``` + +**`.errors` / `.repairs`** *(per task)*: each task can declare its own handlers, resolved the same way as resource pipelines (the task's own handlers, then its module's). See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +task("send_invoice", { + fetch({"https://api.billing.dev/invoices/{{invoice_id}}", "inv"}) +}, .repairs = {{m_not_authorized, {exec(.call = refresh_billing_token)}}}); +``` + +Combined: +```c +// on-demand: enqueued via run("recount_todos") +task("recount_todos", { + sqlite_query({"todos_db", "recount"}) +}, .accepts = {"user_id"}); + +// recurring: runs on schedule, no caller +task("daily_digest", { + sqlite_query({"todos_db", "digest"}), + emit("digest_ready") +}, .cron = "0 8 * * *"); +``` + +### Modules and Composition + +The root `main.c` defines the app with the `mach()` macro. A module is declared with `module(name)` in a `name/name.c` file. A module owns its own resources, databases, migrations, tasks, event contracts, and middleware. Compose by `#include`ing a module's `.c` file. + +A module owns the files in its folder, which are seeded into its context at startup. See [Assets](#assets) and [Context](#context). + +**`module(name)`**: declares a module. +```c +// todos/todos.c +module(todos){ + // resources, databases, tasks, subscribers ... +} +``` + +**`middleware(steps)`**: registers shared steps that run on every request to a resource in the same module. Cross-cutting setup like session loading or tenant resolution lives here. +```c +mach(){ middleware(session()); /* modules, resources, ... */ } +``` + +**`error(...)` / `repair(...)`**: module-scoped error and repair handlers (see [Error and Repair Pipelines](#error-and-repair-pipelines)). They cover resources in the same module; a resource's own `.errors`/`.repairs` override them for the same code. + +**Pipeline composition.** A request runs the resource's `.all` steps first, then the module's `middleware()`, then the verb pipeline. + +```c +// main.c: root config +#include +#include +#include "todos/todos.c" + +mach(){ + middleware(session()); + + resource("home", "/", .get = {mustache("home")}); +} + +// todos/todos.c: session loads, resources require login +#include +#include +#include + +module(todos){ + middleware(logged_in()); + middleware(session()); + + resource("todos", "/todos", + .get = { sqlite_query({"todos_db", "get_todos", "todos_data"}), mustache("todos") }, + .post = { input({"title", m_not_empty}), sqlite_query({"todos_db", "create_todo"}), redirect("todos") } + ); + + resource("todo", "/todos/:id", + .all = { + input({"id", m_positive}) + }, + .delete = { sqlite_query({"todos_db", "delete_todo", .must_exist = true}), redirect("todos") } + ); +} +``` + +For `GET /todos/5` the executed order is: `input({"id", ...})` (resource `.all`), `logged_in()`, `session()` (module `middleware`), then the verb pipeline `sqlite_query({"get_todo", ..., .must_exist = true})`, `mustache("todo")`. + +**Complete module file.** A module registers the same kinds of things the root does. A `blogs/blogs.c`: + +```c +#include +#include + +module(blogs){ + sqlite_database( + "blog_db", + "file:blogs.db?mode=rwc", + {"create_blogs_table", "create_comments_table"} + ); + + resource("blog", "/blogs/:id", + .get = {...} + ); +} +``` + +Bring it into scope by `#include`ing its `.c` file from `main.c`: +```c +// main.c +#include +#include "blogs/blogs.c" + +mach(){} +``` + +A typical project layout: +``` +├── todos/ # todos module (folder + matching .c) +│ ├── todos.c # module(todos){ ... } +│ ├── todos.mustache.html # → todos +│ ├── create_todos_table.sql # → todos +│ └── get_todos.sql # → todos +├── activity/ # activity module +│ └── activity.c +├── home.mustache.html # → main (also the shared layout) +├── public/ # static files, served directly +│ └── favicon.png +└── main.c # mach() { ... }, composes the rest +``` + +![App Composition Tree](./05-app-composition-tree.svg) +![Middleware Scoping](./06-middleware-scoping.svg) + +--- + +### Module Reference + +Bundled modules. Activate each by `#include`ing its header. + +* [htmx](#htmx) +* [datastar](#datastar) +* [tailwind](#tailwind) +* [session_auth](#session_auth) +* [Database engines](#database-engines) + +#### htmx + +Activate with `#include `. Serves the htmx runtime as the `{{>htmx}}` partial, and sets the `is_htmx` context flag on requests carrying the `HX-Request` header. Pair the flag with `.if_context`/`.unless_context` to return a fragment to htmx and a full page to a direct visit, or use `hx-boost` to upgrade ordinary links and forms into AJAX swaps. + +```c +#include +#include + +mach(){ + resource("todos", "/todos", + .get = { + sqlite_query({"todos_db", "get_todos", "todos_data"}), + mustache("todos_fragment", .if_context = "is_htmx"), + mustache("todos_page", .unless_context = "is_htmx") + } + ); +} +``` + +Include the runtime once in the page ``: +```html +{{>htmx}} +... +``` + +#### datastar + +Activate with `#include `. Serves the Datastar runtime as the `{{>datastar}}` partial and provides `datastar_sse()` for pushing reactive fragment and signal patches over an SSE channel. A page opens an SSE connection (a resource `.sse` channel); pipelines push patches to that channel, and Datastar applies them in the DOM. + +`datastar_sse()` renders a template and patches it into the page by CSS selector. The first value is the channel (supports `{{interpolation}}`). + +**`.channel` *(by order)***: channel to push to. +```c +datastar_sse("todos:{{user_id}}", .target = "#todo-list", .mode = mode_append, .elements = {"todo_row"}) +``` + +**`.target`**: CSS selector for the element to patch; supports `{{interpolation}}`. +```c +.target = "#todo-{{id}}" +``` + +**`.mode`**: how the rendered fragment is applied to the target (a `datastar_mode`). +```c +.mode = mode_replace +``` + +**`.elements`**: a `render_config` (a template asset name) producing the fragment to patch in. Not required for `mode_remove`. +```c +.elements = {"todo_row"} +``` + +**`.signals`**: context key holding signal state to merge into the client store. +```c +.signals = "ui_state" +``` + +**`.js`**: JavaScript to execute on the client. +```c +.js = "window.scrollTo(0, document.body.scrollHeight)" +``` + +**Patch modes (`datastar_mode`):** `mode_outer`, `mode_inner`, `mode_replace`, `mode_prepend`, `mode_append`, `mode_before`, `mode_after`, `mode_remove`. + +Worked example: a POST inserts a row, returns it with `RETURNING`, appends it to every connected client's list. + +```c +resource("todos", "/todos", + // Each browser opens this channel and listens for patches. + .sse = {"todos:{{user_id}}"}, + + .post = { + input({"title", m_not_empty}), + // RETURNING gives the new row back; capture it under "todo". + sqlite_query({"todos_db", "insert_todo", "todo", .must_exist = true}), + // Patch the new row into the list for everyone on the channel. + datastar_sse("todos:{{user_id}}", + .target = "#todo-list", + .mode = mode_append, + .elements = {"todo_row"} + ) + } +); +``` + +Removing an element needs only a selector: +```c +datastar_sse("todos:{{user_id}}", .target = "#todo-{{id}}", .mode = mode_remove) +``` + +Datastar sets a context flag on requests it originates, usable with `.if_context`. + +Include the runtime once in the page ``: +```html +{{>datastar}} +``` + +![SSE + Datastar Flow](./08-sse-datastar-flow.svg) + +#### tailwind + +Activate with `#include `. Compiles Tailwind utility classes used across the project's templates and serves the stylesheet as the `{{>tailwind}}` partial. Use Tailwind classes directly in templates; no build step or config file required. + +```html +{{>tailwind}} + +

Vote for which is roundest

+ +``` + +#### session_auth + +Activate with `#include `. Cookie-based authentication as pipeline steps. `session()` loads the current `user` record into context from the session cookie; run it as `middleware()` in each module whose pipelines need to know who is signed in. `logged_in()` guards a resource, redirecting anonymous visitors to the login page. `login()`, `logout()`, and `signup()` perform the corresponding actions. The login page template is the asset named `login`. + +**`session()`**: loads the current user into context from the session cookie. Use as middleware. +```c +middleware(session()); +``` + +**`logged_in()`**: requires an authenticated session; redirects to login otherwise. Use in a resource `.all`. +```c +resource("todos", "/todos", .all = {logged_in()}, .get = { ... }); +``` + +**`login()` / `logout()` / `signup()`**: authentication actions for the corresponding verb pipelines. +```c +resource("login", "/login", + .get = { mustache("login") }, + .post = { login() } +); +resource("logout", "/logout", .post = { logout() }); +resource("signup", "/signup", + .get = { mustache("signup") }, + .post = { signup() } +); +``` + +Combined: load the session in the module whose resources it gates, then read user fields in that module's templates. +```c +// todos/todos.c +#include +#include + +module(todos){ + middleware(logged_in()); + middleware(session()); + + resource("todos", "/todos", .get = { mustache("todos") }); +} + +// main.c: login/logout live at the root +#include +#include +#include "todos/todos.c" + +mach(){ + resource("login", "/login", .get = {mustache("login")}, .post = {login()}); + resource("logout", "/logout", .post = {logout()}); +} +``` +```html + +{{#user}}Hi, {{short_name}}{{/user}} +``` + +#### Database engines + +Each engine is its own module: `#include` its header, then use `_database(...)` to register and `_query({...})` as a pipeline step. They share `database_config` and `query_config` from [Databases](#databases) and [query](#query); only `.connect` is engine-specific. + +```c +#include // sqlite_database("...", "file:app.db?mode=rwc", ...); sqlite_query({...}); +#include // postgres_database("...", "postgres://...", ...); postgres_query({...}); +#include // mysql_database("...", "mysql://...", ...); mysql_query({...}); +#include // redis_database("...", "redis://...", ...); redis_query({...}); +#include // duckdb_database("...", "duckdb:analytics.db", ...); duckdb_query({...}); +``` + +### Static Files + +Files in `public/` are served directly. Reference them in templates with `{{asset:filename}}`, which resolves to a content-checksummed, cache-busted URL with immutable cache headers. Updates invalidate caches automatically; unchanged files cache forever. + +``` +public/ +├── favicon.png +├── styles.css +└── logo.svg +``` + +```html + + +Logo +``` + +This differs from assets like SQL and HTML templates, which are embedded from files anywhere in the project and seeded into context for steps to read by key (see [Assets](#assets) and [Context](#context)). `public/` holds opaque files served to the browser. + +### External Dependencies + +Drop third-party C libraries into `/vendor`; MACH compiles and links them with the app. Call into them from `exec()`/`worker()` steps. Memory returned by a library that must be freed manually is registered with `defer_free()` so it is reclaimed when the request completes (see [memory](#memory)). + +``` +vendor/ +└── cmark/ + ├── cmark.c + └── cmark.h +``` + +```c +#include +#include "vendor/cmark/cmark.h" + +void render_markdown(){ + worker(^(){ + auto md = get("markdown"); + auto html = cmark_markdown_to_html(md, strlen(md), 0); + defer_free(html); // library-owned pointer + set("html_content", html); + }); +} +``` + +For dependencies that aren't plain source (system packages, build tooling), provide a custom `Dockerfile`. MACH builds from it instead of the default image. + +--- + +## Architecture + +* [Data-Oriented Pipelines](#data-oriented-pipelines) +* [Multi-Reactor Architecture](#multi-reactor-architecture) +* [Safe by Default](#safe-by-default) + +### Data-Oriented Pipelines + +`mach()` runs once at boot, alongside each module's constructor. Registration calls (`resource()`, `sqlite_database()`, `task()`, `middleware()`, `publish()`, etc.) are processed into an execution graph with precompiled pipelines, queries, and templates. Each incoming request 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 is set in `compose.yml`. + +- **Request reactors** handle HTTP traffic; each gets a dedicated CPU core and event loop. +- **Task reactors** handle background work; each gets a 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. + +A `worker()` step dispatches work to the shared pool, releasing the reactor; the pipeline resumes on the original reactor when the call completes. `exec()` runs inline on the reactor for short, non-blocking logic. `run()` adds jobs to the task database, picked up by task reactors. Tasks can call `run()` themselves. + +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` (use `allocate()` and `defer_free()` from the [Imperative API](#memory) for raw buffers), avoiding 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 exceeding their memory limit (default 5MB, configurable in `compose.yml`) abort with a 500, mitigating OOM denial-of-service. + +#### SQL Injection Prevention + +Interpolations like `{{user_id}}` inside a query's SQL (whether the SQL comes from a `.sql` file or a `context()`-registered string) are bound as parameters in prepared statements, preventing SQL injection at the framework level. + +#### XSS Prevention + +The `mustache()` and `mdm()` steps auto-escape context values, so malicious input is rendered as text. Raw HTML requires explicit opt-in via Mustache's standard unescape syntax: `{{{field}}}` or `{{&field}}`. + +#### CSRF Prevention + +State-changing requests are verified against a per-session CSRF token. Emit the token with `{{csrf:input}}` (hidden form field) or `{{csrf:token}}` (value for query strings); MACH sets it on an httponly, secure, samesite cookie and rejects requests whose token does not match. See [Templates](#templates). + +--- + +## Tooling + +* [Development Environment](#development-environment) +* [Introspection](#introspection) +* [Testing](#testing) +* [Debugging](#debugging) +* [Deployment](#deployment) +* [Observability](#observability) +* [Project Management](#project-management) + +### 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, module boundaries), so it reasons about the application's actual execution graph rather than the source text alone. + +### 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 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 +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 a minimal 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 +Ships with integrated 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).