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");
+2
View File
@@ -0,0 +1,2 @@
/* embedded bundle */
body{font-family:sans-serif}
+20
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
hello from embedded assets
+166
View File
@@ -0,0 +1,166 @@
// Statistics page: polls /stats/data and renders Chart.js charts.
// Chart.js itself is served from the embedded bundle (/embedded/chart.umd.min.js).
(function () {
"use strict";
var REFRESH_MS = 5000;
var charts = {};
var timer = null;
function css(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
function series(i) { return css("--series-" + i); }
function fmtBytes(n) {
if (n < 1024) return n + " B";
if (n < 1048576) return (n / 1024).toFixed(1) + " kB";
return (n / 1048576).toFixed(2) + " MB";
}
function fmtUptime(s) {
var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60);
return h ? h + "h " + m + "m" : m ? m + "m " + (s % 60) + "s" : s + "s";
}
function hhmmss(t) {
var d = new Date(t * 1000);
return d.toTimeString().slice(0, 8);
}
function setText(id, v) { document.getElementById(id).textContent = v; }
function draw(id, config) {
var canvas = document.getElementById(id);
if (charts[id]) {
charts[id].data = config.data;
charts[id].update("none");
return;
}
config.options = config.options || {};
config.options.responsive = true;
config.options.maintainAspectRatio = false;
config.options.animation = false;
charts[id] = new Chart(canvas, config);
}
function grid() { return { color: css("--grid") }; }
function scales(extra) {
var s = {
x: { grid: grid(), ticks: { color: css("--text-secondary"), maxTicksLimit: 6 } },
y: { grid: grid(), beginAtZero: true, ticks: { color: css("--text-secondary") } }
};
for (var k in extra) s[k] = Object.assign(s[k] || {}, extra[k]);
return s;
}
function legend() {
return { position: "bottom", labels: { color: css("--text-secondary"), boxWidth: 12 } };
}
function line(label, data, color, fill) {
return { label: label, data: data, borderColor: color, backgroundColor: color + "33",
fill: !!fill, borderWidth: 2, pointRadius: 0, pointHoverRadius: 5, tension: 0.25 };
}
function bar(label, data, color) {
return { label: label, data: data, backgroundColor: color, borderRadius: 4 };
}
function palette(n) {
var out = [];
for (var i = 1; i <= n; i++) out.push(series(((i - 1) % 8) + 1));
return out;
}
function table(id, head, rows) {
var t = document.getElementById(id);
var h = "<thead><tr>" + head.map(function (c) { return "<th>" + c + "</th>"; }).join("") + "</tr></thead><tbody>";
rows.forEach(function (r) {
h += "<tr>" + r.map(function (c) { return "<td>" + String(c).replace(/&/g, "&amp;").replace(/</g, "&lt;") + "</td>"; }).join("") + "</tr>";
});
t.innerHTML = h + (rows.length ? "" : "<tr><td colspan=\"" + head.length + "\">no data yet</td></tr>") + "</tbody>";
}
function render(d) {
var h = d.http, sv = d.services, pts = h.series.points;
var labels = pts.map(function (p) { return hhmmss(p.t); });
var errPct = h.totals.requests ? (100 * h.totals.errors / h.totals.requests) : 0;
setText("t-uptime", fmtUptime(h.uptime_sec));
setText("t-requests", h.totals.requests);
setText("t-errors", h.totals.errors + " (" + errPct.toFixed(1) + "%)");
setText("t-avg", h.totals.avg_ms.toFixed(2) + " ms");
setText("t-p95", h.latency.p95_ms.toFixed(2) + " ms");
setText("t-p99", h.latency.p99_ms.toFixed(2) + " ms");
setText("t-in", fmtBytes(h.totals.bytes_in));
setText("t-out", fmtBytes(h.totals.bytes_out));
setText("t-conn", h.connections.total);
setText("t-active", h.connections.active + " (peak " + h.connections.peak + ")");
setText("t-timeouts", h.connections.timeouts + " / " + h.connections.malformed);
var left = h.connections.cap ? Math.max(0, h.connections.cap - h.connections.total) : "n/a";
setText("t-left", left);
setText("t-updated", "updated " + new Date().toTimeString().slice(0, 8));
draw("c-requests", { type: "line", data: { labels: labels, datasets: [
line("Requests", pts.map(function (p) { return p.requests; }), series(1), true),
line("Errors", pts.map(function (p) { return p.errors; }), series(8), false)] },
options: { scales: scales({}), plugins: { legend: legend() }, interaction: { mode: "index", intersect: false } } });
draw("c-latency", { type: "line", data: { labels: labels, datasets: [
line("Avg latency (ms)", pts.map(function (p) { return p.avg_ms; }), series(2), true)] },
options: { scales: scales({}), plugins: { legend: legend() }, interaction: { mode: "index", intersect: false } } });
draw("c-bytes", { type: "line", data: { labels: labels, datasets: [
line("Bytes in", pts.map(function (p) { return p.bytes_in; }), series(3), true),
line("Bytes out", pts.map(function (p) { return p.bytes_out; }), series(7), true)] },
options: { scales: scales({}), plugins: { legend: legend() }, interaction: { mode: "index", intersect: false } } });
draw("c-conns", { type: "bar", data: { labels: labels, datasets: [
bar("Connections opened", pts.map(function (p) { return p.connections; }), series(1))] },
options: { scales: scales({}), plugins: { legend: legend() } } });
var codes = Object.keys(h.by_status);
draw("c-status", { type: "doughnut", data: { labels: codes, datasets: [{
data: codes.map(function (k) { return h.by_status[k]; }),
backgroundColor: codes.map(function (k) { return k < 300 ? series(3) : k < 400 ? series(1) : k < 500 ? series(4) : series(8); }),
borderColor: css("--surface-1"), borderWidth: 2 }] },
options: { plugins: { legend: legend() } } });
var methods = Object.keys(h.by_method);
draw("c-methods", { type: "doughnut", data: { labels: methods, datasets: [{
data: methods.map(function (k) { return h.by_method[k]; }),
backgroundColor: palette(methods.length), borderColor: css("--surface-1"), borderWidth: 2 }] },
options: { plugins: { legend: legend() } } });
draw("c-hist", { type: "bar", data: { labels: h.latency.histogram.map(function (b) { return b.bucket; }),
datasets: [bar("Requests", h.latency.histogram.map(function (b) { return b.count; }), series(1))] },
options: { scales: scales({}), plugins: { legend: { display: false } } } });
var top = h.by_route.slice(0, 10);
draw("c-routes", { type: "bar", data: { labels: top.map(function (r) { return r.route; }),
datasets: [bar("Requests", top.map(function (r) { return r.count; }), series(1)),
bar("Errors", top.map(function (r) { return r.errors; }), series(8))] },
options: { indexAxis: "y", scales: scales({}), plugins: { legend: legend() } } });
table("tbl-routes", ["Route", "Count", "Errors", "Avg ms", "Max ms", "Bytes out"],
h.by_route.map(function (r) { return [r.route, r.count, r.errors, r.avg_ms.toFixed(2), r.max_ms.toFixed(2), fmtBytes(r.bytes_out)]; }));
var st = Object.keys(sv.stores);
draw("c-stores", { type: "bar", data: { labels: st, datasets: [
bar("Entries", st.map(function (k) { return sv.stores[k]; }), series(3))] },
options: { indexAxis: "y", scales: scales({}), plugins: { legend: { display: false } } } });
draw("c-cache", { type: "doughnut", data: { labels: ["Hits", "Misses"], datasets: [{
data: [sv.cache.hits, sv.cache.misses], backgroundColor: [series(3), series(4)],
borderColor: css("--surface-1"), borderWidth: 2 }] }, options: { plugins: { legend: legend() } } });
var ts = Object.keys(sv.tasks);
draw("c-tasks", { type: "doughnut", data: { labels: ts.length ? ts : ["none"], datasets: [{
data: ts.length ? ts.map(function (k) { return sv.tasks[k]; }) : [0],
backgroundColor: palette(Math.max(ts.length, 1)), borderColor: css("--surface-1"), borderWidth: 2 }] },
options: { plugins: { legend: legend() } } });
var orm = Object.keys(sv.orm);
draw("c-orm", { type: "bar", data: { labels: orm, datasets: [
bar("Tables", orm.map(function (k) { return sv.orm[k].tables; }), series(1)),
bar("Rows", orm.map(function (k) { return sv.orm[k].rows; }), series(2))] },
options: { scales: scales({}), plugins: { legend: legend() } } });
table("tbl-workers", ["Worker", "State", "Restarts"],
sv.workers.map(function (w) { return [w.name, w.running ? "running" : "stopped", w.restarts]; }));
table("tbl-metrics", ["Metric", "Value"],
Object.keys(sv.metrics).map(function (k) { return [k, sv.metrics[k]]; }));
}
function load() {
fetch("/stats/data", { cache: "no-store" }).then(function (r) { return r.json(); })
.then(render).catch(function (e) { setText("t-updated", "load failed: " + e); });
}
function setAuto(on) {
if (timer) { clearInterval(timer); timer = null; }
if (on) timer = setInterval(load, REFRESH_MS);
}
document.getElementById("refresh").addEventListener("click", load);
document.getElementById("auto").addEventListener("change", function (e) { setAuto(e.target.checked); });
load();
})();
+49 -49
View File
@@ -24,6 +24,7 @@ EXAMPLE_SRCS = \
$(EXAMPLE_DIR)/fw/StaticFiles.cpp \
$(EXAMPLE_DIR)/fw/Tls.cpp \
$(EXAMPLE_DIR)/fw/Kv.cpp \
$(EXAMPLE_DIR)/fw/Stats.cpp \
$(EXAMPLE_DIR)/fw/Observ.cpp \
$(EXAMPLE_DIR)/fw/Data.cpp \
$(EXAMPLE_DIR)/fw/Jobs.cpp \
@@ -41,69 +42,68 @@ EXAMPLE_SRCS = \
$(EXAMPLE_DIR)/app/SecurityDemo.cpp \
$(EXAMPLE_DIR)/app/FormatsDemo.cpp \
$(EXAMPLE_DIR)/app/RealtimeDemo.cpp \
$(EXAMPLE_DIR)/app/OpsDemo.cpp
$(EXAMPLE_DIR)/app/OpsDemo.cpp \
$(EXAMPLE_DIR)/app/StatsDemo.cpp
EXAMPLE_TESTS = \
$(EXAMPLE_TESTDIR)/index_test.cpp \
$(EXAMPLE_TESTDIR)/health_test.cpp \
$(EXAMPLE_TESTDIR)/routing/hello_test.cpp \
$(EXAMPLE_TESTDIR)/routing/views_test.cpp \
$(EXAMPLE_TESTDIR)/routing/routers_test.cpp \
$(EXAMPLE_TESTDIR)/chain/deep_test.cpp \
$(EXAMPLE_TESTDIR)/orm/users_test.cpp \
$(EXAMPLE_TESTDIR)/kv/items_test.cpp \
$(EXAMPLE_TESTDIR)/cache/lookup_test.cpp \
$(EXAMPLE_TESTDIR)/pubsub/publish_test.cpp \
$(EXAMPLE_TESTDIR)/auth/login_test.cpp \
$(EXAMPLE_TESTDIR)/auth/me_test.cpp \
$(EXAMPLE_TESTDIR)/sessions/counter_test.cpp \
$(EXAMPLE_TESTDIR)/uploads/file_test.cpp \
$(EXAMPLE_TESTDIR)/forms/contact_test.cpp \
$(EXAMPLE_TESTDIR)/validate/user_test.cpp \
$(EXAMPLE_TESTDIR)/templates/page_test.cpp \
$(EXAMPLE_TESTDIR)/formats/data_test.cpp \
$(EXAMPLE_TESTDIR)/static/files_test.cpp \
$(EXAMPLE_TESTDIR)/embedded/assets_test.cpp \
$(EXAMPLE_TESTDIR)/streaming/feed_test.cpp \
$(EXAMPLE_TESTDIR)/streaming/passthrough_test.cpp \
$(EXAMPLE_TESTDIR)/ws/chat_test.cpp \
$(EXAMPLE_TESTDIR)/socketio/rooms_test.cpp \
$(EXAMPLE_TESTDIR)/sse/events_test.cpp \
$(EXAMPLE_TESTDIR)/webdav/files_test.cpp \
$(EXAMPLE_TESTDIR)/events/fire_test.cpp \
$(EXAMPLE_TESTDIR)/metrics/counters_test.cpp \
$(EXAMPLE_TESTDIR)/telemetry/trace_test.cpp \
$(EXAMPLE_TESTDIR)/supervisor/tasks_test.cpp \
$(EXAMPLE_TESTDIR)/supervisor/workers_test.cpp \
$(EXAMPLE_TESTDIR)/replication/state_test.cpp \
$(EXAMPLE_TESTDIR)/restclient/self_test.cpp \
$(EXAMPLE_TESTDIR)/openapi/docs_test.cpp \
$(EXAMPLE_TESTDIR)/cli/ai_test.cpp \
$(EXAMPLE_TESTDIR)/workflow/release_test.cpp \
$(EXAMPLE_TESTDIR)/redirect/here_test.cpp
# Tests are discovered: every tests/example/**/*_test.cpp is one route test.
EXAMPLE_TEST_JOBS ?= 8
.PHONY: example example-test example-clean
EXAMPLE_GEN = $(EXAMPLE_BUILD)/gen
EXAMPLE_EMBED_SRCS = \
src/cli/embed/asset_scanner.cpp \
src/cli/embed/embed_emitter.cpp \
src/cli/embed/gzip_stored.cpp \
src/cli/embed/mime.cpp \
src/cli/embed/sha256.cpp
EXAMPLE_ASSETS = \
$(EXAMPLE_DIR)/assets/app.css \
$(EXAMPLE_DIR)/assets/chart.umd.min.js \
$(EXAMPLE_DIR)/assets/hello.txt \
$(EXAMPLE_DIR)/assets/stats.js
EXAMPLE_INC = -I$(EXAMPLE_DIR) -I$(EXAMPLE_BUILD)
example:
.PHONY: example example-assets example-test example-clean
# Asset embedding is part of the build: example/assets (Chart.js included)
# becomes generated C++ under build/example/gen via the MoloApp embedder.
example-assets: $(EXAMPLE_GEN)/assets.cpp
$(EXAMPLE_GEN)/assets.cpp: $(EXAMPLE_ASSETS) $(EXAMPLE_DIR)/tools/embed_assets.cpp \
$(EXAMPLE_EMBED_SRCS)
mkdir -p $(EXAMPLE_GEN)
$(CXX) $(EXAMPLE_CXXFLAGS) -Isrc/cli -Isrc \
$(EXAMPLE_DIR)/tools/embed_assets.cpp $(EXAMPLE_EMBED_SRCS) \
-o $(EXAMPLE_BUILD)/embed_assets
$(EXAMPLE_BUILD)/embed_assets $(EXAMPLE_DIR)/assets \
$(EXAMPLE_GEN)/assets.cpp $(EXAMPLE_GEN)/assets.hpp molo::example::gen
example: example-assets
mkdir -p $(EXAMPLE_BUILD)/obj
for s in $(EXAMPLE_SRCS); do \
o=$(EXAMPLE_BUILD)/obj/`echo $$s | tr '/' '_'`.o; \
$(CXX) $(EXAMPLE_CXXFLAGS) -I$(EXAMPLE_DIR) -c $$s -o $$o || exit 1; \
$(CXX) $(EXAMPLE_CXXFLAGS) $(EXAMPLE_INC) -c $$s -o $$o || exit 1; \
done
$(CXX) $(EXAMPLE_CXXFLAGS) -c $(EXAMPLE_GEN)/assets.cpp \
-o $(EXAMPLE_BUILD)/obj/gen_assets.o
ar rcs $(EXAMPLE_BUILD)/libexample.a $(EXAMPLE_BUILD)/obj/*.o
$(CXX) $(EXAMPLE_CXXFLAGS) -I$(EXAMPLE_DIR) $(EXAMPLE_DIR)/main.cpp \
$(EXAMPLE_BUILD)/libexample.a -o $(EXAMPLE_BUILD)/living-server
example-test: example
rm -rf $(EXAMPLE_BUILD)/tests
mkdir -p $(EXAMPLE_BUILD)/tests
find $(EXAMPLE_TESTDIR) -name '*_test.cpp' | sort > $(EXAMPLE_BUILD)/tests/list.txt
xargs -P $(EXAMPLE_TEST_JOBS) -I{} sh -c ' \
t={}; n=`echo $$t | sed "s|$(EXAMPLE_TESTDIR)/||; s|/|_|g; s|\\.cpp$$||"`; \
b=$(EXAMPLE_BUILD)/tests/$$n; \
if $(CXX) $(EXAMPLE_CXXFLAGS) -I$(EXAMPLE_DIR) -I$(EXAMPLE_TESTDIR) \
$$t $(EXAMPLE_BUILD)/libexample.a -o $$b > $$b.log 2>&1; \
then $$b >> $$b.log 2>&1; else echo "COMPILE FAILED: $$t" >> $$b.log; false; fi; \
echo $$? > $$b.rc' < $(EXAMPLE_BUILD)/tests/list.txt
pass=0; fail=0; \
for t in $(EXAMPLE_TESTS); do \
n=`echo $$t | sed 's|$(EXAMPLE_TESTDIR)/||; s|/|_|g; s|\.cpp$$||'`; \
$(CXX) $(EXAMPLE_CXXFLAGS) -I$(EXAMPLE_DIR) -I$(EXAMPLE_TESTDIR) \
$$t $(EXAMPLE_BUILD)/libexample.a \
-o $(EXAMPLE_BUILD)/tests/$$n || exit 1; \
if $(EXAMPLE_BUILD)/tests/$$n; then pass=$$((pass+1)); \
else fail=$$((fail+1)); echo "FAIL: $$t"; fi; \
for l in `ls $(EXAMPLE_BUILD)/tests/*.log | sort`; do \
if [ "`cat $${l%.log}.rc`" = 0 ]; then pass=$$((pass+1)); \
else fail=$$((fail+1)); echo "FAIL: $$l"; cat $$l; fi; \
done; \
echo "example suite: $$pass passed, $$fail failed"; \
test $$fail -eq 0
+31 -1
View File
@@ -1,5 +1,6 @@
#include "App.hpp"
#include <chrono>
#include <stdexcept>
#include "Caps.hpp"
@@ -32,7 +33,35 @@ void Application::mount(const std::string& path,
mounts_.emplace_back(path, std::move(sub));
}
namespace {
// Pattern of the route matched for the request now being served on this
// thread; read once by dispatch() for the stats sample.
thread_local std::string g_matched_route;
} // namespace
void Application::observe(std::shared_ptr<Stats> stats) {
stats_ = std::move(stats);
}
Response Application::dispatch(Request req) {
if (!stats_) return dispatch_untimed(std::move(req));
g_matched_route.clear();
RequestSample sample;
sample.method = req.method;
sample.bytes_in = req.body.size();
auto start = std::chrono::steady_clock::now();
Response res = dispatch_untimed(std::move(req));
sample.micros = (long)std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - start)
.count();
sample.route = g_matched_route;
sample.status = res.status;
sample.bytes_out = res.body.size();
stats_->record_request(sample);
return res;
}
Response Application::dispatch_untimed(Request req) {
if (req.body.size() > caps::kMaxRequestBody)
return TextResponse("body too large", 413);
try {
@@ -77,7 +106,8 @@ Response Application::dispatch_inner(Request req, int depth) {
return target->run_chain(std::move(req), depth + 1);
}
Handler handler;
if (router_.match(req, handler)) return handler(std::move(req));
if (router_.match(req, handler, &g_matched_route))
return handler(std::move(req));
bool path_exists = false;
for (const auto& r : router_.routes()) {
std::map<std::string, std::string> params;
+7
View File
@@ -12,6 +12,7 @@
#include "Http.hpp"
#include "Router.hpp"
#include "Stats.hpp"
namespace molo::example::fw {
@@ -46,7 +47,10 @@ class Application : public std::enable_shared_from_this<Application> {
const std::string& name_prefix = "");
void mount(const std::string& path, std::shared_ptr<Application> sub);
// Outermost entry. Records one RequestSample per call when a Stats sink
// is attached with observe().
Response dispatch(Request req);
void observe(std::shared_ptr<Stats> stats);
const std::vector<Route>& routes() const;
@@ -54,6 +58,9 @@ class Application : public std::enable_shared_from_this<Application> {
Response dispatch_inner(Request req, int depth);
Response run_chain(Request req, int depth);
Response dispatch_untimed(Request req);
std::shared_ptr<Stats> stats_;
Router router_;
std::vector<std::pair<MiddlewareSlot, Middleware>> middlewares_;
std::vector<std::pair<std::string, std::shared_ptr<Application>>> mounts_;
+10
View File
@@ -269,4 +269,14 @@ std::string WebdavStore::propfind_xml(const std::string& root) const {
return out + "</D:multistatus>";
}
std::size_t SessionStore::size() const {
std::lock_guard<std::mutex> lock(mu_);
return sessions_.size();
}
std::size_t WebdavStore::size() const {
std::lock_guard<std::mutex> lock(mu_);
return files_.size();
}
} // namespace molo::example::fw
+2
View File
@@ -20,6 +20,7 @@ class SessionStore {
void put(const std::string& id, const std::string& key,
const std::string& value);
void rotate(const std::string& old_id, std::string& new_id);
std::size_t size() const;
private:
mutable std::mutex mu_;
@@ -104,6 +105,7 @@ class WebdavStore {
bool get(const std::string& path, std::string& out) const;
bool remove(const std::string& path);
std::string propfind_xml(const std::string& root) const;
std::size_t size() const;
private:
mutable std::mutex mu_;
+16 -1
View File
@@ -39,15 +39,30 @@ void Cache::put(const std::string& key, const std::string& value, long ttl_sec,
bool Cache::lookup(const std::string& key, std::string& out, long now) {
std::lock_guard<std::mutex> lock(mu_);
auto it = data_.find(key);
if (it == data_.end()) return false;
if (it == data_.end()) {
++misses_;
return false;
}
if (it->second.expires_at <= now) {
data_.erase(it);
++misses_;
return false;
}
out = it->second.value;
++hits_;
return true;
}
long Cache::hits() const {
std::lock_guard<std::mutex> lock(mu_);
return hits_;
}
long Cache::misses() const {
std::lock_guard<std::mutex> lock(mu_);
return misses_;
}
void Cache::invalidate(const std::string& key) {
std::lock_guard<std::mutex> lock(mu_);
data_.erase(key);
+4
View File
@@ -37,10 +37,14 @@ class Cache {
bool lookup(const std::string& key, std::string& out, long now);
void invalidate(const std::string& key);
std::size_t size() const;
long hits() const;
long misses() const;
private:
mutable std::mutex mu_;
std::map<std::string, CacheEntry> data_;
long hits_ = 0;
long misses_ = 0;
};
using PubsubHandler = std::function<void(const std::string& message)>;
+5
View File
@@ -47,6 +47,11 @@ double Metrics::get(const std::string& name) const {
return it == values_.end() ? 0.0 : it->second;
}
std::map<std::string, double> Metrics::snapshot() const {
std::lock_guard<std::mutex> lock(mu_);
return values_;
}
std::string Metrics::render_prometheus() const {
std::lock_guard<std::mutex> lock(mu_);
std::string out;
+1
View File
@@ -42,6 +42,7 @@ class Metrics {
void gauge(const std::string& name, double value);
double get(const std::string& name) const;
std::string render_prometheus() const;
std::map<std::string, double> snapshot() const;
private:
mutable std::mutex mu_;
+2 -1
View File
@@ -104,7 +104,7 @@ void Router::include_router(const std::string& prefix, const Router& other,
}
}
bool Router::match(Request& req, Handler& out) const {
bool Router::match(Request& req, Handler& out, std::string* pattern) const {
for (const auto& r : routes_) {
bool method_ok = false;
for (Method m : r.methods) {
@@ -118,6 +118,7 @@ bool Router::match(Request& req, Handler& out) const {
if (match_pattern(r.pattern, req.path, params)) {
for (auto& [k, v] : params) req.path_params[k] = v;
out = r.handler;
if (pattern) *pattern = r.pattern;
return true;
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ class Router {
void include_router(const std::string& prefix, const Router& other,
const std::string& name_prefix = "");
bool match(Request& req, Handler& out) const;
bool match(Request& req, Handler& out, std::string* pattern = nullptr) const;
const std::vector<Route>& routes() const;
+30 -4
View File
@@ -5,6 +5,7 @@
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <sstream>
@@ -18,6 +19,11 @@ Server::Server(std::shared_ptr<Application> app) : app_(std::move(app)) {
Server::~Server() { stop(); }
void Server::set_stats(std::shared_ptr<Stats> stats) {
stats_ = std::move(stats);
if (stats_) stats_->set_connection_cap(caps::kMaxConnections);
}
bool Server::start(const std::string& host, int port) {
if (running_) return false;
listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
@@ -87,28 +93,44 @@ void Server::loop() {
struct timeval tv{};
tv.tv_sec = caps::kServerTimeoutSec;
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
handle_one(fd);
if (stats_) stats_->connection_opened();
std::size_t bytes_in = 0, bytes_out = 0;
ConnEnd how = ConnEnd::Closed;
handle_one(fd, bytes_in, bytes_out, how);
::close(fd);
if (stats_) stats_->connection_closed(how, bytes_in, bytes_out);
++served;
}
// The accept loop stops at the cap; the listener stays open but unserved.
if (stats_ && served >= caps::kMaxConnections) stats_->connection_rejected();
}
void Server::handle_one(int fd) {
void Server::handle_one(int fd, std::size_t& bytes_in,
std::size_t& bytes_out, ConnEnd& how) {
std::string raw;
char buf[4096];
while (raw.size() < caps::kMaxHeaderBytes) {
ssize_t n = ::recv(fd, buf, sizeof(buf), 0);
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
how = ConnEnd::Timeout;
if (n <= 0) break;
bytes_in += (std::size_t)n;
raw.append(buf, (std::size_t)n);
if (raw.find("\r\n\r\n") != std::string::npos) break;
}
std::size_t hdr_end = raw.find("\r\n\r\n");
if (hdr_end == std::string::npos) return;
if (hdr_end == std::string::npos) {
if (how == ConnEnd::Closed) how = ConnEnd::Malformed;
return;
}
std::string head = raw.substr(0, hdr_end);
std::string rest = raw.substr(hdr_end + 4);
std::istringstream lines(head);
std::string line;
if (!std::getline(lines, line)) return;
if (!std::getline(lines, line)) {
how = ConnEnd::Malformed;
return;
}
if (!line.empty() && line.back() == '\r') line.pop_back();
std::istringstream rl(line);
std::string method_s, target, version;
@@ -148,7 +170,10 @@ void Server::handle_one(int fd) {
while (req.body.size() < content_length &&
req.body.size() < caps::kMaxRequestBody) {
ssize_t n = ::recv(fd, buf, sizeof(buf), 0);
if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
how = ConnEnd::Timeout;
if (n <= 0) break;
bytes_in += (std::size_t)n;
req.body.append(buf, (std::size_t)n);
}
Response res = app_->dispatch(std::move(req));
@@ -172,6 +197,7 @@ void Server::handle_one(int fd) {
ssize_t n = ::send(fd, wire.data() + sent, wire.size() - sent, 0);
if (n <= 0) break;
sent += (std::size_t)n;
bytes_out += (std::size_t)n;
}
}
+5 -1
View File
@@ -22,6 +22,8 @@ class Server {
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
// Optional sink for connection counters; set before start().
void set_stats(std::shared_ptr<Stats> stats);
bool start(const std::string& host, int port);
void stop();
int port() const;
@@ -29,9 +31,11 @@ class Server {
private:
void loop();
void handle_one(int fd);
void handle_one(int fd, std::size_t& bytes_in, std::size_t& bytes_out,
ConnEnd& how);
std::shared_ptr<Application> app_;
std::shared_ptr<Stats> stats_;
int listen_fd_ = -1;
int port_ = 0;
std::atomic<bool> running_{false};
+218
View File
@@ -0,0 +1,218 @@
#include "Stats.hpp"
#include <algorithm>
#include <cstdio>
namespace molo::example::fw {
namespace {
// Upper bounds in microseconds; the last bucket is open-ended.
constexpr std::array<long, 7> kBounds = {500, 1000, 5000, 10000,
50000, 100000, 500000};
std::string quote(const std::string& s) { return "\"" + json_escape(s) + "\""; }
} // namespace
Stats::Stats() {
ring_.reserve(stats_caps::kLatencyRing);
started_ = now();
}
void Stats::set_clock(long (*now_sec)()) {
std::lock_guard<std::mutex> lock(mu_);
clock_ = now_sec;
}
long Stats::now() const {
if (clock_) return clock_();
return (long)std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
}
Stats::Bucket& Stats::bucket_for(long slot) {
Bucket& b = buckets_[(std::size_t)(slot % (long)stats_caps::kBuckets)];
if (b.slot != slot) {
b = Bucket{};
b.slot = slot;
}
return b;
}
void Stats::record_request(const RequestSample& s) {
std::lock_guard<std::mutex> lock(mu_);
const bool failed = s.status >= 400;
++requests_;
if (failed) ++errors_;
bytes_in_ += (long)s.bytes_in;
bytes_out_ += (long)s.bytes_out;
micros_ += s.micros;
++by_method_[method_name(s.method)];
++by_status_[s.status];
std::string key = s.route.empty() ? "(unmatched)" : s.route;
if (!by_route_.count(key) && by_route_.size() >= stats_caps::kMaxRoutes)
key = "(other)";
RouteStat& r = by_route_[key];
++r.count;
if (failed) ++r.errors;
r.micros += s.micros;
r.max_micros = std::max(r.max_micros, s.micros);
r.bytes_out += (long)s.bytes_out;
std::size_t h = 0;
while (h < kBounds.size() && s.micros >= kBounds[h]) ++h;
++histogram_[h];
if (ring_.size() < stats_caps::kLatencyRing) {
ring_.push_back(s.micros);
} else {
ring_[ring_next_] = s.micros;
ring_next_ = (ring_next_ + 1) % stats_caps::kLatencyRing;
}
Bucket& b = bucket_for(now() / stats_caps::kBucketSec);
++b.requests;
if (failed) ++b.errors;
b.bytes_in += (long)s.bytes_in;
b.bytes_out += (long)s.bytes_out;
b.micros += s.micros;
}
void Stats::connection_opened() {
std::lock_guard<std::mutex> lock(mu_);
++conn_total_;
++conn_active_;
conn_peak_ = std::max(conn_peak_, conn_active_);
++bucket_for(now() / stats_caps::kBucketSec).connections;
}
void Stats::connection_closed(ConnEnd how, std::size_t in, std::size_t out) {
std::lock_guard<std::mutex> lock(mu_);
if (conn_active_ > 0) --conn_active_;
if (how == ConnEnd::Timeout) ++conn_timeout_;
if (how == ConnEnd::Malformed) ++conn_malformed_;
conn_bytes_in_ += (long)in;
conn_bytes_out_ += (long)out;
}
void Stats::connection_rejected() {
std::lock_guard<std::mutex> lock(mu_);
++conn_rejected_;
}
void Stats::set_connection_cap(long cap) {
std::lock_guard<std::mutex> lock(mu_);
conn_cap_ = cap;
}
long Stats::total_requests() const {
std::lock_guard<std::mutex> lock(mu_);
return requests_;
}
long Stats::total_connections() const {
std::lock_guard<std::mutex> lock(mu_);
return conn_total_;
}
long Stats::active_connections() const {
std::lock_guard<std::mutex> lock(mu_);
return conn_active_;
}
std::string Stats::to_json() const {
std::lock_guard<std::mutex> lock(mu_);
const long t = now();
auto num = [](long v) { return std::to_string(v); };
auto dbl = [](double v) {
char buf[48];
std::snprintf(buf, sizeof(buf), "%.3f", v);
return std::string(buf);
};
std::string out = "{";
out += "\"generated_at\":" + num(t) + ",\"uptime_sec\":" + num(t - started_);
out += ",\"totals\":{\"requests\":" + num(requests_) +
",\"errors\":" + num(errors_) + ",\"bytes_in\":" + num(bytes_in_) +
",\"bytes_out\":" + num(bytes_out_) + ",\"avg_ms\":" +
dbl(requests_ ? micros_ / 1000.0 / (double)requests_ : 0.0) + "}";
out += ",\"by_method\":{";
bool first = true;
for (const auto& [k, v] : by_method_) {
out += (first ? "" : ",") + quote(k) + ":" + num(v);
first = false;
}
out += "},\"by_status\":{";
first = true;
for (const auto& [k, v] : by_status_) {
out += (first ? "" : ",") + quote(std::to_string(k)) + ":" + num(v);
first = false;
}
out += "},\"by_route\":[";
std::vector<std::pair<std::string, RouteStat>> routes(by_route_.begin(),
by_route_.end());
std::sort(routes.begin(), routes.end(), [](const auto& a, const auto& b) {
return a.second.count > b.second.count;
});
first = true;
for (const auto& [k, r] : routes) {
out += std::string(first ? "" : ",") + "{\"route\":" + quote(k) +
",\"count\":" + num(r.count) + ",\"errors\":" + num(r.errors) +
",\"avg_ms\":" + dbl(r.micros / 1000.0 / (double)r.count) +
",\"max_ms\":" + dbl(r.max_micros / 1000.0) +
",\"bytes_out\":" + num(r.bytes_out) + "}";
first = false;
}
out += "]";
static const char* kLabels[8] = {"<0.5ms", "<1ms", "<5ms", "<10ms",
"<50ms", "<100ms", "<500ms", ">=500ms"};
out += ",\"latency\":{\"histogram\":[";
for (std::size_t i = 0; i < histogram_.size(); ++i)
out += std::string(i ? "," : "") + "{\"bucket\":" + quote(kLabels[i]) +
",\"count\":" + num(histogram_[i]) + "}";
std::vector<long> sorted = ring_;
std::sort(sorted.begin(), sorted.end());
auto pct = [&](double p) {
if (sorted.empty()) return 0.0;
std::size_t idx = (std::size_t)(p * (double)(sorted.size() - 1));
return sorted[idx] / 1000.0;
};
out += "],\"p50_ms\":" + dbl(pct(0.50)) + ",\"p95_ms\":" + dbl(pct(0.95)) +
",\"p99_ms\":" + dbl(pct(0.99)) + ",\"samples\":" +
num((long)sorted.size()) + "}";
out += ",\"connections\":{\"total\":" + num(conn_total_) +
",\"active\":" + num(conn_active_) + ",\"peak\":" + num(conn_peak_) +
",\"timeouts\":" + num(conn_timeout_) + ",\"malformed\":" +
num(conn_malformed_) + ",\"rejected\":" + num(conn_rejected_) +
",\"cap\":" + num(conn_cap_) + ",\"bytes_in\":" +
num(conn_bytes_in_) + ",\"bytes_out\":" + num(conn_bytes_out_) + "}";
// Oldest first, one entry per bucket slot including empty ones.
const long cur = t / stats_caps::kBucketSec;
const long n = (long)stats_caps::kBuckets;
out += ",\"series\":{\"bucket_sec\":" + num(stats_caps::kBucketSec) +
",\"points\":[";
for (long i = n - 1; i >= 0; --i) {
const long slot = cur - i;
const Bucket& b = buckets_[(std::size_t)(slot % n)];
const bool live = b.slot == slot;
const long reqs = live ? b.requests : 0;
out += std::string(i == n - 1 ? "" : ",") + "{\"t\":" +
num(slot * stats_caps::kBucketSec) +
",\"requests\":" + num(reqs) +
",\"errors\":" + num(live ? b.errors : 0) +
",\"bytes_in\":" + num(live ? b.bytes_in : 0) +
",\"bytes_out\":" + num(live ? b.bytes_out : 0) +
",\"avg_ms\":" + dbl(reqs ? b.micros / 1000.0 / (double)reqs : 0.0) +
",\"connections\":" + num(live ? b.connections : 0) + "}";
}
out += "]}}";
return out;
}
} // namespace molo::example::fw
+108
View File
@@ -0,0 +1,108 @@
#pragma once
// Request and connection statistics behind /stats. One mutex, fixed-size
// storage, static caps: 90 ten-second buckets (15 min of history), 256
// distinct routes, a 1024-sample latency ring. Everything past a cap is
// counted under "(other)" or dropped oldest-first, never grown.
// Gap: real export (Prometheus, OTel) lives in 02-observability.md.
#include <array>
#include <chrono>
#include <cstddef>
#include <map>
#include <mutex>
#include <string>
#include <vector>
#include "Http.hpp"
namespace molo::example::fw {
namespace stats_caps {
inline constexpr std::size_t kBuckets = 90;
inline constexpr long kBucketSec = 10;
inline constexpr std::size_t kMaxRoutes = 256;
inline constexpr std::size_t kLatencyRing = 1024;
} // namespace stats_caps
struct RequestSample {
Method method = Method::Get;
std::string route; // matched pattern, empty when no route matched
int status = 200;
std::size_t bytes_in = 0;
std::size_t bytes_out = 0;
long micros = 0;
};
enum class ConnEnd { Closed, Timeout, Malformed };
class Stats {
public:
Stats();
void record_request(const RequestSample& sample);
void connection_opened();
void connection_closed(ConnEnd how, std::size_t bytes_in,
std::size_t bytes_out);
void connection_rejected();
void set_connection_cap(long cap);
// Test hook: current time in seconds; defaults to the wall clock.
void set_clock(long (*now_sec)());
// JSON document consumed by the /stats page: totals, by_method, by_status,
// by_route, latency histogram + percentiles, connections, time series.
std::string to_json() const;
long total_requests() const;
long total_connections() const;
long active_connections() const;
private:
struct Bucket {
long slot = -1; // epoch seconds / kBucketSec; -1 = unused
long requests = 0;
long errors = 0;
long bytes_in = 0;
long bytes_out = 0;
long micros = 0;
long connections = 0;
};
struct RouteStat {
long count = 0;
long errors = 0;
long micros = 0;
long max_micros = 0;
long bytes_out = 0;
};
long now() const;
Bucket& bucket_for(long slot);
mutable std::mutex mu_;
long (*clock_)() = nullptr;
long started_ = 0;
long requests_ = 0;
long errors_ = 0;
long bytes_in_ = 0;
long bytes_out_ = 0;
long micros_ = 0;
std::map<std::string, long> by_method_;
std::map<int, long> by_status_;
std::map<std::string, RouteStat> by_route_;
std::array<long, 8> histogram_{};
std::vector<long> ring_;
std::size_t ring_next_ = 0;
std::array<Bucket, stats_caps::kBuckets> buckets_{};
long conn_total_ = 0;
long conn_active_ = 0;
long conn_peak_ = 0;
long conn_timeout_ = 0;
long conn_malformed_ = 0;
long conn_rejected_ = 0;
long conn_cap_ = 0;
long conn_bytes_in_ = 0;
long conn_bytes_out_ = 0;
};
} // namespace molo::example::fw
+51 -10
View File
@@ -129,6 +129,43 @@ std::string Environment::render_source(const std::string& name,
return render_blocks(src, ctx, depth);
}
namespace {
// Position of the "{% <close> %}" matching an already-open tag, honoring
// nested "{% <open> ... %}" tags of the same kind. When else_pos is given it
// receives the depth-zero "{% else %}" position (npos if none).
std::size_t find_matching(const std::string& src, std::size_t from,
const std::string& open, const std::string& close,
std::size_t* else_pos = nullptr) {
int depth = 0;
if (else_pos) *else_pos = std::string::npos;
std::size_t i = from;
while (true) {
std::size_t t = src.find("{%", i);
if (t == std::string::npos) return std::string::npos;
std::size_t e = src.find("%}", t);
if (e == std::string::npos) return std::string::npos;
std::size_t a = t + 2;
while (a < e && src[a] == ' ') ++a;
std::size_t b = e;
while (b > a && src[b - 1] == ' ') --b;
std::string tag = src.substr(a, b - a);
if (tag.rfind(open + " ", 0) == 0) {
++depth;
} else if (tag == close) {
if (depth == 0) return t;
--depth;
} else if (tag == "else" && depth == 0 && else_pos &&
*else_pos == std::string::npos) {
*else_pos = t;
}
i = e + 2;
}
}
} // namespace
std::string Environment::render_blocks(const std::string& src, TemplateCtx& ctx,
int depth) const {
std::string out;
@@ -185,16 +222,20 @@ std::string Environment::render_blocks(const std::string& src, TemplateCtx& ctx,
std::string tag = trim(src.substr(t + 2, e - t - 2));
if (tag.rfind("if ", 0) == 0) {
std::string cond = trim(tag.substr(3));
std::size_t end = src.find("{% endif %}", e);
std::size_t els_pos = std::string::npos;
std::size_t end = find_matching(src, e + 2, "if", "endif", &els_pos);
if (end == std::string::npos) break;
std::string inner = src.substr(e + 2, end - e - 2);
std::size_t els = inner.find("{% else %}");
std::string yes = els == std::string::npos ? inner
: inner.substr(0, els);
std::string no =
els == std::string::npos ? "" : inner.substr(els + 10);
std::size_t close_end = src.find("%}", end) + 2;
std::string yes, no;
if (els_pos == std::string::npos) {
yes = src.substr(e + 2, end - e - 2);
} else {
yes = src.substr(e + 2, els_pos - e - 2);
no = src.substr(src.find("%}", els_pos) + 2,
end - src.find("%}", els_pos) - 2);
}
out += render_blocks(ctx_truthy(ctx, cond) ? yes : no, ctx, depth + 1);
i = end + 11;
i = close_end;
} else if (tag.rfind("for ", 0) == 0) {
std::string rest = trim(tag.substr(4));
std::size_t in = rest.find(" in ");
@@ -204,7 +245,7 @@ std::string Environment::render_blocks(const std::string& src, TemplateCtx& ctx,
std::string list = in == std::string::npos
? ""
: trim(rest.substr(in + 4));
std::size_t end = src.find("{% endfor %}", e);
std::size_t end = find_matching(src, e + 2, "for", "endfor");
if (end == std::string::npos) break;
std::string inner = src.substr(e + 2, end - e - 2);
auto it = ctx.find(list);
@@ -220,7 +261,7 @@ std::string Environment::render_blocks(const std::string& src, TemplateCtx& ctx,
}
}
}
i = end + 12;
i = src.find("%}", end) + 2;
} else if (tag.rfind("include ", 0) == 0) {
std::string rest = trim(tag.substr(8));
if (rest.size() >= 2 && rest.front() == '"') {
+18 -7
View File
@@ -15,6 +15,12 @@ const std::vector<FieldError>& ValidationError::failures() const {
return failures_;
}
std::map<std::string, std::string> ValidationError::by_field() const {
std::map<std::string, std::string> out;
for (const auto& f : failures_) out.emplace(f.field, f.message);
return out;
}
std::string ValidationError::to_json() const {
std::string out = "{\"error\":\"validation_error\",\"failures\":[";
bool first = true;
@@ -70,30 +76,35 @@ std::map<std::string, std::string> Model::validate(
if (!f.default_value.empty()) clean[f.name] = f.default_value;
continue;
}
failures.push_back({f.name, "field is required"});
failures.push_back({f.name, "is required"});
continue;
}
if (f.type != FieldType::Integer && value.size() < f.min_len)
failures.push_back({f.name, "too short"});
failures.push_back(
{f.name, "must be at least " + std::to_string(f.min_len) +
" characters"});
else if (f.type != FieldType::Integer && value.size() > f.max_len)
failures.push_back({f.name, "too long"});
failures.push_back(
{f.name, "must be at most " + std::to_string(f.max_len) +
" characters"});
else if (f.type == FieldType::Integer) {
long n = 0;
if (!parse_long(value, n)) {
failures.push_back({f.name, "not an integer"});
failures.push_back({f.name, "must be a whole number"});
} else if (f.has_range && (n < f.min_value || n > f.max_value)) {
failures.push_back({f.name, "out of range"});
failures.push_back({f.name, "must be between " + std::to_string(f.min_value) +
" and " + std::to_string(f.max_value)});
} else {
clean[f.name] = value;
}
continue;
} else if (f.type == FieldType::Email && !looks_like_email(value)) {
failures.push_back({f.name, "not an email address"});
failures.push_back({f.name, "must be a valid email address"});
continue;
} else if (f.type == FieldType::Boolean &&
value != "true" && value != "false" && value != "1" &&
value != "0") {
failures.push_back({f.name, "not a boolean"});
failures.push_back({f.name, "must be true or false"});
continue;
} else {
clean[f.name] = value;
+2
View File
@@ -38,6 +38,8 @@ class ValidationError : public HttpError {
explicit ValidationError(std::vector<FieldError> failures);
const std::vector<FieldError>& failures() const;
std::string to_json() const;
// First failure per field, for inline display next to each input.
std::map<std::string, std::string> by_field() const;
private:
std::vector<FieldError> failures_;
+1
View File
@@ -22,6 +22,7 @@ int main(int argc, char** argv) {
molo::example::app::Services services;
auto app = molo::example::app::build_application(services);
molo::example::fw::Server server(app);
server.set_stats(services.stats);
if (!server.start("127.0.0.1", port)) {
std::cerr << "bind failed\n";
return 1;
+60 -7
View File
@@ -1,6 +1,28 @@
/* Living example stylesheet: mobile-first, responsive by default. */
/* Living example stylesheet: mobile-first, responsive by default.
Chart palette: validated categorical slots (light and dark). */
:root {
color-scheme: light dark;
--surface-1: #fcfcfb; --text-primary: #0b0b0b; --text-secondary: #52514e;
--grid: #e4e3df; --border: #ccc; --danger: #a00; --danger-bg: #fdecec;
--ok: #0a6b0a;
--series-1: #2a78d6; --series-2: #eb6834; --series-3: #1baf7a;
--series-4: #eda100; --series-5: #e87ba4; --series-6: #008300;
--series-7: #6250d6; --series-8: #e34948;
}
@media (prefers-color-scheme: dark) {
:root {
--surface-1: #1a1a19; --text-primary: #f0efec; --text-secondary: #c3c2b7;
--grid: #3a3a37; --border: #4a4a46; --danger: #ff8f8f; --danger-bg: #3a1c1c;
--ok: #6fd36f;
--series-1: #3987e5; --series-2: #d95926; --series-3: #199e70;
--series-4: #c98500; --series-5: #d55181; --series-6: #008300;
--series-7: #9085e9; --series-8: #e66767;
}
}
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5;
background: var(--surface-1); color: var(--text-primary); }
a { color: var(--series-1); }
.topbar { display: flex; align-items: center; gap: 1rem; padding: 0.5rem 1rem;
background: #102030; color: #fff; }
.brand { color: #fff; font-weight: bold; text-decoration: none; }
@@ -8,15 +30,46 @@ body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; }
.nav-wide a { color: #cde; text-decoration: none; }
.nav-narrow { margin-left: auto; }
.nav-narrow nav { display: flex; flex-direction: column; gap: 0.25rem;
background: #fff; padding: 0.5rem; border: 1px solid #ccc; }
background: var(--surface-1); padding: 0.5rem; border: 1px solid var(--border); }
main { padding: 1rem; max-width: 60rem; margin: 0 auto; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 0.25rem 0.5rem; text-align: left; }
th, td { border: 1px solid var(--border); padding: 0.25rem 0.5rem; text-align: left; }
form { display: flex; flex-direction: column; gap: 0.5rem; max-width: 28rem; }
input, textarea, button { font-size: 1rem; padding: 0.4rem; }
.ok { color: #0a0; }
.error { color: #a00; }
.hint { color: #555; }
.ok { color: var(--ok); }
.error { color: var(--danger); }
.hint { color: var(--text-secondary); }
code { overflow-wrap: anywhere; }
/* Forms: inline field errors plus a summary box. */
.field { display: flex; flex-direction: column; gap: 0.2rem; }
.field input, .field textarea { border: 1px solid var(--border);
background: var(--surface-1); color: inherit; border-radius: 4px; }
.field.invalid input, .field.invalid textarea { border-color: var(--danger);
border-width: 2px; }
.field-error { color: var(--danger); font-size: 0.9rem; margin: 0; }
.field-error::before { content: "\26A0\00a0"; }
.form-errors { border: 2px solid var(--danger); background: var(--danger-bg);
border-radius: 4px; padding: 0.5rem 0.75rem; max-width: 28rem; }
.form-errors h2 { margin: 0 0 0.25rem; font-size: 1rem; color: var(--danger); }
.form-errors ul { margin: 0; padding-left: 1.25rem; }
label.inline { flex-direction: row; align-items: center; gap: 0.4rem; display: inline-flex; }
label.inline input { padding: 0; }
/* Statistics page */
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; margin-bottom: 0.75rem; }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(9.5rem, 1fr)); gap: 0.5rem; }
.tile { border: 1px solid var(--border); border-radius: 6px; padding: 0.4rem 0.6rem;
display: flex; flex-direction: column; min-width: 0; }
.tile .k { color: var(--text-secondary); font-size: 0.8rem; }
.tile .v { font-size: 1.25rem; font-weight: 600; overflow-wrap: anywhere; }
.grid { display: grid; grid-template-columns: 1fr; gap: 1rem; }
.chart { margin: 0; border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; min-width: 0; }
.chart figcaption { color: var(--text-secondary); font-size: 0.9rem; margin-bottom: 0.25rem; }
.plot { position: relative; height: 14rem; }
.plot.tall { height: 22rem; }
.scroll { overflow-x: auto; margin: 0.75rem 0; }
@media (min-width: 48rem) { .grid { grid-template-columns: 1fr 1fr; } }
/* Big button group becomes a dropdown on small phones: the details element
above is the dropdown; on wide screens show the plain link row. */
@media (min-width: 48rem) {
+34
View File
@@ -0,0 +1,34 @@
// Build-time helper: embeds example/assets into generated C++ using the
// MoloApp embedder (src/cli/embed). Same engine as `molo embed`, without the
// CLI's database and TLS link dependencies.
// Usage: embed_assets <asset-dir> <out.cpp> <out.hpp> <namespace>
#include <iostream>
#include <string>
#include "embed/asset_scanner.hpp"
#include "embed/embed_emitter.hpp"
int main(int argc, char** argv) {
if (argc != 5) {
std::cerr << "usage: embed_assets <dir> <out.cpp> <out.hpp> <namespace>\n";
return 2;
}
molo::embed::AssetScanner scanner;
molo::embed::ScanResult scanned = scanner.scan(argv[1]);
if (!scanned.ok()) {
std::cerr << scanned.error << "\n";
return 1;
}
molo::embed::EmitOptions opts;
opts.namespc = argv[4];
molo::embed::EmbedEmitter emitter;
std::string error;
if (!emitter.emit(scanned.files, argv[2], argv[3], opts, error)) {
std::cerr << error << "\n";
return 1;
}
std::cout << "embedded " << scanned.files.size() << " files ("
<< scanned.total_bytes << " bytes)\n";
return 0;
}
+22 -6
View File
@@ -1,21 +1,37 @@
// Route: /forms/contact (form render plus validation)
// Route: /forms/contact (form render plus validation shown inline)
#include "support/Assert.hpp"
using namespace molo::example::test;
int main() {
Fixture f;
const char* form_type = "application/x-www-form-urlencoded";
auto form = f.client->get("/forms/contact");
check(form.status == 200, "form renders 200");
check(contains(form.body, "<form"), "form markup present");
check(!contains(form.body, "form-errors"), "fresh form has no error box");
auto ok = f.client->post("/forms/contact",
"name=ada&email=ada@x.io&message=hi",
"application/x-www-form-urlencoded");
"name=ada&email=ada@x.io&message=hi", form_type);
check(ok.status == 200, "valid post is 200");
check(contains(ok.body, "Thanks ada"), "success page names user");
auto bad = f.client->post("/forms/contact", "name=ada",
"application/x-www-form-urlencoded");
auto bad = f.client->post("/forms/contact", "name=ada&email=nope", form_type);
check(bad.status == 422, "invalid post is 422");
check(contains(bad.body, "validation_error"), "failures listed");
check(contains(bad.body, "<form"), "form is shown again");
check(contains(bad.body, "form-errors"), "summary box rendered");
check(contains(bad.body, "Please fix 2 field(s)"), "summary counts failures");
check(contains(bad.body, "must be a valid email address"),
"email message inline");
check(contains(bad.body, "id=\"e-message\""), "message error attached");
check(contains(bad.body, "aria-invalid=\"true\""), "invalid input flagged");
check(contains(bad.body, "value=\"ada\""), "valid input kept on redisplay");
check(!contains(bad.body, "validation_error"), "no raw JSON in the page");
check(!contains(bad.body, "{&quot;"), "no escaped JSON in the page");
auto api = f.client->request(
molo::example::fw::Method::Post, "/forms/contact", "name=ada",
{{"Content-Type", form_type}, {"Accept", "application/json"}});
check(api.status == 422, "json client gets 422");
check(contains(api.body, "validation_error"), "json client gets failures");
return finish("forms/contact");
}
+29
View File
@@ -0,0 +1,29 @@
// Route: GET /stats/data (request, connection, and service statistics)
#include "support/Assert.hpp"
using namespace molo::example::test;
int main() {
Fixture f;
f.client->get("/health");
f.client->get("/health");
f.client->get("/no/such/route");
f.client->post("/forms/contact", "name=ada",
"application/x-www-form-urlencoded");
auto res = f.client->get("/stats/data");
check(res.status == 200, "status 200");
check(contains(res.headers.get("Content-Type"), "application/json"), "json");
check(contains(res.body, "\"requests\":4"), "four requests before this one");
check(contains(res.body, "\"errors\":2"), "404 and 422 counted as errors");
check(contains(res.body, "\"404\":1") && contains(res.body, "\"422\":1"),
"status breakdown");
check(contains(res.body, "\"/health\""), "route pattern grouped");
check(contains(res.body, "\"(unmatched)\""), "unmatched bucket");
check(contains(res.body, "\"POST\":1") && contains(res.body, "\"GET\":3"),
"method breakdown");
check(contains(res.body, "\"p95_ms\""), "latency percentiles");
check(contains(res.body, "\"connections\""), "connection block");
check(contains(res.body, "\"series\""), "time series");
check(f.services.stats->total_requests() == 5, "side effect: 5 recorded");
return finish("stats/data");
}
+24
View File
@@ -0,0 +1,24 @@
// Route: GET /stats (Chart.js page; library comes from the embedded bundle)
#include "support/Assert.hpp"
using namespace molo::example::test;
int main() {
Fixture f;
auto page = f.client->get("/stats");
check(page.status == 200, "status 200");
check(contains(page.headers.get("Content-Type"), "text/html"), "html");
check(contains(page.body, "<canvas id=\"c-requests\""), "request chart");
check(contains(page.body, "<canvas id=\"c-conns\""), "connection chart");
check(contains(page.body, "/embedded/chart.umd.min.js"), "chart.js linked");
auto lib = f.client->get("/embedded/chart.umd.min.js");
check(lib.status == 200, "chart.js served");
check(lib.headers.get("X-Asset-Source") == "embedded", "from the bundle");
check(contains(lib.body, "Chart.js v"), "real chart.js build embedded");
auto js = f.client->get("/embedded/stats.js");
check(js.status == 200 && contains(js.body, "/stats/data"), "page script");
check(f.client->request(molo::example::fw::Method::Post, "/stats").status ==
405,
"post is 405");
return finish("stats/page");
}
+15 -1
View File
@@ -1,4 +1,4 @@
// Route: POST /validate/user (all-failures validation error)
// Route: /validate/user (all-failures validation, JSON and HTML form)
#include "support/Assert.hpp"
using namespace molo::example::test;
@@ -17,5 +17,19 @@ int main() {
check(contains(bad.body, "username"), "username failure listed");
check(contains(bad.body, "email"), "missing email listed");
check(contains(bad.body, "age"), "bad age listed");
auto page = f.client->get("/validate/user");
check(page.status == 200, "form page is 200");
check(contains(page.body, "name=\"username\""), "username input");
auto html = f.client->request(
molo::example::fw::Method::Post, "/validate/user",
"username=ad&email=x&age=200",
{{"Content-Type", "application/x-www-form-urlencoded"},
{"Accept", "text/html"}});
check(html.status == 422, "browser post is 422");
check(contains(html.body, "Please fix 3 field(s)"), "all three listed");
check(contains(html.body, "must be at least 3 characters"), "username text");
check(contains(html.body, "must be between 0 and 150"), "age text");
check(!contains(html.body, "validation_error"), "no raw JSON in the page");
return finish("validate/user");
}