commit fa78bbde14e811ac1a7d702cb88b2c40473f12e2 Author: nightshade Date: Thu Jul 24 12:46:01 2025 -0500 MaCH repo diff --git a/00_hello_text/main.c b/00_hello_text/main.c new file mode 100644 index 0000000..67ed42e --- /dev/null +++ b/00_hello_text/main.c @@ -0,0 +1,9 @@ +#include + +void mach(){ + resource("home", "/", .mime = m_txt, + .get = { + mustache(.body = "hello") + } + ); +} diff --git a/01-multi-reactor-architecture.svg b/01-multi-reactor-architecture.svg new file mode 100644 index 0000000..8c145d1 --- /dev/null +++ b/01-multi-reactor-architecture.svg @@ -0,0 +1,155 @@ + + + + + + + + + + + + + + + + + + Multi-Reactor Architecture + + + request/task/cpu ratio configurable in compose.yml + + + + HTTP Clients + + + + + + + + + REQUEST REACTORS + + + + Core 0 + event loop + + pipeline + + + + Core 1 + event loop + + pipeline + + + + + + + + Core N + event loop + + pipeline + + + + TASK REACTORS + + + + Core + event loop + + cron / jobs + + + + Core + event loop + + cron / jobs + + + + + + + + Core + event loop + + cron / jobs + + + + mach_tasks + database + + + + + + + + SHARED THREAD POOL + remaining cores + + + work queue + + + + + + + + + + + + + + + + + + + + + Thread 1 + + + ... + + + Thread N + + + on complete, resumes pipeline on reactor + + + + + invoke() + + + + invoke() + + + + + task() + + + + task() + + diff --git a/01_hello_world_text/main.c b/01_hello_world_text/main.c new file mode 100644 index 0000000..84b882b --- /dev/null +++ b/01_hello_world_text/main.c @@ -0,0 +1,10 @@ +#include + +void mach(){ + resource("home", "/", .mime = m_txt, + .get = { + input({"name", .fallback = "world"}), + mustache(.body = "Hello {{name}}") + } + ); +} diff --git a/02-request-pipeline-flow.svg b/02-request-pipeline-flow.svg new file mode 100644 index 0000000..0303b6f --- /dev/null +++ b/02-request-pipeline-flow.svg @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + POST /todos + + + .before + + + + session() + + + + + + + .post pipeline + + + + param() + validate title + + + + + + + + db() + INSERT todo + + + + + + + + emit() + todo_created + + + + + + + + redirect() + 302 → /todos + + + + PIPELINE CONTEXT + + + + user_id + ← session + + + title + ← param + + + todo + ← db .set + + + base_layout + ← .context + diff --git a/02_hello_world_html/main.c b/02_hello_world_html/main.c new file mode 100644 index 0000000..179ac1b --- /dev/null +++ b/02_hello_world_html/main.c @@ -0,0 +1,17 @@ +#include + +void mach(){ + resource("home", "/", + .get = { + input({"name", .fallback = "world"}), + mustache(.body = + "" + "" + "" + "

Hello {{name}}

" + "" + "" + ) + } + ); +} diff --git a/03-event-pub-sub.svg b/03-event-pub-sub.svg new file mode 100644 index 0000000..1bc924b --- /dev/null +++ b/03-event-pub-sub.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + todos module + .post pipeline: + param() → db() + → emit("todo_created") + → redirect("/todos") + + + .publishes + + todo_created → user_id, title + + + + Event Bus + + + + + + + + + activity module + .events: + "todo_created" → db(log.sql) + + + + + + + + + notifications module + .events: + "todo_created" → call(notify) + + + + + + + Modules are decoupled — publishers don't know about subscribers + diff --git a/03_hello_world_html_db/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..4e37173 --- /dev/null +++ b/03_hello_world_html_db/main.c @@ -0,0 +1,20 @@ +#include +#include + +void mach(){ + sqlite_config(); + + 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..dd2711e --- /dev/null +++ b/04_todo/main.c @@ -0,0 +1,60 @@ +#include +#include +#include + +void mach(){ + sqlite_config(); + session_auth_config(); + + sqlite_database( + .name ="todos_db", + .connect = "file:{{user_id}}_todo.db?mode=rwc", + .migrations = {"create_todos_table"} + ); + + error(m_error, {mustache("5xx")}); + error(m_not_found, {mustache("404")}); + + middleware(session()); + + 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..4e54991 --- /dev/null +++ b/05_todo_sse_datastar/main.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include + +void mach(){ + sqlite_config(); + datastar_config(); + session_auth_config(); + + sqlite_database( + .name = "todos_db", + .connect = "file:todo.db?mode=rwc", + .migrations = {"create_todos_table"} + ); + + error(m_error, {mustache("5xx")}); + error(m_not_found, {mustache("404")}); + + middleware(session()); + + 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..cd2aee4 --- /dev/null +++ b/06_todo_events/activity/activity.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +void activity_config(){ + name("activity"); + + sqlite_config(); + pubsub_config(); + session_auth_config(); + + 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", + .all = {logged_in()}, + .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..678bf96 --- /dev/null +++ b/06_todo_events/main.c @@ -0,0 +1,19 @@ +#include +#include +#include "todos/todos.c" +#include "activity/activity.c" + +void mach(){ + todos_config(); + activity_config(); + session_auth_config(); + + error(m_error, {mustache("5xx")}); + error(m_not_found, {mustache("404")}); + + 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..1bc4427 --- /dev/null +++ b/06_todo_events/todos/todos.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include + +void todos_config(){ + name("todos"); + + sqlite_config(); + pubsub_config(); + session_auth_config(); + + 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", + .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"}), + emit("todo_created"), + 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/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-context-scoping.svg b/07-context-scoping.svg new file mode 100644 index 0000000..0dd81ea --- /dev/null +++ b/07-context-scoping.svg @@ -0,0 +1,50 @@ + + + + + + + + + Global .context + base_layout, site_name + + + + Resource .context + layout, sidebar + + + + Route Pipeline — GET /todos + + + + db() → todos + + + + + + call() → count + + + + + + render() + + + render() sees: base_layout, site_name, layout, sidebar, todos, count + Context merges top-down; first named registration wins + + + + + + + + + + Context cascades: global .context → resource .context → pipeline steps add to context → render() merges all + diff --git a/07_roundest_pokemon_htmx/README.md b/07_roundest_pokemon_htmx/README.md new file mode 100644 index 0000000..e958b0f --- /dev/null +++ b/07_roundest_pokemon_htmx/README.md @@ -0,0 +1 @@ +compare to https://github.com/t3dotgg/1app5stacks diff --git a/07_roundest_pokemon_htmx/create_pokemons_table.sql b/07_roundest_pokemon_htmx/create_pokemons_table.sql new file mode 100644 index 0000000..f820320 --- /dev/null +++ b/07_roundest_pokemon_htmx/create_pokemons_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS pokemons ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + sprite TEXT NOT NULL, + wins INTEGER NOT NULL DEFAULT 0, + loses INTEGER NOT NULL DEFAULT 0 +); diff --git a/07_roundest_pokemon_htmx/get_challengers.sql b/07_roundest_pokemon_htmx/get_challengers.sql new file mode 100644 index 0000000..57f2514 --- /dev/null +++ b/07_roundest_pokemon_htmx/get_challengers.sql @@ -0,0 +1,4 @@ +select id, name, sprite +from pokemons +order by random() +limit 2; diff --git a/07_roundest_pokemon_htmx/get_results.sql b/07_roundest_pokemon_htmx/get_results.sql new file mode 100644 index 0000000..a4105ba --- /dev/null +++ b/07_roundest_pokemon_htmx/get_results.sql @@ -0,0 +1,5 @@ +select id, name, sprite, wins, loses, + cast(wins as real) / nullif(loses, 0) as ratio_of_wins_to_loses, + row_number() over (order by (cast(wins as real) / nullif(loses, 0)) desc) as rank +from pokemons +order by ratio_of_wins_to_loses desc; diff --git a/07_roundest_pokemon_htmx/home.mustache.html b/07_roundest_pokemon_htmx/home.mustache.html new file mode 100644 index 0000000..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..a54321e --- /dev/null +++ b/07_roundest_pokemon_htmx/main.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include + +void mach(){ + htmx_config(); + sqlite_config(); + tailwind_config(); + + 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..2e1626f --- /dev/null +++ b/README.md @@ -0,0 +1,2118 @@ + +# MACH + +## Why MACH + +MACH (Modern Asynchronous C Hypermedia) is a declarative framework for building asynchronous web applications in C23. + +* **No build configuration.** Compilation, hot reload, and hmr are handled by the framework. There are no build scripts, package managers, or ORMs to set up. Templates and SQL live in files that are discovered and registered automatically. +* **Memory, concurrency, and I/O managed by the framework.** Application code does not call `malloc`/`free` or manage threads, mutexes, or locks. Database queries run as prepared statements. Pipeline steps emit OpenTelemetry spans, logs, and errors automatically. +* **Durable tasks and events.** Both are persisted. If the process crashes, incomplete tasks resume at the step where they left off and undelivered events replay on the next boot. +* **Bundled modules.** SSE plus modules for Datastar, HTMX, Tailwind, SQLite, Postgres, MySQL, Redis/Valkey, DuckDB, and auth. Multi-tenant database support is built in. + +--- + +## Table of Contents +* [Quick Start](#quick-start) +* [Philosophy](#philosophy) +* [Guide](#guide) +* [Reference](#reference) +* [Architecture](#architecture) +* [Tooling](#tooling) +* [License](#license) + +--- + +## Quick Start + +Everything runs in Docker, no other local dependencies are required. + +```bash +mkdir myapp && cd myapp +wget https://docker.nightshadecoder.dev/mach/compose.yml + +# Dev server on :3000, telemetry on :4000 +# Includes file watching, auto compilation, hot code reloading, HMR +docker compose up +``` + +Create `main.c` with the example below. MACH watches for changes and hot-reloads on save. Use your own editor, or attach to the built-in TUI with `docker compose attach mach` for an integrated environment with editor, AI, LSP, and console. + +```c +#include + +void mach(){ + resource("home", "/", + .get = { + mustache(.body = "

Hello, world!

") + } + ); +} +``` + +The `mach()` function runs once at boot and declares the application by calling into the MACH API. Each call configures MACH: here, a single `resource()` declares the `home` endpoint that maps `/` to a GET pipeline whose only step renders inline HTML. For a step-by-step walkthrough, see the [Guide](#guide). + +--- + +## Philosophy + +An application is a data transformation: input arrives, goes through transformation, and leaves as output. MACH is a thin pipeline wrapper around that path, built to get from input to output with as little overhead as possible. + +Mach uses standard formats and tools. Assets are raw SQL, JSON, Markdown, and HTML/CSS/JS via Mustache templates, not ORMs or bespoke formats. Business logic is plain C. The tooling is the same: lldb for debugging, Playwright and Criterion for testing, OpenTelemetry for observability, and OpenCode AI assistant. MACH uses these standard tools and formats and arranges them 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. MACH takes this literally. The pipeline context stores and passes data as strings; there is no intermediate parsing or serialization layer. Data flows through the pipeline as strings, interpolated into SQL, templates, and URLs with `{{context_key}}`. + +### CLAD + +MACH is organized around four principles. + +* **(C)omposable:** small, independent steps chain into feature pipelines. +* **(L)ocality of Behavior:** the behavior of a unit of code is apparent from reading it. SQL, templates, and behavior for a feature live together rather than across separate model, view, and controller trees. +* **(A)utonomous:** modules are self-contained: own schemas, migrations, seeds, routes, UI, and logic. The compiler enforces strict boundaries. +* **(D)omain Based:** each module owns one slice of the app. A `todos` module defines everything related to todos and nothing else. + +CLAD is influenced by: + +* [Data Oriented Design](https://youtu.be/rX0ItVEVjHc) +* [A Philosophy of Software Design](https://youtu.be/bmSAYlu0NcY) +* [CUPID](https://youtu.be/cyZDLjLuQ9g) +* [Self-Contained Systems](https://youtu.be/Jjrencq8sUQ) +* [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour) + +--- + +## Guide + +This walkthrough builds a todo app one concept at a time. It stays high-level and points to the [Reference](#reference) for the full options on each step, helper, and field. MACH discovers templates and SQL automatically and works out which module owns each one from its location (see [Modules and Composition](#modules-and-composition)). + +* [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 + +`mach()` is the declarative entry point: each `resource(...)` call declares a named URL endpoint, and each verb pipeline is a list of steps. The `mustache("home")` step renders the template asset `home`, which is the file `home.mustache.html`. Reference resources by name with `{{url:...}}`, never by hard-coded path. + +Both pages share the same layout, so the `home` page doubles as the layout: it declares the nav and a `{{$body}}` block whose default content is the welcome page, and the `todos` page extends it with `{{ + + +
{{$body}}

Welcome

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

Nothing yet.

+ {{/body}} +{{/home}} +``` + +**`main.c`** +```c +#include + +void mach(){ + resource("home", "/", .get = { mustache("home") }); + resource("todos", "/todos", .get = { mustache("todos") }); +} +``` + +See [Resource Pipelines](#resource-pipelines) for more configuration options, and [Template Helpers](#template-helpers) for the full template feature set. + +### 2. Show Data + +Activate the module with `sqlite_config()`, declare a database with `sqlite_database(...)`, and read from it with a `sqlite_query()` step. SQL lives in files too, including seed data: `get_todos.sql` becomes the asset `get_todos`, `seed_todos.sql` becomes `seed_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 + + void mach(){ ++ sqlite_config(); ++ ++ sqlite_database( ++ .name = "todos_db", ++ .connect = "file:todos.db?mode=rwc", ++ .migrations = {"create_todos_table"}, ++ .seeds = {"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") ++ } ++ ); + } +``` + +The query's parameters are the database name, the SQL asset, and the context key the result table is stored under (`todos_data`). The `.seeds` entry is the asset name of `seed_todos.sql`. The template walks the result with `{{#todos_data}}...{{/todos_data}}`. Migrations/Seeds run on first connection if needed. 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 when validation fails. + +**`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 + 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` is bound 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 in context, so no argument is needed: + +**`todos.mustache.html`** +```diff + {{My Todos +-
    {{#todos_data}}
  • {{title}}
  • {{/todos_data}}
++ +
+``` + +Register the migration and add a `todo` resource: + +**`main.c`** +```diff + sqlite_database( + .name = "todos_db", + .connect = "file:todos.db?mode=rwc", +- .migrations = {"create_todos_table"}, ++ .migrations = {"create_todos_table", "create_comments_table"}, + .seeds = {"seed_todos"} + ); +``` +```diff ++ 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(.parent_key = "todo_data", .field_key = "id", .child_key = "comments", .child_field_key = "todo_id", .join_field_key = "comments"), ++ 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 a 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 an optional `.cron`, and enqueue on-demand runs with the `task("name")` step. + +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, and enqueue it from the POST: + +**`main.c`** +```diff + sqlite_database( + .name = "todos_db", + .connect = "file:todos.db?mode=rwc", +- .migrations = {"create_todos_table", "create_comments_table"}, ++ .migrations = {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + .seeds = {"seed_todos"} + ); +``` +```diff ++ task("record_daily_stats", { ++ sqlite_query({"todos_db", "record_daily_stats"}) ++ }, .cron = "0 0 * * *"); +``` +```diff + .post = { + input({"title", m_not_empty}), + sqlite_query({"todos_db", "create_todo"}), ++ task("record_daily_stats"), + redirect("todos") + }, +``` + +The `.cron` schedule and the `task("record_daily_stats")` step both run the task on a task reactor, off the request reactors, so the POST returns immediately. Tasks are durable, so 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 + +As the app grows, split features into modules that talk through pub/sub events rather than calling each other. A module is a folder with a matching `.c` file (`todos/todos.c`) defining `void todos_config()`, which calls `name("todos")` and declares the module's resources, databases, tasks, and subscribers. Templates and SQL in that folder belong to the module. `main.c` composes modules by `#include`ing each `.c` and calling its `_config()`. + +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, and leave `home` (which is also 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 "todos/todos.c" ++#include "activity/activity.c" + + void mach(){ +- sqlite_config(); +- +- sqlite_database( +- .name = "todos_db", +- .connect = "file:todos.db?mode=rwc", +- .migrations = {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, +- .seeds = {"seed_todos"} +- ); +- +- task("record_daily_stats", { +- sqlite_query({"todos_db", "record_daily_stats"}) +- }, .cron = "0 0 * * *"); +- ++ todos_config(); ++ activity_config(); + resource("home", "/", .get = { mustache("home") }); +- +- resource("todos", "/todos", ...); +- resource("todo", "/todos/:id", ...); + } +``` + +The todos logic moves into the module unchanged, gaining a `name()`, a `publish()`, and an `emit()` step: + +**`todos/todos.c`** +```c +#include +#include +#include + +void todos_config(){ + name("todos"); + sqlite_config(); + pubsub_config(); + + sqlite_database( + .name = "todos_db", + .connect = "file:todos.db?mode=rwc", + .migrations = {"create_todos_table", "create_comments_table", "create_daily_stats_table"}, + .seeds = {"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"}), + task("record_daily_stats"), + emit("todo_created"), + redirect("todos") + }, + .errors = { + {m_bad_request, {reroute("todos")}} + } + ); +} +``` + +The `activity` module subscribes to the event; nothing in it references the todos module: + +**`activity/insert_activity.sql`** +```sql +insert into activities(kind, ref) values('created', {{title}}); +``` + +**`activity/activity.c`** +```c +#include +#include +#include + +void activity_config(){ + name("activity"); + sqlite_config(); + pubsub_config(); + + 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", "activities"}), + mustache("activity") + } + ); +} +``` + +When the POST calls `emit("todo_created")`, MACH propagates the keys named in `publish(...).with` (here `title`) to every subscriber. The `activity` module writes its row, with no direct link between the two modules. 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 +- resource("home", "/", .get = { mustache("home") }); ++ resource("home", "/", ++ .get = { ++ fetch( ++ {"https://api.quotable.io/random", .set_key = "quote"}, ++ {"https://api.weather.dev/now", .set_key = "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) +* [Databases](#databases) +* [Resource Pipelines](#resource-pipelines) +* [Template Helpers](#template-helpers) +* [Pipeline Steps](#pipeline-steps) +* [Imperative API](#imperative-api) +* [Conditionals](#conditionals) +* [Iteration](#iteration) +* [Error and Repair Pipelines](#error-and-repair-pipelines) +* [Event Pipelines](#event-pipelines) +* [Task Pipelines](#task-pipelines) +* [Modules and Composition](#modules-and-composition) +* [Module Reference](#module-reference) +* [Static Files](#static-files) +* [External Dependencies](#external-dependencies) + +### Context + +Pipelines read from and write to a shared, scoped key-value store that lives for the duration of one request. Every step draws inputs from context and writes outputs back to it. + +Values enter the context from several places: `sqlite_query()` (and the other engine queries) store result tables under their `set_key`; `fetch()` stores parsed responses; `input()` promotes validated request parameters; `session()` loads the current `user`; and `set()` inside `exec()` writes computed values. Docker secrets exposed to the container are also available. + +The context uses three scopes: `input:xxx` for raw request parameters, `error:xxx` for validation/error data, and unprefixed names for app scope (query results, validated inputs, computed values). The `input()` step promotes values from the `input:` scope to app scope. + +Templates and SQL are not part of the context. They are **assets**, discovered automatically from `*.mustache.html` and `*.sql` files anywhere in the project and referenced by name (filename without the type suffix). There is no registration step and no `#embed`; saving the file is enough. Each asset belongs to a module based on where it sits in the directory tree, and a pipeline can reference assets from its own module or any ancestor module. See [Modules and Composition](#modules-and-composition). + +**Reading and writing at runtime** happens through the [Imperative API](#imperative-api) inside `exec()`: +```c +exec(^(){ + auto rows = get("todos"); + if (table_count(rows) > 5) set("is_urgent", "1"); +}) +``` + +**App-wide values** that should be present on every request can be seeded with a `set()` in a `middleware()` step: +```c +middleware(exec(^(){ set("site_name", "MACH App"); })); +``` + +![Context Scoping](./07-context-scoping.svg) + +### Databases + +Each database is registered with its engine's `_database(...)` call (for example `sqlite_database(...)`), and the engine module must be activated first with `_config()`. There is no `.engine` field; the function you call selects the engine. Migrations are forward-only and index-based: they run in array order, each applied once, with new migrations appended to the end. Seeds are idempotent and safe to re-run. Both are tracked in a `mach_meta` table. + +Multi-tenant databases use `{{interpolation}}` in `.connect`. Connections are pooled with LRU eviction: active tenants stay warm, idle connections are reclaimed. + +**`.name`**: identifier referenced by the first positional 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 either an asset name (a discovered `.sql` file) or an inline SQL string. +```c +.migrations = {"create_todos_table", "create_comments_table"} +``` + +**`.seeds`**: array of idempotent seed entries (asset name or inline SQL), safe to re-run on every boot. +```c +.seeds = {"seed_todos"} +``` + +Combined: +```c +sqlite_config(); + +sqlite_database( + .name = "blog_db", + .connect = "file:{{user_id}}_blog.db?mode=rwc", + .migrations = {"create_blogs_table", "create_comments_table"}, + .seeds = {"seed_blogs"} +); +``` + +**Engine activation / query / register:** `sqlite_config()` + `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(...)` call defines a named URL endpoint with HTTP verb pipelines. Resources are identified by name. `{{url:name}}`, `redirect()`, and `reroute()` all take only the resource name; any `:params` in the URL pattern are read from the current scope by matching key names. Path specificity is automatic: exact matches (`/todos/active`) 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 *(pos)***: resource identifier used by `{{url:name}}`, `redirect()`, and `reroute()`. +```c +resource("todos", "/todos", .get = { ... }); +``` + +**URL pattern *(pos)***: 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 for the resource. +```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. First positional 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")}}} +); +``` + +**MIME types (for `.mime`):** `m_html`, `m_txt`, `m_sse`, `m_json`, `m_js` + +### Template Helpers + +Templates are Mustache. MACH supports the full Mustache base spec with one exception: dot notation. Use a section instead. `{{a.b}}` does not work; `{{#a}}{{b}}{{/a}}` does. + +Supported base-spec features: +- **Interpolation**: `{{name}}` (HTML-escaped), `{{{name}}}` or `{{&name}}` (unescaped). +- **Sections**: `{{#name}}...{{/name}}` renders when truthy and iterates over arrays. +- **Inverted sections**: `{{^name}}...{{/name}}` renders when falsy or empty. +- **Comments**: `{{! ignored }}`. +- **Set delimiters**: `{{=<% %>=}}`. +- **Partials**: `{{>name}}` inlines the asset named `name`, rendered against the current scope. +- **Layout inheritance**: `{{All" // /todos + "{{#todos_data}}{{title}}{{/todos_data}}" // /todos/{{id}} per row + "{{#todo}}{{title}}{{/todo}}" // /todos/{{id}} from a single record +) +``` + +**`{{asset:filename}}`**: resolve a file in `public/` to a cache-busted URL (content checksum + immutable cache headers). See [Static Files](#static-files). +```c +mustache(.body = "") +``` + +**`{{csrf:token}}`**: emit a CSRF token, for use in URL query strings. Generates a random hash, sets it on an httponly/secure/samesite cookie, and outputs the same value inline. +```c +mustache(.body = "Log out") +``` + +**`{{csrf:input}}`**: emit a hidden `` carrying a CSRF token, for use inside a ``. Same cookie-setting behavior as `{{csrf:token}}`. +```c +mustache(.body = "{{csrf:input}}") +``` + +> **CSRF verification is automatic.** MACH checks that the incoming token (from the form field or query parameter) matches the value stored in the CSRF cookie and rejects mismatches with a 403. The cookie is httponly, secure, and samesite, so nothing beyond emitting `{{csrf:token}}` or `{{csrf:input}}` in the rendered response is required. + +--- + +### Pipeline Steps + +Steps are the units of work in a pipeline. Each receives the current context, acts on it, and passes control to the next. All steps accept `.if_context` and `.unless_context` for [conditional execution](#conditionals), and `.table_key` for concurrent fan-out across rows of a context table (see [Iteration](#iteration)). + +> **Concurrency comes from multiple items inside one step, not from multiple steps in sequence.** `sqlite_query({...}, {...})` runs both queries concurrently; two back-to-back `sqlite_query({...})` steps run serially. The same applies to `fetch()` and to `.table_key` iteration. + +* [input](#input) +* [query](#query) +* [join](#join) +* [fetch](#fetch) +* [exec and worker](#exec-and-worker) +* [emit](#emit) +* [task](#task) +* [sse](#sse) +* [mustache and mdm](#mustache-and-mdm) +* [headers and cookies](#headers-and-cookies) +* [redirect and reroute](#redirect-and-reroute) +* [nest](#nest) + +![Request Pipeline Flow](./02-request-pipeline-flow.svg) + +#### input + +Checks request parameters (query string, form body, URL params) against regex patterns. On success, each value is promoted from `input:name` to app scope. On failure, errors land in `error:name` and a `400 Bad Request` triggers the nearest [error/repair pipeline](#error-and-repair-pipelines). All validations in one call complete before the error fires, so all errors are available together for form re-rendering. + +Built-in regex macros are defined in `mach.h`; define your own the same way: `#define m_zipcode "^\\d{5}$"`. For checks that don't fit a regex (uniqueness, cross-field rules, async lookups), follow `input()` with an `exec()` step that reads the value from context and calls `error_set()` on failure. + +**`.param_key` *(pos)***: name of the parameter to validate. +```c +input({"title", "^\\S+$", "required"}) +``` + +**`.matches` *(pos)***: regex pattern, or a built-in validator macro. +```c +input({"email", m_email, "bad email"}) +``` + +**`.message` *(pos)***: 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 database engine provides its own query step: `sqlite_query()`, `postgres_query()`, `mysql_query()`, `redis_query()`, `duckdb_query()`. All share the same `query_config` shape. The first positional is the database `.name`; the second is the SQL asset to run; the third is the `.set_key` the result table is stored under (even single-row results are tables). Multiple items in a single step run **concurrently**. Queries use prepared statements; interpolated `{{values}}` are bound, not spliced. For transactions, put `BEGIN`/`COMMIT`/`ROLLBACK` directly in the SQL. + +**`.db` *(pos)***: name of the database, matching a registered `_database(.name = ...)`. +```c +sqlite_query({"todos_db", "get_todos", "todos_data"}) +``` + +**`.query` *(pos)***: name of a SQL asset (a discovered `.sql` file). Mutually exclusive with `.body`. +```c +sqlite_query({"todos_db", "get_todos", "todos_data"}) +``` + +**`.set_key` *(pos)***: context key for the result table. Optional; omit it 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" +``` + +**`.body`**: inline SQL string, as an alternative to a named asset. Supports `{{interpolation}}`, bound as parameters. Mutually exclusive with the `.query` asset name. +```c +sqlite_query({.db = "todos_db", .set_key = "todos_data", .body = "select id, title from todos where user_id = {{user_id}};"}) +``` + +**`.must_exist`**: when true, raise `404 Not Found` if the query affects/returns zero rows. Default is 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"}, + {.db = "todos_db", .set_key = "count", .body = "select count(*) as n from todos where user_id = {{user_id}};"}, + {"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 performed in memory. Useful when records come from separate databases or queries and need to be combined. After the step, each outer record gains a new field holding its matched inner records. + +**`.parent_key`**: outer table whose records receive nested children. +```c +.parent_key = "projects" +``` + +**`.field_key`**: field on the outer table to match against. +```c +.field_key = "id" +``` + +**`.child_key`**: inner table whose records get nested. +```c +.child_key = "todos" +``` + +**`.child_field_key`**: field on the inner table that points at the outer. +```c +.child_field_key = "project_id" +``` + +**`.join_field_key`**: new field on outer records holding the matched inner records. +```c +.join_field_key = "todos" +``` + +Combined: +```c +join(.parent_key = "projects", .field_key = "id", .child_key = "todos", .child_field_key = "project_id", .join_field_key = "todos") +``` + +**Full context example.** Concurrent query → `join()` → `mustache()`: fetch parent and children from separate queries, then render them as one nested structure. Blog + comments, single database: + +```c +resource("blog", "/blogs/:id", + .get = { + input({"id", m_integer}), + + // Fetch both concurrently: one query() call, two items + sqlite_query( + {.db = "blog_db", .set_key = "blog", .body = "select id, title, content from blogs where id = {{id}};"}, + {.db = "blog_db", .set_key = "comments", .body = "select id, blog_id, body from comments where blog_id = {{id}};"} + ), + + // Nest each comment into its matching blog record + join(.parent_key = "blog", .field_key = "id", .child_key = "comments", .child_field_key = "blog_id", .join_field_key = "comments"), + + // Enter {{#blog}} first; after join(), comments lives INSIDE each blog record + mustache(.body = + "
" + "{{#blog}}" + "

{{title}}

" + "
{{content}}
" + "

Comments

" + "
    {{#comments}}
  • {{body}}
  • {{/comments}}
" + "{{/blog}}" + "
" + ) + } +); +``` + +Shape of the context at each step: + +``` +after query(): { blog: [{id, title, content}], + comments: [{id, blog_id, body}, ...] } // two sibling tables + +after join(): { blog: [{id, title, content, + comments: [{id, blog_id, body}, ...]}] } // nested inside blog +``` + +#### fetch + +Makes one or more HTTP requests and stores responses in context. JSON is parsed into tables and records (with nested tables for nested JSON); plain-text responses are stored as a string. Like `query()`, multiple items in a single step run **concurrently**, so a page can fan out to several services and join the results downstream. + +**`.url` *(pos)***: request URL; supports `{{interpolation}}`. +```c +fetch({"https://api.weather.dev/forecast?city={{city}}", .set_key = "w"}) +``` + +**`.set_key`**: context key for the response. +```c +fetch({"https://api.weather.dev/now", .set_key = "weather"}) +``` + +**`.method`**: HTTP method. Defaults to `m_get`. +```c +fetch({"https://api.dev/charge", .set_key = "r", .method = m_post}) +``` + +**`.headers`**: array of name/value pairs. +```c +fetch({"https://api.dev/me", .set_key = "r", .headers = {{"Authorization", "Bearer {{token}}"}}}) +``` + +**`.json`**: context key serialized as the JSON request body. +```c +fetch({"https://api.dev/charge", .set_key = "receipt", .method = m_post, .json = "order"}) +``` + +**`.text`**: context key sent as the plain-text request body. +```c +fetch({"https://api.dev/log", .set_key = "r", .method = m_post, .text = "raw_body"}) +``` + +**`.if_context` / `.unless_context`** *(per item)*: conditionally include or skip individual requests while running the others concurrently. +```c +fetch( + {"https://api.weather.dev/now", .set_key = "weather"}, + {"https://api.quotes.dev/random", .set_key = "quote", .if_context = "show_quote"} +) +``` + +Combined, single request: +```c +fetch({"https://api.payments.dev/charge", + .set_key = "receipt", + .method = m_post, + .headers = { + {"Authorization", "Bearer {{api_key}}"}, + {"Idempotency-Key", "{{order_id}}"} + }, + .json = "order" +}) +``` + +Combined, concurrent fan-out: +```c +fetch( + {"https://api.weather.dev/now?city={{city}}", .set_key = "weather"}, + {"https://api.news.dev/headlines?topic={{topic}}", .set_key = "news"}, + {"https://api.quotes.dev/random", .set_key = "quote"} +) +``` + +**HTTP methods (for `.method`):** `m_get`, `m_post`, `m_put`, `m_patch`, `m_delete`, `m_sse_method` + +#### exec and worker + +`exec()` calls a C function or block with access to the context via the Imperative API. It is where business logic and data shaping lives: enriching query results with computed fields, aggregating across rows, transforming data between steps, setting flags for [conditional](#conditionals) downstream steps. To trigger an error/repair pipeline from inside, call `error_set()`. + +`worker()` takes the same configuration as `exec()` but is for blocking or CPU-bound work such as calling external C libraries, blocking I/O, or heavy computation. The work is dispatched to the shared thread pool, which releases the reactor; the pipeline resumes on the original reactor when the call returns. Use `worker()` when the body would otherwise stall a request reactor. + +**Block *(pos)***: inline block, for short logic specific to this pipeline. Here, attaching each challenger's opponent id so the template can render two voting forms with the right winner/loser pairing: +```c +exec(^(){ + auto 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 `exec`/`worker` blocks and functions, context, memory, errors, tables, and records are manipulated through the [Imperative API](#imperative-api). + +#### emit + +Triggers an internal pub/sub event. Subscribers in other modules react in their `subscribe()` pipelines, with no direct dependency on the emitter. See [Event Pipelines](#event-pipelines). + +**Event name *(pos)***: name of the event to publish. +```c +emit("todo_created") +``` + +#### task + +Adds a named job to the task database; the calling pipeline continues immediately. Task reactors pick up queued jobs and execute their pipelines. The task must be defined elsewhere with a `task(name, { ... })` registration. See [Task Pipelines](#task-pipelines). + +**Task name *(pos)***: name of a defined task. +```c +task("record_daily_stats") +``` + +#### sse + +Pushes a Server-Sent Event. With `.channel`, the event is broadcast to all clients on that channel. Without `.channel`, the event is returned directly to the requesting client. See [Resource Pipelines](#resource-pipelines). + +**`.channel` *(pos)***: channel to broadcast on; supports `{{interpolation}}`. +```c +sse(.channel = "todos/{{user_id}}", .event = "new_todo", .data = {"{{todo}}"}) +``` + +**`.event`**: SSE `event:` line value. +```c +sse(.event = "ping") +``` + +**`.data`**: array of strings, one per SSE `data:` line (multi-line data). +```c +sse(.event = "msg", .data = {"line one", "line two"}) +``` + +**`.comment`**: SSE `:` comment line value, useful for keep-alives. +```c +sse(.comment = "keep-alive") +``` + +Combined: +```c +sse( + .channel = "todos/{{user_id}}", + .event = "todo_updated", + .data = {"id: {{todo_id}}", "title: {{title}}"}, + .comment = "broadcast at {{timestamp}}" +) +``` + +#### mustache and mdm + +Outputs a template using the current context. `mustache()` renders Mustache; `mdm()` renders Markdown-with-Mustache. Both take the same `render_config`: the positional `.template` names a discovered template asset, or `.body` supplies an inline template string. + +**`.template` *(pos)***: asset name of a discovered template. +```c +mustache("todos") +``` + +**`.body`**: inline template string. +```c +mustache(.body = "

{{site_name}}

") +``` + +**`.status`**: HTTP response status (defaults to `m_ok`). +```c +mustache("not_found", .status = m_not_found) +``` + +**`.mime`**: override the response content type. +```c +mustache("plain", .mime = m_txt) +``` + +**`.json_table_key`**: context table to serialize as the JSON response. Sets `application/json`; nested tables produce nested JSON. +```c +mustache(.json_table_key = "todos") +``` + +Markdown-with-Mustache: +```c +mdm(.body = "# Welcome, {{user_name}}") +``` + +**HTTP statuses (for `.status`):** `m_ok` (200), `m_created` (201), `m_redirect` (302), `m_bad_request` (400), `m_not_authorized` (401), `m_not_found` (404), `m_error` (500) + +**MIME types (for `.mime`):** `m_html`, `m_txt`, `m_sse`, `m_json`, `m_js` + +#### headers and cookies + +Set HTTP response headers and cookies declaratively. Both accept an array of name/value pairs; values support `{{interpolation}}`. + +**Pairs *(pos)***: array of `{name, value}` entries. +```c +headers({{"X-Request-Id", "{{request_id}}"}}) +``` +```c +cookies({{"session", "{{session_id}}"}}) +``` + +Combined: +```c +headers({ + {"X-Request-Id", "{{request_id}}"}, + {"Cache-Control", "no-store"} +}), +cookies({ + {"session", "{{session_id}}"}, + {"theme", "{{theme}}"} +}) +``` + +#### redirect 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; no positional args. + +**Resource name *(pos)***: 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 +``` + +Required `:params` must be in context before the step runs. `input()` promotes validated parameters into context; otherwise, write them with `set()` in an `exec()`. + +#### nest + +Groups multiple steps into a single composite step. Useful when applying one `.if_context`/`.unless_context` to several steps, to avoid repeating the condition on each. + +**`.steps` *(pos)***: array of steps that run as a unit. +```c +nest({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 to templates. +```c +set("is_urgent", "1"); +``` + +**`has(name)`**: returns true when `name` exists in the current scope. +```c +if (has("user_id")) { ... } +``` + +**`format(fmt)`**: returns `fmt` with `{{name}}` interpolations resolved against the current context. Same scopes and helpers as templates. +```c +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 inside `exec()` to trigger error/repair pipelines. The keys land in the `error:name` scope, visible to templates as `{{error:name}}`, `{{error_code:name}}`, and `{{error_message:name}}`. + +**`error_set(name, err)`**: associates an error with `name` and triggers the nearest [error or repair pipeline](#error-and-repair-pipelines). +```c +error_set("token", (error){ 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`, which name a context variable. They work for any context value: validated inputs, query results, framework flags such as `is_htmx`, or flags set from `exec()`. + +**`.if_context`**: context key. Step runs only when the value is present. +```c +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, and all rows run **concurrently**, the same as 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}}", .set_key = "profiles", .table_key = "users"}) +``` + +Use `.table_key` for per-row work that doesn't fit a single query or request, such as external APIs without bulk endpoints. For nesting tables already in context, prefer `join()`. + +### Error and Repair Pipelines + +When a pipeline step fails, execution halts and MACH searches for a handler bottom-up: resource, then module, then root. Errors are terminal: the handler sends a response and ends the request. Repairs are resumable: they fix the context and resume the original pipeline at the step after the failure. If no matching repair is found, resolution falls through to errors. Unhandled errors fall through to MACH's internal handler, which renders the error message as `text/plain` with the error code as the HTTP status, and surfaces in the TUI console and telemetry. + +The `error` scope is shared across `input()` failures and `error_set()` calls: `{{error:name}}`, `{{error_code:name}}`, `{{error_message:name}}`. The raw input value remains available in `input:name` for re-rendering forms. + +Handlers are registered two ways. At a resource, use the `.errors` / `.repairs` fields inside the `resource(...)` call. At module or root scope, call `error(...)` / `repair(...)` directly; the handler applies to that whole config scope. + +**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/root-scoped (`error()` / `repair()` calls):** +```c +void mach(){ + 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_ok` (200), `m_created` (201), `m_redirect` (302), `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, with no changes to the publisher. Activate the system with `pubsub_config()` in any module that publishes or subscribes. + +Events are durable by default. When a publisher is declared anywhere in the app, MACH creates a `mach_events` database to track delivery. If the process crashes, undelivered events are replayed on the next boot. + +**`publish(event, .with = {...})`**: declares an outbound event contract. The positional 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 with the same bottom-up search as resource pipelines. 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 +void todos_config(){ + name("todos"); + sqlite_config(); + pubsub_config(); + + 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 +void activity_config(){ + name("activity"); + sqlite_config(); + pubsub_config(); + + subscribe("todo_created", { + sqlite_query({.db = "activity_db", .body = "insert into activities(kind, user_id, ref) values('created', {{user_id}}, {{title}});"}) + }); + subscribe("todo_deleted", { + sqlite_query({.db = "activity_db", .body = "insert into activities(kind, user_id, ref) values('deleted', {{user_id}}, {{todo_id}});"}) + }); +} +``` + +![Event Pub/Sub](./03-event-pub-sub.svg) + +### Task Pipelines + +Tasks are named pipelines that run asynchronously on task reactors. Fire-and-forget: the calling pipeline continues immediately. Defined at module or root scope. Triggered on demand with the `task("name")` step or on a schedule via `.cron`. Tasks can enqueue more tasks. Activate the system with `task_config()`. + +A task is registered with `task(name, { pipeline }, ...)`: the name, a pipeline body, and optional `.cron`/`.accepts`. The same `task("name")` form with only a name is the [enqueue step](#task) used inside a pipeline. + +Tasks are durable: when a task is defined, MACH creates a `mach_tasks` database and checkpoints the context after each step. A crash mid-task resumes at the step where it left off on the next boot. + +**Task name *(pos)***: task identifier, enqueued via `task("name")`. +```c +task("recount_todos", { + sqlite_query({.db = "db", .body = "update users set ..."}) +}); +``` + +**Pipeline *(pos)***: the task's pipeline body, the second positional brace block. +```c +task("name", { sqlite_query({...}), emit("done"), task("followup") }); +``` + +**`.accepts`**: context keys to pull from the caller into the task. +```c +task("recount_todos", { + sqlite_query({.db = "db", .body = "update users set todo_count = ... where id = {{user_id}};"}) +}, .accepts = {"user_id"}); +``` + +**`.cron`**: standard cron schedule for recurring tasks (no caller required). +```c +task("daily_digest", { + sqlite_query({.db = "db", .body = "insert into digest_reports ..."}) +}, .cron = "0 8 * * *"); +``` + +**`.errors` / `.repairs`** *(per task)*: each task can declare its own handlers, resolved with the same bottom-up search as resource pipelines. See [Error and Repair Pipelines](#error-and-repair-pipelines). +```c +task("send_invoice", { + fetch({"https://api.billing.dev/invoices/{{invoice_id}}", .set_key = "inv"}) +}, .repairs = {{m_not_authorized, {exec(.call = refresh_billing_token)}}}); +``` + +Combined: +```c +// on-demand: enqueued via task("recount_todos") +task("recount_todos", { + sqlite_query({.db = "todos_db", .body = "update users set todo_count = (select count(*) from todos where user_id = users.id) where id = {{user_id}};"}) +}, .accepts = {"user_id"}); + +// recurring: runs on schedule, no caller +task("daily_digest", { + sqlite_query({.db = "todos_db", .body = "insert into digest_reports(generated_at) values(now());"}), + emit("digest_ready") +}, .cron = "0 8 * * *"); +``` + +### Modules and Composition + +Every MACH app and module is a function that registers its pieces by calling into the MACH API. The root `main.c` must define `void mach()`; a module defines `void _config()` and declares its identity with `name("...")`. A module owns its own resources, databases, migrations, tasks, event contracts, and middleware. + +Compose by `#include`ing a module's `.c` file and calling its `_config()` function. Activation is idempotent: calling `sqlite_config()` from several modules, or a module's `_config()` indirectly more than once, is safe and deduplicated. This replaces listing a module in multiple `.modules` arrays. + +**Assets and module ownership.** Templates and SQL can live anywhere in the directory tree. To decide which module owns an asset, MACH looks at the asset's containing folder: a folder is a module when it contains a matching `.c` file (so `todo/` is a module when `todo/todo.c` exists). An asset belongs to the nearest such module folder walking up from its location; folders without a matching `.c` file are organizational only and pass ownership up to their parent. The root is the `main` module, defined by `main.c`. Given: + +``` +. +├── main.c # defines void mach(), the "main" module +├── layout.mustache.html # → main (root, no nearer module folder) +├── asset/ +│ └── home.mustache.html # → main (asset/ has no asset.c, so it's just a folder) +└── todo/ + ├── todo.c # defines void todo_config(), the "todo" module + ├── todos.mustache.html # → todo + └── stuff/ + └── todo.mustache.html # → todo (stuff/ has no stuff.c, ownership rises to todo) +``` + +A pipeline can reference assets owned by its own module **or by any ancestor module**, never by sibling or descendant modules. So the `todo` module can render `layout` (owned by its parent `main`) and its own `todos`, but `main` cannot reach into `todo`'s assets. A parent can therefore provide shared chrome while keeping module internals private. + +When the root and a module both define something with the same name, resolution depends on the kind. Context variables and databases resolve **top-down** from the root, so the **root wins**. Error and repair handlers resolve **bottom-up** from the resource (resource → module → root), so the **innermost handler wins**. Shared steps participate in every request pipeline within their scope and execute **bottom-up**: a resource's `.all` steps run first, then enclosing `middleware()` from innermost out (module → root), then the verb pipeline. Modules don't call each other directly; they communicate through pub/sub events. + +**`name(string)`**: declares a module's identifier. Called inside a module's `_config()`; the root `mach()` is implicitly named. +```c +void todos_config(){ name("todos"); /* resources, databases, ... */ } +``` + +**`_config()`**: a module's registration function. Call it to compose the module (from the root or another module). +```c +todos_config(); +activity_config(); +sqlite_config(); +session_auth_config(); +``` + +**`middleware(step)`**: registers a shared step that runs on every request within the current config scope. Cross-cutting setup like session loading or tenant resolution lives here. Call once per step. +```c +void mach(){ middleware(session()); /* modules, resources, ... */ } +``` + +**`error(...)` / `repair(...)`**: config-scoped error and repair handlers (see [Error and Repair Pipelines](#error-and-repair-pipelines)). Resolved bottom-up with resource and module handlers; the innermost handler wins. + +**Pipeline composition.** A request composes shared steps from every config layer with the resource's own steps and the verb pipeline, executing **bottom-up**: resource `.all` steps first, then enclosing `middleware()` from innermost out (module → root), then the verb pipeline. + +```c +// main.c: root config +#include +#include +#include "todos/todos.c" + +void mach(){ + todos_config(); + session_auth_config(); + + middleware(session()); + + resource("home", "/", .get = {mustache("home")}); +} + +// todos/todos.c: resources require login +#include +#include +#include + +void todos_config(){ + name("todos"); + sqlite_config(); + session_auth_config(); + + 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}) + }, + .delete = { sqlite_query({"todos_db", "delete_todo", .must_exist = true}), redirect("todos") } + ); +} +``` + +For `GET /todos/5` the executed order is: `logged_in()`, `input({"id", ...})` (resource `.all`), `session()` (root `middleware`), then the verb pipeline `sqlite_query({"get_todo", ..., .must_exist = true})`, `mustache("todo")`. + +**Complete module file.** A module's `_config()` registers the same kinds of things the root does (resources, databases, tasks, subscribers), plus a `name()`. A `blogs/blogs.c`: + +```c +#include +#include + +void blogs_config(){ + name("blogs"); + sqlite_config(); + + sqlite_database( + .name = "blog_db", + .connect = "file:blogs.db?mode=rwc", + .migrations = {"create_blogs_table", "create_comments_table"} + ); + + resource("blog", "/blogs/:id", + .get = { /* input → query → join → render; see `join` worked example */ } + ); +} +``` + +Bring the module into scope by `#include`ing its `.c` file from `main.c`, then call its `_config()`: +```c +// main.c +#include +#include "blogs/blogs.c" + +void mach(){ blogs_config(); } +``` + +A typical project layout: +``` +├── todos/ # todos module (folder + matching .c) +│ ├── todos.c # void todos_config() { ... } +│ ├── 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 # void mach(), the main module, composes the rest +``` + +**Bundled modules (activate by calling their `_config()`):** `sqlite_config`, `postgres_config`, `mysql_config`, `redis_config`, `duckdb_config`, `htmx_config`, `datastar_config`, `tailwind_config`, `session_auth_config`, `pubsub_config`, `task_config`. See [Module Reference](#module-reference) for what each provides. + +![App Composition Tree](./05-app-composition-tree.svg) +![Middleware Scoping](./06-middleware-scoping.svg) + +--- + +### Module Reference + +Bundled modules. Activate each by calling its `_config()` from the root or any module that uses it; activation is idempotent. + +* [htmx](#htmx) +* [datastar](#datastar) +* [tailwind](#tailwind) +* [session_auth](#session_auth) +* [Database engines](#database-engines) + +#### htmx + +Activate with `htmx_config()`. Serves the htmx runtime and exposes it as the `{{>htmx}}` partial, and sets the `is_htmx` context flag on requests that carry 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 + +void mach(){ + htmx_config(); + + 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 `datastar_config()`. Serves the Datastar runtime as the `{{>datastar}}` partial and provides the `datastar_sse()` step for pushing reactive fragment and signal patches over an SSE channel. A page opens an SSE connection (a resource `.sse` channel); pipelines elsewhere 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 positional is the channel (supports `{{interpolation}}`). + +**`.channel` *(pos)***: 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` (template asset or `.body`) 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`, and 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({.db = "todos_db", .set_key = "todo", .must_exist = true, + .body = "insert into todos(user_id, title) values({{user_id}}, {{title}}) returning id, title;"}), + // 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) +``` + +Like htmx, Datastar sets a context flag on requests it originates, usable with `.if_context`. Include the runtime once: `{{>datastar}}`. + +![SSE + Datastar Flow](./08-sse-datastar-flow.svg) + +#### tailwind + +Activate with `tailwind_config()`. Compiles Tailwind utility classes used across the project's templates and serves the stylesheet as the `{{>tailwind}}` partial. Use Tailwind utility classes directly in templates; no build step or config file is required. + +```html +{{>tailwind}} + +

Vote for which is roundest

+ +``` + +#### session_auth + +Activate with `session_auth_config()`. Provides cookie-based authentication as pipeline steps. `session()` loads the current `user` record (and `user_id`) into context from the session cookie; run it as `middleware()` so every pipeline can see 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 globally, gate a module's resources, and read user fields in templates. +```c +// main.c +#include +#include +#include "todos/todos.c" + +void mach(){ + session_auth_config(); + todos_config(); + + middleware(session()); + + 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 exposing three calls: `_config()` to activate, `_database(...)` to register a database, and `_query({...})` as a pipeline step. They share the `database_config` and `query_config` shapes documented in [Databases](#databases) and [query](#query); only the `.connect` string is engine-specific. + +```c +sqlite_config(); sqlite_database(.name = "...", .connect = "file:app.db?mode=rwc", ...); sqlite_query({...}); +postgres_config(); postgres_database(.name = "...", .connect = "postgres://...", ...); postgres_query({...}); +mysql_config(); mysql_database(.name = "...", .connect = "mysql://...", ...); mysql_query({...}); +redis_config(); redis_database(.name = "...", .connect = "redis://...", ...); redis_query({...}); +duckdb_config(); duckdb_database(.name = "...", .connect = "duckdb:analytics.db", ...); duckdb_query({...}); +``` + +### Static Files + +Files placed in `public/` are served directly by the framework. Reference them in templates with `{{asset:filename}}`, which resolves to a content-checksummed, cache-busted URL with immutable cache headers, so updates invalidate caches automatically while unchanged files cache forever. + +``` +public/ +├── favicon.png +├── styles.css +└── logo.svg +``` + +```html + + +Logo +``` + +This differs from templates and SQL, which are *assets* discovered from `*.mustache.html` and `*.sql` files anywhere in the project and referenced by name within pipelines (see [Modules and Composition](#modules-and-composition) for how assets are resolved to modules). `public/` holds opaque files served to the browser. + +### External Dependencies + +Drop third-party C libraries into a `/vendor` directory; 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, so anything installable in the container is available at compile and run time. + +--- + +## Architecture + +* [Data-Oriented Pipelines](#data-oriented-pipelines) +* [Multi-Reactor Architecture](#multi-reactor-architecture) +* [Safe by Default](#safe-by-default) +* [String Interpolation](#string-interpolation) + +### Data-Oriented Pipelines + +The `mach()` function runs once at boot. Its registration calls (`resource()`, `sqlite_database()`, `task()`, `middleware()`, module `_config()` calls, and so on) are processed into an execution graph with precompiled pipelines, queries, and templates. Each incoming request then executes its matching pipeline as a sequence of pre-warmed steps. + +![Boot-Time Compilation](./10-boot-time-compilation.svg) + +### Multi-Reactor Architecture + +MACH runs two types of reactors backed by a shared thread pool. The request/task/cpu ratio can be set in `compose.yml`. + +- **Request reactors** handle HTTP traffic; each gets its own dedicated CPU core and event loop. +- **Task reactors** handle background work; each gets its own dedicated core, monitors the task database for pending and incomplete tasks, and processes cron schedules. +- **Shared thread pool** handles CPU-bound and blocking I/O work on the remaining cores. + +When a pipeline executes a `worker()` step, the work is dispatched to the shared thread pool, which releases the reactor; when the call completes, the pipeline resumes on the original reactor. (An `exec()` step runs inline on the reactor for short, non-blocking logic.) The `task()` step adds jobs to the task database, where they are picked up by task reactors. Tasks can call `task()` themselves to enqueue additional work. + +Application code does not manage threads, mutexes, or locks. The architecture isolates request state to the pipeline's context. + +![Multi-Reactor Architecture](./01-multi-reactor-architecture.svg) + +### Safe by Default + +MACH prevents common C and web vulnerabilities at the framework level. + +#### Memory Safety + +Each reactor maintains a pool of arena allocators. When a request arrives, the pipeline is assigned an arena, and all allocations draw from it. When the pipeline completes, the arena is cleared and returned to the pool. Application code does not call `malloc` or `free` (it uses `allocate()` and `defer_free()` from the [Imperative API](#memory) when it needs raw buffers), which avoids leaks, double-frees, and use-after-free. + +All framework data structures (tables, records, strings) enforce bounds checking. Out-of-bounds reads and missing context values return `nullptr` rather than faulting (`table_get` past the end, `get`/`record_get` of an absent key). Pipelines that exceed their memory limit (default 5MB, configurable in `compose.yml`) abort with a 500, mitigating OOM denial-of-service. + +#### SQL Injection Prevention + +Interpolations such as `{{user_id}}` inside a query's SQL (whether a named `.query` asset or inline `.body`) 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}}` (a hidden form field) or `{{csrf:token}}` (a value for query strings); MACH sets it on an httponly, secure, samesite cookie and rejects requests whose token does not match. See [Template Helpers](#template-helpers). + +### String Interpolation + +Any string (SQL queries, URLs, connection strings, templates) can reference values from the context with `{{context_key}}`. The same scopes described in [Context](#context) apply everywhere interpolation is used. + +--- + +## Tooling + +* [Development Environment](#development-environment) +* [Introspection](#introspection) +* [Testing](#testing) +* [Debugging](#debugging) +* [Deployment](#deployment) +* [Observability](#observability) +* [Project Management](#project-management) +* [Built With](#built-with) + +### Development Environment +Built-in TUI editor with HMR, LSP support, integrated source control, and a topology-aware AI assistant. The AI uses the `app_info` command to inspect the full application topology (routes, pipelines, database schemas, event contracts, and module boundaries), so it reasons about the application's actual execution graph rather than 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 test runners for unit and end-to-end testing; no external framework setup required. +```bash +unit_tests # fast, criterion-based tests +e2e_tests # playwright-powered browser tests +``` + +### Debugging +Built-in debugging with pipeline-aware commands. Halt on individual pipeline steps, step through execution, and inspect the full pipeline context including nested tables and records. +```bash +app_debug # interactive debugger in the TUI +``` + +### Deployment +MACH deploys as a standard Docker container. It does not terminate TLS; production deployments place MACH behind a reverse proxy or load balancer (Nginx, Caddy, AWS ALB) to handle HTTPS. +```bash +app_build # outputs 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 +MACH ships with integrated project infrastructure: source control, issue tracking, wiki, forum, and a project website. + +### Built With + +| | | +|---|---| +| [C23](https://en.cppreference.com/w/c/23) | Language standard | +| [Docker](https://www.docker.com/) | Development environment, production images, stack orchestration | +| [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) / [libuv](https://libuv.org/) | HTTP server, event loops, async I/O, file watching, shared thread pool | +| [Mustach](https://gitlab.com/jobol/mustach) | Templating and string interpolation | +| [Jansson](https://github.com/akheron/jansson) | JSON parsing and generation | +| [curl](https://curl.se/) | HTTP client for fetch steps | +| [Fossil](https://fossil-scm.org/) | Source control, wiki, forum, issue tracker, project site | +| [Fresh](https://getfresh.dev/) | TUI editor | +| [clangd](https://clangd.llvm.org/) | Language server | +| [LLDB](https://lldb.llvm.org/) | Debugger | +| [Criterion](https://github.com/Snaipe/Criterion) | Unit testing | +| [Playwright](https://playwright.dev/) | End-to-end testing | +| [SigNoz](https://signoz.io/) + [OpenTelemetry](https://opentelemetry.io/) | APM, traces, logs, errors, dashboards | +| [Open Code](https://opencode.ai/) | AI assistant with custom agent and skill files | + +--- + +## License + +MACH is licensed under the [LGPL](./LICENSE).