feat(workflow): example stats page with embedded Chart.js, inline form validation errors

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-24 01:59:27 +02:00
co-authored by Claude Sonnet 5.5
parent 16a0bb0de4
commit 00af65613d
36 changed files with 1274 additions and 138 deletions
+5
View File
@@ -8,6 +8,7 @@ std::shared_ptr<fw::Application> build_application(Services& services) {
load_embedded(services);
auto app = std::make_shared<fw::Application>();
app->observe(services.stats);
app->use(fw::MiddlewareSlot::Errors, fw::errors_middleware());
app->use(fw::MiddlewareSlot::Observability, fw::request_id_middleware());
app->use(fw::MiddlewareSlot::SessionAuth,
@@ -46,6 +47,10 @@ std::shared_ptr<fw::Application> build_application(Services& services) {
register_ops_demo(ops, services);
app->include_router("", ops);
fw::Router stats;
register_stats_demo(stats, services);
app->include_router("", stats);
register_chain_demo(app, services);
return app;
}
+3
View File
@@ -14,6 +14,7 @@
#include "../fw/Kv.hpp"
#include "../fw/Net.hpp"
#include "../fw/Observ.hpp"
#include "../fw/Stats.hpp"
#include "../fw/Templates.hpp"
namespace molo::example::app {
@@ -23,6 +24,7 @@ struct Services {
std::shared_ptr<fw::Cache> cache = std::make_shared<fw::Cache>();
std::shared_ptr<fw::Pubsub> pubsub = std::make_shared<fw::Pubsub>();
std::shared_ptr<fw::EventBus> events = std::make_shared<fw::EventBus>();
std::shared_ptr<fw::Stats> stats = std::make_shared<fw::Stats>();
std::shared_ptr<fw::Metrics> metrics = std::make_shared<fw::Metrics>();
std::shared_ptr<fw::Telemetry> telemetry =
std::make_shared<fw::Telemetry>();
@@ -61,6 +63,7 @@ void register_security_demo(fw::Router& router, Services& services);
void register_formats_demo(fw::Router& router, Services& services);
void register_realtime_demo(fw::Router& router, Services& services);
void register_ops_demo(fw::Router& router, Services& services);
void register_stats_demo(fw::Router& router, Services& services);
void load_templates(Services& services);
void load_embedded(Services& services);
+14 -11
View File
@@ -1,19 +1,22 @@
#include "App.hpp"
#include "gen/assets.hpp"
namespace molo::example::app {
namespace {
// Byte-identical reproducible bundle. Production bundles are generated by
// the asset embedder CLI (09-cli-ops.md); this hand-written copy proves the
// serving path with sorted names and no timestamps.
} // namespace
// The bundle is generated at build time from example/assets by the MoloApp
// embedder (see example/example.mk, target example-assets). Names are
// sorted and byte-identical across runs.
void load_embedded(Services& services) {
services.embedded["/app.css"] =
"/* embedded bundle */\nbody{font-family:sans-serif}\n";
services.embedded["/hello.txt"] = "hello from embedded assets\n";
const gen::EmbeddedFile* files = gen::bundle_files();
for (unsigned long i = 0; i < gen::bundle_count(); ++i) {
std::string body;
body.reserve(files[i].size);
for (unsigned long c = 0; c < files[i].chunk_count; ++c)
body.append(reinterpret_cast<const char*>(files[i].chunks[c].data),
files[i].chunks[c].size);
services.embedded["/" + std::string(files[i].path)] = std::move(body);
}
}
} // namespace molo::example::app
+75
View File
@@ -0,0 +1,75 @@
#pragma once
// Shared HTML form rendering. One partial (form_page.html) draws every form:
// a summary box listing all failures with links to the fields, plus the
// message next to each invalid input. JSON clients keep the machine format.
#include <map>
#include <string>
#include <vector>
#include "../fw/Http.hpp"
#include "../fw/Templates.hpp"
#include "../fw/Validate.hpp"
namespace molo::example::app {
struct FormField {
std::string name;
std::string label;
std::string type = "text"; // text, email, number, password, textarea
std::string hint;
};
// True when the client asked for a page (browser) and not for JSON.
inline bool wants_html(const fw::Request& req) {
std::string accept = req.headers.get("Accept");
if (accept.find("text/html") != std::string::npos) return true;
return accept.find("application/json") == std::string::npos &&
req.headers.get("Content-Type").find("application/json") ==
std::string::npos;
}
struct FormView {
std::string title;
std::string action;
std::string submit = "Send";
std::string notice; // success message; hides the form when `done`
bool done = false;
std::vector<FormField> fields;
std::map<std::string, std::string> values;
const fw::ValidationError* error = nullptr;
fw::TemplateCtx ctx() const {
fw::TemplateCtx c;
c["title"] = title;
c["action"] = action;
c["submit"] = submit;
c["notice"] = notice;
c["done"] = std::string(done ? "true" : "");
std::map<std::string, std::string> by_field;
if (error) by_field = error->by_field();
fw::TemplateList rows, summary;
for (const auto& f : fields) {
auto v = values.find(f.name);
auto e = by_field.find(f.name);
std::string err = e == by_field.end() ? "" : e->second;
rows.push_back({{"name", f.name},
{"label", f.label},
{"type", f.type == "textarea" ? "" : f.type},
{"textarea", f.type == "textarea" ? "true" : ""},
{"hint", f.hint},
{"value", v == values.end() ? "" : v->second},
{"error", err},
{"invalid", err.empty() ? "" : "true"}});
if (!err.empty())
summary.push_back({{"name", f.name}, {"label", f.label}, {"message", err}});
}
c["fields"] = rows;
c["errors"] = summary;
c["error_count"] = std::string(summary.empty() ? "" : std::to_string(summary.size()));
return c;
}
};
} // namespace molo::example::app
+59 -24
View File
@@ -1,5 +1,6 @@
#include "App.hpp"
#include "FormUi.hpp"
#include "../fw/Negotiate.hpp"
#include "../fw/Router.hpp"
#include "../fw/StaticFiles.hpp"
@@ -25,6 +26,27 @@ fw::Model user_model() {
age});
}
FormView contact_view() {
FormView v;
v.title = "Contact";
v.action = "/forms/contact";
v.fields = {{"name", "Name", "text", ""},
{"email", "Email", "email", ""},
{"message", "Message", "textarea", ""}};
return v;
}
FormView user_view() {
FormView v;
v.title = "Validate a user";
v.action = "/validate/user";
v.submit = "Validate";
v.fields = {{"username", "Username", "text", "3 to 40 characters"},
{"email", "Email", "email", ""},
{"age", "Age", "number", "whole number, 0 to 150"}};
return v;
}
} // namespace
void register_formats_demo(fw::Router& router, Services& services) {
@@ -67,51 +89,64 @@ void register_formats_demo(fw::Router& router, Services& services) {
router.get("/forms/contact", "contact-get", [env](fw::Request req) {
(void)req;
fw::TemplateCtx ctx;
ctx["title"] = std::string("Contact");
ctx["posted"] = std::string("");
ctx["name"] = std::string("");
ctx["email"] = std::string("");
ctx["message"] = std::string("");
return fw::Response(200, env->render("contact.html", ctx),
FormView view = contact_view();
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.post("/forms/contact", "contact-post", [env](fw::Request req) {
router.post("/forms/contact", "contact-post", [env](fw::Request req) -> fw::Response {
fw::Form form(contact_model());
fw::TemplateCtx ctx;
ctx["title"] = std::string("Contact");
FormView view = contact_view();
try {
auto clean = form.bind(req);
ctx["posted"] = std::string("true");
ctx["name"] = clean["name"];
ctx["email"] = clean["email"];
ctx["message"] = clean["message"];
if (!wants_html(req))
return fw::JsonResponse("{\"ok\":true,\"name\":\"" +
fw::json_escape(clean["name"]) + "\"}",
200);
view.done = true;
view.notice = "Thanks " + clean["name"] + ", message received.";
} catch (const fw::ValidationError& e) {
ctx["posted"] = std::string("");
auto input = fw::parse_form(req.body);
ctx["name"] = input.count("name") ? input["name"] : "";
ctx["email"] = input.count("email") ? input["email"] : "";
ctx["message"] = input.count("message") ? input["message"] : "";
ctx["error"] = e.to_json();
return fw::Response(422, env->render("contact.html", ctx),
if (!wants_html(req)) return fw::JsonResponse(e.to_json(), 422);
view.values = fw::parse_form(req.body);
view.error = &e;
return fw::Response(422, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
return fw::Response(200, env->render("contact.html", ctx),
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.post("/validate/user", "validate-user", [](fw::Request req) {
router.get("/validate/user", "validate-user-form", [env](fw::Request req) {
(void)req;
FormView view = user_view();
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.post("/validate/user", "validate-user", [env](fw::Request req) -> fw::Response {
fw::Model model = user_model();
auto input = fw::parse_json_object_flat(req.body);
if (input.empty()) input = fw::parse_form(req.body);
const bool html = req.headers.get("Accept").find("text/html") !=
std::string::npos;
try {
auto clean = model.validate(input);
if (html) {
FormView view = user_view();
view.done = true;
view.notice = "User " + clean["username"] + " is valid.";
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
return fw::JsonResponse(
"{\"ok\":true,\"username\":\"" +
fw::json_escape(clean["username"]) + "\"}",
200);
} catch (const fw::ValidationError& e) {
return fw::JsonResponse(e.to_json(), 422);
if (!html) return fw::JsonResponse(e.to_json(), 422);
FormView view = user_view();
view.values = input;
view.error = &e;
return fw::Response(422, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
});
+98
View File
@@ -0,0 +1,98 @@
#include "App.hpp"
#include "../fw/Router.hpp"
#include "../fw/Templates.hpp"
namespace molo::example::app {
namespace {
std::string num(std::size_t v) { return std::to_string(v); }
std::string quote(const std::string& s) {
return "\"" + fw::json_escape(s) + "\"";
}
// Counts of every service the example wires, for the "services" charts.
std::string services_json(Services& s) {
std::string out = "{";
out += "\"stores\":{\"kv\":" + num(s.kv->size()) +
",\"cache\":" + num(s.cache->size()) +
",\"sessions\":" + num(s.sessions->size()) +
",\"pubsub_topics\":" + num(s.pubsub->topics().size()) +
",\"events\":" + num(s.events->delivered().size()) +
",\"spans\":" + num(s.telemetry->spans().size()) +
",\"uploads\":" + num(s.uploads->list().size()) +
",\"webdav_files\":" + num(s.webdav->size()) +
",\"replication_entries\":" + num(s.repl->latest()) +
",\"openapi_routes\":" + num(s.openapi->size()) +
",\"embedded_assets\":" + num(s.embedded.size()) + "}";
out += ",\"cache\":{\"hits\":" + std::to_string(s.cache->hits()) +
",\"misses\":" + std::to_string(s.cache->misses()) + "}";
std::size_t upload_bytes = 0;
for (const auto& u : s.uploads->list()) upload_bytes += u.size;
out += ",\"upload_bytes\":" + num(upload_bytes);
std::map<std::string, std::size_t> task_states;
for (const auto& t : s.tasks->list()) ++task_states[t.state];
out += ",\"tasks\":{";
bool first = true;
for (const auto& [k, v] : task_states) {
out += (first ? "" : ",") + quote(k) + ":" + num(v);
first = false;
}
out += "},\"workers\":[";
first = true;
for (const auto& w : s.supervisor->status()) {
out += std::string(first ? "" : ",") + "{\"name\":" + quote(w.name) +
",\"running\":" + (w.running ? "true" : "false") +
",\"restarts\":" + std::to_string(w.restarts) + "}";
first = false;
}
out += "],\"orm\":{";
first = true;
for (auto* db : {s.sqlite.get(), s.postgres.get()}) {
std::size_t rows = 0;
auto tables = db->tables();
for (const auto& t : tables) rows += db->select_all(t).rows.size();
out += std::string(first ? "" : ",") + quote(fw::backend_name(db->backend())) +
":{\"tables\":" + num(tables.size()) + ",\"rows\":" + num(rows) + "}";
first = false;
}
out += "},\"metrics\":{";
first = true;
for (const auto& [k, v] : s.metrics->snapshot()) {
out += (first ? "" : ",") + quote(k) + ":" + std::to_string(v);
first = false;
}
out += "}}";
return out;
}
} // namespace
void register_stats_demo(fw::Router& router, Services& services) {
Services* s = &services;
fw::Environment* env = services.templates.get();
router.get("/stats", "stats-page", [env](fw::Request req) {
(void)req;
fw::TemplateCtx ctx;
ctx["title"] = std::string("Statistics");
return fw::Response(200, env->render("stats.html", ctx),
"text/html; charset=utf-8");
});
router.get("/stats/data", "stats-data", [s](fw::Request req) {
(void)req;
fw::Response res(200,
"{\"http\":" + s->stats->to_json() +
",\"services\":" + services_json(*s) + "}",
"application/json");
res.headers.set("Cache-Control", "no-store");
return res;
});
}
} // namespace molo::example::app
+86 -14
View File
@@ -21,6 +21,7 @@ const char kBase[] = R"BASE(<!DOCTYPE html>
<a href="/">Index</a>
<a href="/templates/page">Templates</a>
<a href="/forms/contact">Forms</a>
<a href="/stats">Stats</a>
<a href="/docs">Docs</a>
<a href="/health">Health</a>
</nav>
@@ -30,6 +31,7 @@ const char kBase[] = R"BASE(<!DOCTYPE html>
<a href="/">Index</a>
<a href="/templates/page">Templates</a>
<a href="/forms/contact">Forms</a>
<a href="/stats">Stats</a>
<a href="/docs">Docs</a>
<a href="/health">Health</a>
</nav>
@@ -78,24 +80,93 @@ const char kPage[] = R"PAGE({% extends "base.html" %}
{% endblock %}
)PAGE";
const char kContact[] = R"CONTACT({% extends "base.html" %}
const char kFormPage[] = R"FORM({% extends "base.html" %}
{% block content %}
<h1>Contact</h1>
{% if posted %}
<p class="ok">Thanks {{ name }}, message received.</p>
<h1>{{ title }}</h1>
{% if notice %}<p class="ok" role="status">{{ notice }}</p>{% endif %}
{% if error_count %}
<div class="form-errors" role="alert">
<h2>Please fix {{ error_count }} field(s) and send again</h2>
<ul>
{% for e in errors %}
<li><a href="#f-{{ e.name }}">{{ e.label }}</a> {{ e.message }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if done %}{% else %}
<form method="post" action="{{ action }}" novalidate>
{% for f in fields %}
<div class="field{% if f.invalid %} invalid{% endif %}">
<label for="f-{{ f.name }}">{{ f.label }}</label>
{% if f.textarea %}
<textarea id="f-{{ f.name }}" name="{{ f.name }}"{% if f.invalid %} aria-invalid="true" aria-describedby="e-{{ f.name }}"{% endif %}>{{ f.value }}</textarea>
{% else %}
<form method="post" action="/forms/contact">
<label>Name <input name="name" value="{{ name }}"></label>
<label>Email <input name="email" value="{{ email }}"></label>
<label>Message <textarea name="message">{{ message }}</textarea></label>
<button type="submit">Send</button>
<input id="f-{{ f.name }}" type="{{ f.type }}" name="{{ f.name }}" value="{{ f.value }}"{% if f.invalid %} aria-invalid="true" aria-describedby="e-{{ f.name }}"{% endif %}>
{% endif %}
{% if f.hint %}<span class="hint">{{ f.hint }}</span>{% endif %}
{% if f.error %}<p class="field-error" id="e-{{ f.name }}">{{ f.error }}</p>{% endif %}
</div>
{% endfor %}
<button type="submit">{{ submit }}</button>
</form>
{% endif %}
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
{% endblock %}
)CONTACT";
)FORM";
const char kStats[] = R"STATS({% extends "base.html" %}
{% block content %}
<h1>Statistics</h1>
<p class="hint">HTTP requests, connections, and service state of this running
server. History is 15 minutes in 10 second buckets. The server stops accepting
after its connection cap, so auto refresh is off by default.</p>
<div class="toolbar">
<button type="button" id="refresh">Refresh</button>
<label class="inline"><input type="checkbox" id="auto"> Auto refresh (5 s)</label>
<span class="hint" id="t-updated">loading...</span>
</div>
<section class="tiles" aria-label="Summary">
<div class="tile"><span class="k">Uptime</span><span class="v" id="t-uptime">-</span></div>
<div class="tile"><span class="k">Requests</span><span class="v" id="t-requests">-</span></div>
<div class="tile"><span class="k">Errors</span><span class="v" id="t-errors">-</span></div>
<div class="tile"><span class="k">Avg latency</span><span class="v" id="t-avg">-</span></div>
<div class="tile"><span class="k">p95 latency</span><span class="v" id="t-p95">-</span></div>
<div class="tile"><span class="k">p99 latency</span><span class="v" id="t-p99">-</span></div>
<div class="tile"><span class="k">Bytes in</span><span class="v" id="t-in">-</span></div>
<div class="tile"><span class="k">Bytes out</span><span class="v" id="t-out">-</span></div>
<div class="tile"><span class="k">Connections</span><span class="v" id="t-conn">-</span></div>
<div class="tile"><span class="k">Active</span><span class="v" id="t-active">-</span></div>
<div class="tile"><span class="k">Timeouts / malformed</span><span class="v" id="t-timeouts">-</span></div>
<div class="tile"><span class="k">Connections left (cap)</span><span class="v" id="t-left">-</span></div>
</section>
<h2>Traffic</h2>
<div class="grid">
<figure class="chart"><figcaption>Requests and errors per 10 s</figcaption><div class="plot"><canvas id="c-requests"></canvas></div></figure>
<figure class="chart"><figcaption>Average latency per 10 s</figcaption><div class="plot"><canvas id="c-latency"></canvas></div></figure>
<figure class="chart"><figcaption>Bytes in and out per 10 s</figcaption><div class="plot"><canvas id="c-bytes"></canvas></div></figure>
<figure class="chart"><figcaption>Connections opened per 10 s</figcaption><div class="plot"><canvas id="c-conns"></canvas></div></figure>
</div>
<h2>Requests</h2>
<div class="grid">
<figure class="chart"><figcaption>Status codes</figcaption><div class="plot"><canvas id="c-status"></canvas></div></figure>
<figure class="chart"><figcaption>Methods</figcaption><div class="plot"><canvas id="c-methods"></canvas></div></figure>
<figure class="chart"><figcaption>Latency distribution</figcaption><div class="plot"><canvas id="c-hist"></canvas></div></figure>
<figure class="chart"><figcaption>Top routes</figcaption><div class="plot"><canvas id="c-routes"></canvas></div></figure>
</div>
<div class="scroll"><table id="tbl-routes"></table></div>
<h2>Services</h2>
<div class="grid">
<figure class="chart"><figcaption>Store sizes</figcaption><div class="plot tall"><canvas id="c-stores"></canvas></div></figure>
<figure class="chart"><figcaption>Cache hits and misses</figcaption><div class="plot"><canvas id="c-cache"></canvas></div></figure>
<figure class="chart"><figcaption>Tasks by state</figcaption><div class="plot"><canvas id="c-tasks"></canvas></div></figure>
<figure class="chart"><figcaption>ORM tables and rows</figcaption><div class="plot"><canvas id="c-orm"></canvas></div></figure>
</div>
<div class="scroll"><table id="tbl-workers"></table></div>
<div class="scroll"><table id="tbl-metrics"></table></div>
<script src="/embedded/chart.umd.min.js"></script>
<script src="/embedded/stats.js"></script>
{% endblock %}
)STATS";
const char kDocs[] = R"DOCS({% extends "base.html" %}
{% block content %}
@@ -125,8 +196,9 @@ void load_templates(Services& services) {
services.templates->add_template("base.html", kBase);
services.templates->add_template("index.html", kIndex);
services.templates->add_template("page.html", kPage);
services.templates->add_template("contact.html", kContact);
services.templates->add_template("form_page.html", kFormPage);
services.templates->add_template("docs.html", kDocs);
services.templates->add_template("stats.html", kStats);
services.templates->add_template("error.html", kError);
services.templates->add_template("nav_hint.html", kNavHint);
services.templates->add_global("site", "MoloApp living example");