Files
moloapp/src/app/app/application.h
T
retoor 3c4334cec9 feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security,
data, app, realtime, supervisor, clients, CLI, example plus
enterprise tenancy, audit, operability, governance,
supplychain. Postgres via docker compose for tests.
2026-10-23 18:20:04 +02:00

529 lines
20 KiB
C++

#pragma once
// Spec: molo::app::app::Application. Composition root (plan 05, E3): owns
// the router, middleware chain, DI container, template environment, error
// handler, session store seam and plugin registry. include_router merges a
// router under a prefix; mount nests a sub-application with automatic path
// merge (triple nesting yields /app1/app1/app1). startup() validates names
// (unique after merge; mounted names gain the mount alias prefix),
// converters (fail fast at add), DI cycles and caps, then runs lifespan
// hooks and plugin hooks. handle() matches the route before the chain runs
// so all middleware sees route info, forks a request DI scope, runs parent
// chain outer plus mount chains inner, validates bindings, and invokes the
// handler. 404/405/422 precedence follows Router::match.
#include <ctime>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "../../governance/problem.h"
#include "../../governance/versions/ApiVersion.h"
#include "../async/task.h"
#include "../caps.h"
#include "../di/container.h"
#include "../errors/handler.h"
#include "../errors/http_error.h"
#include "../forms/form.h"
#include "../http_msg/request.h"
#include "../http_msg/response.h"
#include "../middleware/builtins.h"
#include "../middleware/chain.h"
#include "../routing/router.h"
#include "../seams/request_id.h"
#include "../seams/session.h"
#include "../templates/environment.h"
#include "../validate/errors.h"
#include "../validate/model.h"
#include "../validate/value.h"
#include "../views/flash.h"
#include "plugin.h"
namespace molo::app::app {
class StartupError : public std::runtime_error {
public:
explicit StartupError(const std::string& msg) : std::runtime_error(msg) {}
};
class Application;
struct Mount {
std::string prefix;
std::string name_prefix;
std::shared_ptr<Application> sub;
};
struct Resolved {
Application* owner = nullptr;
const routing::Route* route = nullptr;
std::map<std::string, std::string> params;
std::vector<std::string> allow;
std::vector<validate::FieldFailure> path_errors;
std::vector<const Mount*> levels;
};
class Application {
public:
Application()
: error_handler_(std::make_shared<errors::ErrorHandler>()),
sessions_(seams::default_session_store()) {
// ExceptionMapping is outermost by construction. Negotiation runs around
// the terminal dispatch (see run_mount_levels), not in the chain, so it
// stays innermost no matter when user layers register.
chain_.use(std::make_shared<middleware::ExceptionMappingMiddleware>(error_handler_));
error_handler_->set_render_hook([this](int status, const std::string& code) {
last_error_code_ = code;
plugins_.fire_error_render(this, status, code);
});
}
routing::Router& router() { return router_; }
middleware::Chain& chain() { return chain_; }
di::Container& di() { return di_; }
templates::Environment& templates_env() { return templates_; }
errors::ErrorHandler& error_handler() { return *error_handler_; }
PluginRegistry& plugins() { return plugins_; }
std::shared_ptr<seams::SessionStore> sessions() { return sessions_; }
void set_session_store(std::shared_ptr<seams::SessionStore> store) {
sessions_ = std::move(store);
}
const std::string& last_error_code() const { return last_error_code_; }
void include_router(const std::string& prefix, const routing::Router& router,
const std::vector<std::string>& tags = {}) {
if (started_) throw StartupError("cannot include_router after startup");
router_.include_router(prefix, router, tags);
}
void mount(std::string prefix, std::shared_ptr<Application> sub, std::string alias = "") {
if (started_) throw StartupError("cannot mount after startup");
if (prefix.empty() || prefix[0] != '/') {
throw StartupError("mount prefix must start with /");
}
while (prefix.size() > 1 && prefix.back() == '/') prefix.pop_back();
if (sub->depth() + 1 > caps::kMaxSubAppNestingDepth) {
throw StartupError("sub-app nesting exceeds depth cap at '" + prefix + "'");
}
Mount m;
m.prefix = prefix;
if (!alias.empty()) {
m.name_prefix = alias;
} else if (prefix == "/") {
m.name_prefix = "root";
} else {
m.name_prefix = prefix.substr(1);
for (char& c : m.name_prefix) {
if (c == '/') c = '_';
}
}
m.sub = std::move(sub);
mounts_.push_back(std::move(m));
}
void on_startup(std::function<void(Application&)> hook) {
startup_hooks_.push_back(std::move(hook));
}
void on_shutdown(std::function<void(Application&)> hook) {
shutdown_hooks_.push_back(std::move(hook));
}
void startup() {
if (started_) return;
for (const Mount& m : mounts_) m.sub->startup();
if (total_routes() > caps::kMaxRoutesPerApp) {
throw StartupError("too many routes in application");
}
std::vector<std::pair<std::string, std::string>> names;
collect_names("", names);
std::map<std::string, std::vector<std::string>> by_name;
for (const auto& kv : names) by_name[kv.first].push_back(kv.second);
for (const auto& kv : by_name) {
if (kv.second.size() > 1) {
std::string msg = "duplicate route name '" + kv.first + "' at paths:";
for (const auto& p : kv.second) msg += " '" + p + "'";
throw StartupError(msg);
}
}
di_.validate_no_cycles();
try {
router_.validate_governance();
} catch (const std::runtime_error& e) {
throw StartupError(e.what());
}
gov_sunsets_ = CollectGovSunsets(router_);
for (const routing::Route& route : router_.routes()) {
if (!route.is_slash_redirect() && !route.options().name.empty()) {
plugins_.fire_route_added(this, route);
}
}
for (auto& hook : startup_hooks_) hook(*this);
plugins_.fire_app_started(this);
router_.freeze();
started_ = true;
}
void shutdown() {
if (!started_) return;
for (auto& hook : shutdown_hooks_) hook(*this);
for (const Mount& m : mounts_) m.sub->shutdown();
started_ = false;
}
bool started() const { return started_; }
async::Task<http_msg::Response> handle(http_msg::Request& req) {
if (!started_) startup();
// Governance: a sunset-version match answers 410 instead of 404.
if (IsSunsetVersion(req.path())) {
const auto problem = ::molo::govern::Problem::VersionGone();
http_msg::Response res(410);
res.set_content_type(std::string(::molo::govern::Problem::kContentType));
res.set_body(problem.to_json_string());
co_return res;
}
if (req.request_id().empty()) {
std::string rid = req.headers().get(seams::kRequestIdHeader);
req.set_request_id(rid.empty() ? seams::generate_request_id() : rid);
}
// Resolve runs before the chain so every middleware sees route info.
// Resolve-time failures (414 on overlong paths) render here so they
// still get the exact error shape, request ID echo and plugin hooks.
Resolved rr;
try {
rr = resolve_with_method(req.method(), req.path());
} catch (const errors::HttpError& e) {
req.set_app(this);
http_msg::Response early = error_handler_->render(e, req, req.request_id());
early.headers().set(seams::kRequestIdHeader, req.request_id());
co_return early;
} catch (const std::exception& e) {
req.set_app(this);
http_msg::Response early = error_handler_->render_unknown(req, req.request_id(), e.what());
early.headers().set(seams::kRequestIdHeader, req.request_id());
co_return early;
}
if (rr.route != nullptr) {
req.set_route(rr.route);
for (const auto& kv : rr.params) req.set_path_param(kv.first, kv.second);
req.set_app(rr.owner);
} else {
req.set_app(this);
}
// Request DI scope: lives for this call, cleared before returning so
// the scope ends at response completion (R8). Background handoff must
// copy values out; the scope pointer is not valid after handle().
auto scope = std::make_shared<di::RequestScope>(
rr.owner != nullptr ? &rr.owner->di_ : &di_);
req.set_ext("di", scope);
std::function<async::Task<http_msg::Response>(http_msg::Request&)> terminal =
[this, rr](http_msg::Request& r) -> async::Task<http_msg::Response> {
co_return co_await run_mount_levels(r, rr, 0);
};
http_msg::Response res = co_await chain_.run(req, terminal);
req.clear_ext("di");
co_return res;
}
std::string url_for(const std::string& name,
const std::map<std::string, std::string>& params = {},
const std::string& query = "") const {
if (router_.has_route_name(name)) return router_.url_for(name, params, query);
for (const Mount& m : mounts_) {
std::string head = m.name_prefix + ":";
if (name.size() > head.size() && name.substr(0, head.size()) == head) {
std::string rest = name.substr(head.size());
std::string sub_url = m.sub->url_for(rest, params, query);
if (m.prefix == "/") return sub_url;
return m.prefix + sub_url;
}
}
throw errors::NotFound("url_for: unknown route '" + name + "'");
}
std::size_t depth() const {
std::size_t deep = 0;
for (const Mount& m : mounts_) {
std::size_t d = m.sub->depth();
if (d > deep) deep = d;
}
return 1 + deep;
}
std::size_t total_routes() const {
std::size_t n = router_.size();
for (const Mount& m : mounts_) n += m.sub->total_routes();
return n;
}
void collect_names(const std::string& prefix,
std::vector<std::pair<std::string, std::string>>& out) const {
for (const routing::Route& route : router_.routes()) {
if (route.is_slash_redirect() || route.options().name.empty()) continue;
out.emplace_back(prefix + route.options().name, route.pattern());
}
for (const Mount& m : mounts_) {
std::vector<std::pair<std::string, std::string>> sub;
m.sub->collect_names(m.name_prefix + ":", sub);
for (const auto& kv : sub) out.emplace_back(prefix + kv.first, m.prefix + kv.second);
}
}
static di::RequestScope* di_scope(http_msg::Request& req) {
auto* holder = req.get_ext<std::shared_ptr<di::RequestScope>>("di");
if (holder == nullptr || holder->get() == nullptr) {
throw errors::InternalError("no DI scope bound to request");
}
return holder->get();
}
// Method-aware resolve used by handle(). Public for tests.
Resolved resolve_with_method(http_msg::Method method, const std::string& path) const {
Resolved out;
routing::MatchResult own = router_.match(method, path);
if (own.route != nullptr) {
out.owner = const_cast<Application*>(this);
out.route = own.route;
out.params = std::move(own.params);
return out;
}
bool have_mount_405 = false;
bool have_mount_422 = false;
Resolved mount_best;
for (const Mount& m : mounts_) {
bool hit = (path == m.prefix) || (m.prefix == "/" && !path.empty()) ||
(m.prefix != "/" && path.size() > m.prefix.size() &&
path.substr(0, m.prefix.size()) == m.prefix && path[m.prefix.size()] == '/');
if (!hit) continue;
std::string sub_path =
(m.prefix == "/") ? path : path.substr(m.prefix.size());
if (sub_path.empty()) sub_path = "/";
Resolved sub = m.sub->resolve_with_method(method, sub_path);
if (sub.route != nullptr) {
sub.levels.insert(sub.levels.begin(), &m);
return sub;
}
if (!have_mount_405 && !sub.allow.empty()) {
mount_best = sub;
have_mount_405 = true;
} else if (!have_mount_405 && !have_mount_422 && !sub.path_errors.empty()) {
mount_best = sub;
have_mount_422 = true;
}
}
if (!own.allow.empty()) {
out.allow = std::move(own.allow);
return out;
}
if (!own.path_errors.empty()) {
out.path_errors = std::move(own.path_errors);
return out;
}
return mount_best;
}
private:
// Governance: earliest sunset per /v{n} major, collected at startup so
// handle() answers sunset versions in O(1).
static std::map<int, long> CollectGovSunsets(const routing::Router& router) {
std::map<int, long> out;
for (const routing::Route& r : router.routes()) {
if (r.is_slash_redirect()) continue;
const routing::RouteOptions& o = r.options();
if (o.gov_sunset_httpdate.empty()) continue;
const int major =
::molo::govern::versions::ApiVersion::ParseMajor(r.pattern());
if (major == 0) continue;
const long sunset =
routing::detail::ParseImfFixdate(o.gov_sunset_httpdate);
if (sunset < 0) continue;
auto it = out.find(major);
if (it == out.end() || sunset < it->second) out[major] = sunset;
}
return out;
}
bool IsSunsetVersion(const std::string& path) const {
if (gov_sunsets_.empty()) return false;
const int major = ::molo::govern::versions::ApiVersion::ParseMajor(path);
if (major == 0) return false;
auto it = gov_sunsets_.find(major);
if (it == gov_sunsets_.end()) return false;
return std::time(nullptr) >= it->second;
}
// Two-step resolve keeps handle() readable; this section holds dispatch.
async::Task<http_msg::Response> run_mount_levels(http_msg::Request& req, Resolved rr,
std::size_t level) const {
if (level >= rr.levels.size()) {
middleware::NegotiationMiddleware negotiation;
middleware::Next guard(
[this, rr](http_msg::Request& r) -> async::Task<http_msg::Response> {
co_return co_await dispatch_final(r, rr);
});
co_return co_await negotiation.handle(req, guard);
}
const Mount* m = rr.levels[level];
std::function<async::Task<http_msg::Response>(http_msg::Request&)> inner =
[this, rr, level](http_msg::Request& r) -> async::Task<http_msg::Response> {
co_return co_await run_mount_levels(r, rr, level + 1);
};
co_return co_await m->sub->chain_.run(req, inner);
}
async::Task<http_msg::Response> dispatch_final(http_msg::Request& req,
const Resolved& rr) const {
if (rr.route == nullptr) {
if (!rr.allow.empty()) throw errors::MethodNotAllowed(rr.allow);
if (!rr.path_errors.empty()) {
throw errors::ValidationFailed(validate::ValidationError(rr.path_errors));
}
throw errors::NotFound("no route for " + req.path());
}
const routing::Route& route = *rr.route;
const routing::RouteOptions& opts = route.options();
validate::Object path_obj;
for (const auto& kv : rr.params) path_obj[kv.first] = validate::Value(kv.second);
req.set_validated("path", std::move(path_obj));
// R3: one 422 aggregates failures across every bound source.
std::vector<validate::FieldFailure> all_failures;
auto run_model = [&](const std::shared_ptr<validate::Model>& model,
const validate::Object& input, const std::string& source,
const std::string& slot) {
try {
req.set_validated(slot, model->validate(input, source));
} catch (const validate::ValidationError& e) {
for (const auto& item : e.failures()) all_failures.push_back(item);
}
};
if (opts.query_model) run_model(opts.query_model, query_object(req), "query", "query");
if (opts.header_model) {
validate::Object input;
for (const auto& kv : req.headers().items()) {
if (!input.count(kv.first)) input[kv.first] = validate::Value(kv.second);
}
run_model(opts.header_model, input, "header", "headers");
}
if (opts.cookie_model) {
validate::Object input;
for (const auto& kv : req.cookies().items()) input[kv.first] = validate::Value(kv.second);
run_model(opts.cookie_model, input, "cookie", "cookies");
}
if (opts.body_model) {
validate::Object fields;
if (req.body().empty() && req.content_type().empty()) {
fields = validate::Object{};
} else {
if (opts.max_body == 0 && !req.body().empty()) {
throw errors::PayloadTooLarge("route rejects bodies");
}
forms::FormData data = forms::Form::parse_body(req, opts.max_body);
fields = std::move(data.fields);
req.set_ext("form_files", data.files);
}
run_model(opts.body_model, fields, "body", "body");
}
if (!all_failures.empty()) {
throw errors::ValidationFailed(validate::ValidationError(std::move(all_failures)));
}
co_return co_await route.handler()(req);
}
static validate::Object query_object(const http_msg::Request& req) {
validate::Object out;
std::map<std::string, std::vector<std::string>> grouped;
for (const auto& kv : req.query().items()) grouped[kv.first].push_back(kv.second);
for (const auto& kv : grouped) {
if (kv.second.size() == 1) {
out[kv.first] = validate::Value(kv.second[0]);
} else {
validate::Array arr;
for (const auto& v : kv.second) arr.emplace_back(v);
out[kv.first] = validate::Value(std::move(arr));
}
}
return out;
}
routing::Router router_;
middleware::Chain chain_;
di::Container di_;
templates::Environment templates_;
std::shared_ptr<errors::ErrorHandler> error_handler_;
std::shared_ptr<seams::SessionStore> sessions_;
PluginRegistry plugins_;
std::vector<Mount> mounts_;
std::vector<std::function<void(Application&)>> startup_hooks_;
std::vector<std::function<void(Application&)>> shutdown_hooks_;
std::string last_error_code_;
bool started_ = false;
std::map<int, long> gov_sunsets_;
};
// PluginContext definitions (need the complete Application type).
inline PluginContext::PluginContext(Application* app, const std::set<std::string>& capabilities,
std::string plugin_name)
: app_(app), capabilities_(capabilities), plugin_name_(std::move(plugin_name)) {}
inline bool PluginContext::has(const std::string& capability) const {
return capabilities_.count(capability) > 0;
}
inline void PluginContext::require(const std::string& capability) const {
if (!has(capability)) {
throw PluginAccessError("plugin '" + plugin_name_ + "' lacks capability '" + capability +
"'");
}
}
inline std::size_t PluginContext::route_count() const {
require("routes");
return app_->total_routes();
}
inline bool PluginContext::di_has(const std::string& provider) const {
require("di");
return app_->di().has(provider);
}
inline std::string PluginContext::last_error_code() const {
require("errors");
return app_->last_error_code();
}
} // namespace molo::app::app
namespace molo::app::views {
// Flash definitions (need the complete Application type).
inline void Flash::flash(http_msg::Request& req, http_msg::Response& res, std::string level,
std::string text) {
app::Application* app = req.app();
if (app == nullptr) throw errors::InternalError("flash needs a bound application");
std::string sid = req.cookie(kSessionCookie);
if (sid.empty()) {
sid = generate_session_id();
http_msg::SetCookie cookie;
cookie.name = kSessionCookie;
cookie.value = sid;
res.headers().add("set-cookie", cookie.render());
}
app->sessions()->add_flash(sid, seams::FlashMessage{std::move(level), std::move(text)});
}
inline std::vector<seams::FlashMessage> Flash::take(http_msg::Request& req) {
app::Application* app = req.app();
if (app == nullptr) throw errors::InternalError("flash needs a bound application");
std::string sid = req.cookie(kSessionCookie);
if (sid.empty()) return {};
return app->sessions()->take_flashes(sid);
}
} // namespace molo::app::views