#include #include #include #include #include "App.hpp" #include "FormUi.hpp" #include "../fw/Cookies.hpp" #include "../fw/Platform.hpp" #include "../fw/Router.hpp" #include "../fw/Templates.hpp" #include "../fw/Validate.hpp" namespace molo::example::app { namespace { namespace pc = fw::platform_caps; std::string esc(const std::string& s) { return fw::html_escape(s); } bool parse_long_in(const std::string& s, long lo, long hi, long& out) { if (s.empty() || s.size() > 12) return false; std::size_t i = (s[0] == '-') ? 1 : 0; if (i == s.size()) return false; for (std::size_t k = i; k < s.size(); ++k) if (s[k] < '0' || s[k] > '9') return false; out = std::atol(s.c_str()); return out >= lo && out <= hi; } // All state of this feature group lives here, shared by the route lambdas. class PlatformDemo { public: PlatformDemo(Services& services) : env_(services.templates.get()), prom_(services.metrics.get(), services.stats.get()) { env_->add_template( "platform_page.html", "{% extends \"base.html\" %}{% block content %}

{{ title }}

" "{{ body|safe }}{% endblock %}"); seed_catalog(); for (const char* t : {"templates", "embedded-assets", "seed-data"}) health_.add_startup_task(t, true); for (const char* c : {"database", "cache", "workers"}) health_.add_check(c, true); seed_di(); logs_.log(fw::LogLevel::Info, "platform demo ready", "boot"); doc_ = "Conditional GET demo document.\n0123456789abcdefghijklmnopqrstuvwxyz\n"; } void mount(fw::Router& r); private: fw::Response page(const std::string& title, const std::string& body, int status = 200) const { fw::TemplateCtx ctx; ctx["title"] = title; ctx["body"] = body; return fw::Response(status, env_->render("platform_page.html", ctx), "text/html; charset=utf-8"); } fw::Response form_page(const FormView& v, int status = 200) const { return fw::Response(status, env_->render("form_page.html", v.ctx()), "text/html; charset=utf-8"); } static fw::Response json(const std::string& body, int status = 200) { fw::Response r(status, body, "application/json"); r.headers.set("Cache-Control", "no-store"); return r; } static fw::Response see_other(const std::string& to) { fw::Response r(303, "", "text/plain; charset=utf-8"); r.headers.set("Location", to); return r; } fw::Response invalid(const FormView& base, const fw::Request& req, const fw::ValidationError& e) const { if (!wants_html(req)) return json(e.to_json(), 422); FormView v = base; v.values = fw::parse_form(req.body); v.error = &e; return form_page(v, 422); } static std::string corr(const fw::Request& req) { std::string c = req.headers.get("X-Correlation-ID"); return c.empty() ? req.correlation_id : c; } void seed_catalog(); void seed_di(); void mount_i18n(fw::Router& r); void mount_http(fw::Router& r); void mount_ops(fw::Router& r); void mount_observability(fw::Router& r); void mount_app(fw::Router& r); void mount_expose(fw::Router& r); fw::Environment* env_; fw::MessageCatalog catalog_; fw::HealthRegistry health_; fw::PrometheusExporter prom_; fw::LogRing logs_; fw::TraceContextFactory trace_; fw::ServiceRegistry di_; fw::ExposeStats expose_; std::mutex doc_mu_; std::string doc_; std::shared_ptr instance_counter_ = std::make_shared(0); }; void PlatformDemo::seed_catalog() { catalog_.add("en", "welcome", {"Welcome"}); catalog_.add("en", "items", {"%d item", "%d items"}); catalog_.add("nl", "welcome", {"Welkom"}); catalog_.add("nl", "items", {"%d item", "%d items"}); catalog_.add("de", "welcome", {"Willkommen"}); catalog_.add("de", "items", {"%d Artikel", "%d Artikel"}); catalog_.add("fr", "welcome", {"Bienvenue"}); catalog_.add("fr", "items", {"%d article", "%d articles"}); catalog_.add("ru", "welcome", {"Добро пожаловать"}); catalog_.add("ru", "items", {"%d предмет", "%d предмета", "%d предметов"}); catalog_.add("ja", "welcome", {"ようこそ"}); catalog_.add("ja", "items", {"%d 個"}); } void PlatformDemo::seed_di() { auto counter = instance_counter_; auto make = [counter](std::string prefix) { return [counter, prefix]() { return prefix + "#" + std::to_string(++*counter); }; }; di_.add("config", fw::Lifetime::Singleton, make("Config")); di_.add("logger", fw::Lifetime::Singleton, make("Logger")); di_.add("request-context", fw::Lifetime::Scoped, make("RequestContext")); di_.add("mailer", fw::Lifetime::Transient, make("Mailer")); } void PlatformDemo::mount_i18n(fw::Router& r) { r.get("/i18n", "i18n-page", [this](fw::Request req) { std::string lang_param = req.query_or("lang", ""); std::string accept = req.headers.get("Accept-Language"); std::string locale = fw::negotiate_locale(lang_param, accept, catalog_); std::string source = catalog_.has_locale(fw::negotiate_locale(lang_param, "", catalog_)) && !lang_param.empty() && fw::negotiate_locale(lang_param, "", catalog_) == locale ? "?lang parameter" : (locale != catalog_.default_locale() ? "Accept-Language header" : "default"); std::string n_text = req.query_or("n", "3"); long n = 0; std::string n_error; if (!parse_long_in(n_text, 0, pc::kMaxPluralN, n)) n_error = "must be a whole number from 0 to " + std::to_string(pc::kMaxPluralN); std::string body = "

Active locale: " + esc(locale) + " (from " + source + ")

"; body += "
" "
"; if (!n_error.empty()) body += "

" + esc(n_error) + "

"; body += "
"; if (n_error.empty()) { body += "

" + esc(catalog_.translate(locale, "welcome")) + "

"; body += "

" + esc(catalog_.translate(locale, "items", n)) + "

"; body += "

Plural form " + std::to_string(fw::PluralRule::index(locale, n)) + " of " + std::to_string(fw::PluralRule::forms(locale)) + ".

"; } body += "

Switch: "; for (const auto& l : catalog_.locales()) body += "" + l + " "; body += "

catalog as .po

"; fw::Response res = page("Internationalisation", body, n_error.empty() ? 200 : 422); res.headers.set("Content-Language", locale); res.headers.set("Vary", "Accept-Language"); return res; }); r.get("/i18n/po", "i18n-po", [this](fw::Request req) { std::string locale = req.query_or("lang", "en"); if (!catalog_.has_locale(locale)) return fw::Response(404, "unknown locale\n", "text/plain; charset=utf-8"); return fw::Response(200, catalog_.to_po(locale), "text/plain; charset=utf-8"); }); } void PlatformDemo::mount_http(fw::Router& r) { r.get("/compress/demo", "compress-demo", [](fw::Request req) { long size = 2000; if (req.query.count("size") && !parse_long_in(req.query_or("size", ""), 0, (long)pc::kMaxCompressBody, size)) return fw::Response(422, "size must be 0 to " + std::to_string(pc::kMaxCompressBody) + "\n", "text/plain; charset=utf-8"); std::string body; const std::string unit = "MoloApp compresses repetitive text well. "; while ((long)body.size() < size) body += unit; body.resize((std::size_t)size); fw::Response res(200, body, "text/plain; charset=utf-8"); res.headers.set("Vary", "Accept-Encoding"); res.headers.set("X-Original-Length", std::to_string(body.size())); if (body.size() >= pc::kCompressMin && fw::accepts_encoding(req.headers.get("Accept-Encoding"), "gzip")) { res.body = fw::gzip_stored(body); res.headers.set("Content-Encoding", "gzip"); } return res; }); r.get("/conditional/doc", "conditional-get", [this](fw::Request req) { std::string doc; { std::lock_guard lock(doc_mu_); doc = doc_; } std::string etag = fw::make_etag(doc); fw::Response res(200, doc, "text/plain; charset=utf-8"); res.headers.set("ETag", etag); res.headers.set("Accept-Ranges", "bytes"); res.headers.set("Cache-Control", "no-cache"); if (fw::etag_matches(req.headers.get("If-None-Match"), etag)) { res.status = 304; res.body.clear(); return res; } fw::ByteRange range = fw::parse_range(req.headers.get("Range"), doc.size()); if (range.kind == fw::ByteRange::Kind::Unsatisfiable) { res.status = 416; res.body.clear(); res.headers.set("Content-Range", "bytes */" + std::to_string(doc.size())); } else if (range.kind == fw::ByteRange::Kind::Ok) { res.status = 206; res.body = doc.substr(range.first, range.last - range.first + 1); res.headers.set("Content-Range", "bytes " + std::to_string(range.first) + "-" + std::to_string(range.last) + "/" + std::to_string(doc.size())); } return res; }); r.post("/conditional/doc", "conditional-put", [this](fw::Request req) { if (req.body.size() > pc::kMaxDocBytes) return json("{\"error\":\"too_large\",\"max\":" + std::to_string(pc::kMaxDocBytes) + "}", 413); if (req.body.empty()) return json("{\"error\":\"validation\",\"message\":\"body is required\"}", 422); std::lock_guard lock(doc_mu_); std::string match = req.headers.get("If-Match"); if (!match.empty() && !fw::etag_matches(match, fw::make_etag(doc_))) return json("{\"error\":\"precondition_failed\",\"etag\":\"" + fw::json_escape(fw::make_etag(doc_)) + "\"}", 412); doc_ = req.body; fw::Response res = json("{\"bytes\":" + std::to_string(doc_.size()) + "}"); res.headers.set("ETag", fw::make_etag(doc_)); return res; }); } void PlatformDemo::mount_ops(fw::Router& r) { r.get("/healthz", "healthz", [this](fw::Request) { return json(health_.liveness_json()); }); r.get("/readyz", "readyz", [this](fw::Request) { return json(health_.readiness_json(), health_.ready() ? 200 : 503); }); r.get("/startupz", "startupz", [this](fw::Request) { return json(health_.startup_json(), health_.startup_complete() ? 200 : 503); }); r.post("/readyz/checks/{name}", "readyz-toggle", [this](fw::Request req) { std::string state = req.query_or("state", ""); if (state != "up" && state != "down") return json("{\"error\":\"validation\",\"message\":\"state must be up or down\"}", 422); if (!health_.set_check(req.param_or("name", ""), state == "up")) return json("{\"error\":\"not_found\",\"message\":\"unknown check\"}", 404); return json(health_.readiness_json(), health_.ready() ? 200 : 503); }); r.post("/startupz/tasks/{name}", "startupz-toggle", [this](fw::Request req) { std::string state = req.query_or("state", ""); if (state != "done" && state != "pending") return json("{\"error\":\"validation\",\"message\":\"state must be done or pending\"}", 422); if (!health_.set_startup_task(req.param_or("name", ""), state == "done")) return json("{\"error\":\"not_found\",\"message\":\"unknown task\"}", 404); return json(health_.startup_json(), health_.startup_complete() ? 200 : 503); }); r.get("/metrics", "prometheus", [this](fw::Request) { return fw::Response(200, prom_.render(), "text/plain; version=0.0.4; charset=utf-8"); }); } void PlatformDemo::mount_observability(fw::Router& r) { auto emit_view = []() { FormView v; v.title = "Write a log record"; v.action = "/logging/emit"; v.submit = "Log"; v.fields = {{"level", "Level", "text", "debug, info, warn or error"}, {"message", "Message", "text", "secrets like password=x are redacted"}}; return v; }; r.get("/logging/emit", "logging-form", [this, emit_view](fw::Request) { return form_page(emit_view()); }); r.post("/logging/emit", "logging-emit", [this, emit_view](fw::Request req) { auto input = fw::parse_form(req.body); if (req.headers.get("Content-Type").find("application/json") != std::string::npos) input = fw::parse_json_object_flat(req.body); std::vector fails; fw::LogLevel level = fw::LogLevel::Info; if (input["level"].empty()) fails.push_back({"level", "is required"}); else if (!fw::parse_level(input["level"], level)) fails.push_back({"level", "must be debug, info, warn or error"}); if (input["message"].empty()) fails.push_back({"message", "is required"}); else if (input["message"].size() > 300) fails.push_back({"message", "must be at most 300 characters"}); if (!fails.empty()) return invalid(emit_view(), req, fw::ValidationError(fails)); logs_.log(level, input["message"], corr(req)); if (!wants_html(req)) return json("{\"ok\":true,\"size\":" + std::to_string(logs_.size()) + "}"); return see_other("/logging/records"); }); r.get("/logging/records", "logging-records", [this](fw::Request req) { long n = 20; fw::LogLevel min = fw::LogLevel::Debug; if (req.query.count("n") && !parse_long_in(req.query_or("n", ""), 1, 100, n)) return page("Log records", "

n must be a whole number from 1 to 100

", 422); if (req.query.count("level") && !fw::parse_level(req.query_or("level", ""), min)) return page("Log records", "

level must be debug, info, warn or error

", 422); auto recs = logs_.last((std::size_t)n, min); if (req.query_or("format", "") == "json") { std::string out; for (const auto& rec : recs) out += fw::LogRing::to_json(rec) + "\n"; return fw::Response(200, out, "application/x-ndjson"); } std::string body = "

Ring keeps the last " + std::to_string(pc::kLogRing) + " records (now " + std::to_string(logs_.size()) + "). Showing " + std::to_string(recs.size()) + ". Write one, " "JSON lines.

" "
" ""; for (const auto& rec : recs) body += ""; body += "
#LevelMessageCorrelation
" + std::to_string(rec.seq) + "" + fw::level_name(rec.level) + "" + esc(rec.message) + "" + esc(rec.correlation_id) + "
"; return page("Log records", body); }); r.get("/context/trace", "context-trace", [this](fw::Request req) { fw::TraceContext ctx = trace_.from_header(req.headers.get("traceparent")); std::string cid = corr(req); std::string out = "{\"correlation_id\":\"" + fw::json_escape(cid) + "\",\"continued\":" + (ctx.parent_span_id.empty() ? "false" : "true") + ",\"parent_valid\":" + (ctx.parent_valid ? "true" : "false") + ",\"trace_id\":\"" + ctx.trace_id + "\",\"parent_span_id\":\"" + ctx.parent_span_id + "\",\"span_id\":\"" + ctx.span_id + "\",\"traceparent\":\"" + ctx.traceparent() + "\"}"; fw::Response res = json(out); res.headers.set("traceparent", ctx.traceparent()); res.headers.set("X-Correlation-ID", cid); return res; }); } void PlatformDemo::mount_app(fw::Router& r) { r.get("/di/services", "di-services", [this](fw::Request) { std::string body = "
" ""; for (const auto& e : di_.list()) body += ""; body += "
ServiceLifetimeCreatedResolved
" + esc(e.name) + "" + fw::lifetime_name(e.lifetime) + "" + std::to_string(e.created) + "" + std::to_string(e.resolved) + "

Singletons are built once, scoped once per " "?scope= key, transients on every resolve.

"; return page("Dependency injection", body); }); r.get("/di/resolve/{name}", "di-resolve", [this](fw::Request req) { std::string name = req.param_or("name", ""); std::string instance; if (!di_.resolve(name, req.query_or("scope", "default"), instance)) return json("{\"error\":\"not_found\",\"message\":\"unknown service\"}", 404); return json("{\"name\":\"" + fw::json_escape(name) + "\",\"instance\":\"" + fw::json_escape(instance) + "\"}"); }); FormView flash_view; flash_view.title = "Set a flash message"; flash_view.action = "/flash/set"; flash_view.submit = "Save and redirect"; flash_view.fields = {{"message", "Message", "text", "shown once on the next page"}}; r.get("/flash/set", "flash-form", [this, flash_view](fw::Request) { return form_page(flash_view); }); r.post("/flash/set", "flash-set", [this, flash_view](fw::Request req) { fw::Model model({{"message", fw::FieldType::String, true, 1, 120, 0, 0, false, ""}}); std::map clean; try { clean = fw::Form(model).bind(req); } catch (const fw::ValidationError& e) { return invalid(flash_view, req, e); } std::string cookie = fw::make_set_cookie("flash", fw::FlashCodec::encode(clean["message"]), "/", true, false, "Lax", 60); fw::Response res = wants_html(req) ? see_other("/flash") : json("{\"ok\":true}"); res.headers.set("Set-Cookie", cookie); return res; }); r.get("/flash", "flash-show", [this](fw::Request req) { std::string msg; bool has = fw::FlashCodec::decode(req.cookie_or("flash", ""), msg); std::string body; if (has) body += "

" + esc(msg) + "

"; else body += "

No flash message. It is shown once after a POST.

"; body += "

Set a message

"; fw::Response res = page("Flash messages", body); if (has) res.headers.set("Set-Cookie", fw::make_set_cookie("flash", "", "/", true, false, "Lax", 0)); return res; }); r.any({fw::Method::Get, fw::Method::Post}, "/middleware/demo", "middleware-demo", [this](fw::Request req) { std::vector chain; chain.push_back([](fw::Request q, fw::Next next) { // secure headers fw::Response res = next(std::move(q)); res.headers.set("X-Content-Type-Options", "nosniff"); res.headers.set("X-Frame-Options", "DENY"); res.headers.set("Referrer-Policy", "no-referrer"); return res; }); chain.push_back([](fw::Request q, fw::Next next) { // body limit if (q.body.size() > 64) return fw::Response(413, "{\"error\":\"too_large\",\"max\":64}", "application/json"); return next(std::move(q)); }); chain.push_back([](fw::Request q, fw::Next next) { // timing auto t0 = std::chrono::steady_clock::now(); fw::Response res = next(std::move(q)); long us = (long)std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count(); res.headers.set("X-Response-Time-Us", std::to_string(us)); return res; }); fw::Next end = [this](fw::Request q) { return page("Middleware builtins", "

This response passed through three builtin middlewares: secure headers, " "body limit (64 bytes) and timing. Inspect the response headers.

" "

Received " + std::to_string(q.body.size()) + " body bytes.

"); }; for (std::size_t i = chain.size(); i > 0; --i) { fw::Middleware mw = chain[i - 1]; fw::Next inner = end; end = [mw, inner](fw::Request q) { return mw(std::move(q), inner); }; } return end(std::move(req)); }); r.get("/cli/commands", "cli-commands", [this](fw::Request req) { static const std::vector> cmds = { {"new", "Scaffold a project (Makefile, AGENTS.md, .env.json, assets, templates, locales, git init)."}, {"serve", "Dev server; --reload watches and rebuilds."}, {"build", "Build, optionally embedding assets first."}, {"embed", "Turn a static dir into constexpr C++ arrays, optionally gzip."}, {"migrate", "Preview (--check) or apply (--apply) database migrations."}, {"health", "Local liveness and readiness summary."}, {"supervisor", "start, stop, restart, status, logs."}, {"task", "enqueue, retry, cancel, inspect on the background queue."}, {"ai", "new and continue: the AI agent."}, {"expose", "serve, agent, list, stats, expose-key: reverse tunnels."}, {"verify", "Offline artifact verification."}, {"supply-check", "Pin and advisory gate."}, {"release", "Ordered release gate."}, {"rollout", "Staged deploys."}, {"rollback", "Revert a rollout."}, {"experiment", "Chaos and experiments."}, {"debug", "Debug helpers."}}; if (!wants_html(req)) { std::string out = "{\"commands\":["; for (std::size_t i = 0; i < cmds.size(); ++i) out += std::string(i ? "," : "") + "{\"name\":\"" + cmds[i].first + "\",\"summary\":\"" + fw::json_escape(cmds[i].second) + "\"}"; return json(out + "]}"); } std::string body = "

Run molo help <command> for full help.

" "
" ""; for (const auto& [n, s] : cmds) body += ""; body += "
CommandWhat it does
molo " + n + "" + esc(s) + "
"; return page("molo commands", body); }); } void PlatformDemo::mount_expose(fw::Router& r) { FormView view; view.title = "Record a tunnel request"; view.action = "/expose/record"; view.submit = "Record"; view.fields = {{"method", "Method", "text", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"}, {"bytes_up", "Bytes up", "number", "0 to 1000000000"}, {"bytes_down", "Bytes down", "number", "0 to 1000000000"}, {"micros", "Latency (microseconds)", "number", "0 to 60000000"}}; r.get("/expose/record", "expose-form", [this, view](fw::Request) { return form_page(view); }); r.post("/expose/record", "expose-record", [this, view](fw::Request req) { fw::Model model( {{"method", fw::FieldType::String, true, 3, 7, 0, 0, false, ""}, {"bytes_up", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""}, {"bytes_down", fw::FieldType::Integer, true, 0, 0, 0, 1000000000, true, ""}, {"micros", fw::FieldType::Integer, true, 0, 0, 0, 60000000, true, ""}}); std::map c; try { c = fw::Form(model).bind(req); if (!fw::ExposeStats::known_method(c["method"])) throw fw::ValidationError({{"method", "must be an HTTP method in capitals"}}); } catch (const fw::ValidationError& e) { return invalid(view, req, e); } expose_.record(c["method"], std::stoul(c["bytes_up"]), std::stoul(c["bytes_down"]), std::stoul(c["micros"])); if (!wants_html(req)) return json("{\"ok\":true}"); return see_other("/expose/stats"); }); r.get("/expose/stats", "expose-stats", [this](fw::Request req) { auto snap = expose_.snapshot(); auto kb = [](unsigned long b) { char x[32]; std::snprintf(x, sizeof x, "%.1f", b / 1024.0); return std::string(x); }; auto f2 = [](double v) { char x[32]; std::snprintf(x, sizeof x, "%.2f", v); return std::string(x); }; if (!wants_html(req)) { std::string out = "{\"methods\":{"; bool first = true; for (const auto& [m, row] : snap) { out += std::string(first ? "" : ",") + "\"" + m + "\":{\"count\":" + std::to_string(row.count) + ",\"kb_up\":" + kb(row.bytes_up) + ",\"kb_down\":" + kb(row.bytes_down) + ",\"kb_s_up\":" + f2(row.kb_s_up) + ",\"kb_s_down\":" + f2(row.kb_s_down) + ",\"avg_ms\":" + f2(row.avg_ms()) + "}"; first = false; } return json(out + "}}"); } std::string body = "

Mirror of molo expose stats. Rates are a " "60 second window. Record a request.

" "
" "" ""; for (const auto& [m, row] : snap) body += ""; body += "
MethodCountkB upkB downkB/s upkB/s downAvg ms
" + m + "" + std::to_string(row.count) + "" + kb(row.bytes_up) + "" + kb(row.bytes_down) + "" + f2(row.kb_s_up) + "" + f2(row.kb_s_down) + "" + f2(row.avg_ms()) + "
"; return page("Expose stats", body); }); } void PlatformDemo::mount(fw::Router& r) { mount_i18n(r); mount_http(r); mount_ops(r); mount_observability(r); mount_app(r); mount_expose(r); } } // namespace void register_platform_demo(fw::Router& router, Services& services) { auto demo = std::make_shared(services); // Routes capture the raw pointer; the router owner keeps `demo` alive by // holding it in a static-lifetime registry below (bounded: one per app). static std::vector> keep; if (keep.size() >= 64) throw std::runtime_error("platform demo instance cap"); keep.push_back(demo); demo->mount(router); services.add_feature("i18n", "/i18n"); services.add_feature("gzip compression", "/compress/demo"); services.add_feature("conditional GET and ranges", "/conditional/doc"); services.add_feature("liveness probe", "/healthz"); services.add_feature("readiness probe", "/readyz"); services.add_feature("startup gate", "/startupz"); services.add_feature("prometheus metrics", "/metrics"); services.add_feature("structured logging", "/logging/records"); services.add_feature("trace context", "/context/trace"); services.add_feature("DI container", "/di/services"); services.add_feature("flash messages", "/flash"); services.add_feature("middleware builtins", "/middleware/demo"); services.add_feature("expose stats", "/expose/stats"); services.add_feature("CLI commands", "/cli/commands"); } } // namespace molo::example::app