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.
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
# Standalone entry for the request/routing part. Root Makefile includes
|
||||
# app.mk instead; this wrapper only fixes ROOT for isolated builds.
|
||||
ROOT := $(abspath ../..)
|
||||
include app.mk
|
||||
|
||||
.PHONY: all test clean
|
||||
|
||||
all: app-build
|
||||
|
||||
test: app-test
|
||||
|
||||
clean: app-clean
|
||||
@@ -0,0 +1,96 @@
|
||||
# Spec: request/routing part (plan 05)
|
||||
|
||||
Implementation of `plans/05-request-routing.md`, execution steps E1 through
|
||||
E12, rules R1 through R12. All code lives under `src/app/` in namespaces
|
||||
`molo::app::*` (namespaces mirror directories). Tests live under
|
||||
`tests/src/app/` mirroring URL paths. Build outputs go under `build/` only.
|
||||
C++23, standard library plus OS syscalls only. No TLS code in this part, so
|
||||
no wolfSSL use and no stub needed here.
|
||||
|
||||
## Module map
|
||||
|
||||
| Directory | Contents |
|
||||
|---|---|
|
||||
| `async/` | `Task<T>`: minimal eager coroutine task (handler return type) |
|
||||
| `seams/` | Sibling-owned seams: request IDs, session store (in-memory default) |
|
||||
| `http_msg/` | Method, Headers, Query, Cookies, Request, Response hierarchy, HTML/XML escape |
|
||||
| `routing/` | Path compiler, Route, Router, match, url_for |
|
||||
| `app/` | Application, Mount, PluginRegistry, PluginContext |
|
||||
| `validate/` | Value, JSON codec, Field, Model, ValidationError |
|
||||
| `forms/` | Form binding: JSON, urlencoded, multipart |
|
||||
| `errors/` | HttpError hierarchy, ErrorHandler with JSON/HTML renderers |
|
||||
| `negotiate/` | Accept parser, Negotiator, variant rendering |
|
||||
| `views/` | View base, handler adapters, Flash helpers |
|
||||
| `middleware/` | Middleware base, Next guard, Chain, built-ins |
|
||||
| `di/` | Container with app and request scopes, cycle detection |
|
||||
| `templates/` | Lexer, Parser, AST, Renderer, Environment, Loaders, Cache, Filters, Tests, TemplateResponse |
|
||||
|
||||
Caps: `caps.h` holds every static ceiling (R11). No autotuning anywhere.
|
||||
|
||||
## Key behaviors (plan section 6)
|
||||
|
||||
- Matching order: static segments first, converters in registration order,
|
||||
path catch-alls last. Precedence: full match, 405 with `Allow`, 422 on
|
||||
converter failure with `loc: ["path", name]`, else 404.
|
||||
- Trailing slash is strict; `slash_insensitive` registers the declared form
|
||||
plus a companion 308 redirect route (query string preserved).
|
||||
- Mounts merge paths (`/app1/app1/app1` for triple nesting) and prefix
|
||||
route names with the mount alias (`app1:app1:deep`) so R10 uniqueness
|
||||
holds after merge. Mounted apps keep their own DI container and run
|
||||
their own middleware chain inside the parent chain.
|
||||
- One 422 aggregates failures across query, headers, cookies and body
|
||||
(R3). Shape: `{"detail":[{"loc":[...],"msg":"...","type":"..."}]}`
|
||||
(lowercase `detail`).
|
||||
- 406 shape: `{"Detail":{"available":[...]}}` (capital `D`, per plan).
|
||||
- Other errors: `{"error":{"code":...,"message":...,"request_id":"..."}}`,
|
||||
plus a responsive HTML page when the client prefers HTML.
|
||||
- `?format=` override applies only when the route sets
|
||||
`allow_format_override` (default off, Q2).
|
||||
- Redirects are 307 temporary / 308 permanent (method-preserving).
|
||||
- Flash messages ride the session store and render exactly once.
|
||||
- Middleware categories are enforced at registration; `Next` twice is a
|
||||
loud error. ExceptionMapping is outermost by construction;
|
||||
Negotiation wraps the terminal dispatch so it stays innermost.
|
||||
- DI has app and request scopes; request scope is created per `handle()`
|
||||
call and cleared before returning. Declared dependency cycles fail
|
||||
startup with the cycle quoted; resolution carries a dynamic guard too.
|
||||
- Templates: `{{ }}`, `{% %}`, `{# #}` with extends/blocks, include,
|
||||
if/elif/else, for/else with `loop`, set, macros with defaults and
|
||||
kwargs, filters, tests, autoescape blocks. Autoescape is on for
|
||||
`.html`/`.htm`/`.xml` with no global disable (R5). Undefined policy
|
||||
defaults to Strict and Chain renders empty plus a stats counter (Q3).
|
||||
Documented Jinja gaps: no ternary, no `**`, no string `%` formatting,
|
||||
no `super()`, no block-level set, macro defaults are literal-only,
|
||||
case conversion is ASCII-only, Accept range params are ignored.
|
||||
|
||||
## Sibling seams (R12)
|
||||
|
||||
Consumed through seams with standalone defaults, owned elsewhere:
|
||||
|
||||
- 01-runtime: byte caps, transport, production task executor. Local
|
||||
`async::Task` is the eager stand-in with the same `co_await` shape.
|
||||
- 02-observability: correlation IDs (`seams::request_id`), log sink hook
|
||||
on `ErrorHandler`, per-route metrics (not wired here).
|
||||
- 03-security: session store (`Application::set_session_store`), upload
|
||||
quotas and scanning, auth guards consumed via DI and middleware.
|
||||
- 04-data: ORM/KV/cache handles provided through DI by the host app.
|
||||
|
||||
Provided to siblings: `Request`/`Response` shells, router mounting,
|
||||
middleware and DI participation points, validation models for OpenAPI,
|
||||
template loaders (embedded assets plug into `EmbeddedLoader`), request
|
||||
scope teardown at end of `handle()` for background handoff.
|
||||
|
||||
## Static assertions and diagnostics
|
||||
|
||||
- R4 is enforced by explicit constructors plus `static_assert` in
|
||||
`tests/src/app/00_compile_all_test.cpp`.
|
||||
- Route names unique after merge (quoted paths), unknown converters name
|
||||
the route, DI cycles quote the cycle, middleware reorder names layers,
|
||||
plugin capability denial names plugin and capability.
|
||||
|
||||
## ID counters note (R8)
|
||||
|
||||
`generate_request_id` and `generate_session_id` use process-wide atomic
|
||||
counters. This is ID uniqueness, not service state: no service singleton
|
||||
or mutable file-static state is reachable from handlers. All services
|
||||
flow through `Application` and request extensions.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Per-part makefile for the request/routing part (plan 05). Includable by
|
||||
# the root Makefile: set ROOT to the repo root, then `include src/app/app.mk`.
|
||||
# Provides: app-build, app-test, app-clean. All outputs go under build/.
|
||||
ROOT ?= .
|
||||
APP_CXX ?= g++
|
||||
APP_CXXFLAGS ?= -std=c++23 -Wall -Wextra -Isrc
|
||||
APP_BUILD ?= $(ROOT)/build/app
|
||||
APP_TEST_SRCS := $(shell find $(ROOT)/tests/src/app -name '*_test.cpp' | sort)
|
||||
APP_HEADERS := $(shell find $(ROOT)/src/app -name '*.h' | sort)
|
||||
APP_TEST_BINS := $(patsubst $(ROOT)/tests/src/app/%.cpp,$(APP_BUILD)/%,$(APP_TEST_SRCS))
|
||||
|
||||
$(APP_BUILD)/%: $(ROOT)/tests/src/app/%.cpp $(APP_HEADERS)
|
||||
@mkdir -p $(dir $@)
|
||||
$(APP_CXX) $(APP_CXXFLAGS) -I$(ROOT)/src -I$(ROOT)/tests/src/app $< -o $@
|
||||
|
||||
.PHONY: app-build app-test app-clean
|
||||
|
||||
app-build: $(APP_TEST_BINS)
|
||||
|
||||
app-test: $(APP_TEST_BINS)
|
||||
@pass=0; fail=0; \
|
||||
for t in $(APP_TEST_BINS); do \
|
||||
if (cd $(ROOT) && "$$t"); then pass=$$((pass+1)); else fail=$$((fail+1)); fi; \
|
||||
done; \
|
||||
echo "app tests: $$pass passed, $$fail failed"; \
|
||||
test $$fail -eq 0
|
||||
|
||||
app-clean:
|
||||
rm -rf $(APP_BUILD) $(ROOT)/build/tmp_templates
|
||||
@@ -0,0 +1,528 @@
|
||||
#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
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::app plugin registry (plan 05, E12). Named hooks:
|
||||
// route_added, app_started, error_render. Plugins declare capabilities
|
||||
// ("routes", "di", "errors"); PluginContext getters throw PluginAccessError
|
||||
// unless the plugin declared the matching capability, so plugins cannot
|
||||
// reach undeclared internals. Hook order per event is registration order.
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::app::routing {
|
||||
class Route;
|
||||
}
|
||||
|
||||
namespace molo::app::app {
|
||||
|
||||
class Application;
|
||||
|
||||
class PluginAccessError : public std::runtime_error {
|
||||
public:
|
||||
explicit PluginAccessError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class PluginContext {
|
||||
public:
|
||||
PluginContext(Application* app, const std::set<std::string>& capabilities,
|
||||
std::string plugin_name);
|
||||
|
||||
const std::string& plugin_name() const { return plugin_name_; }
|
||||
bool has(const std::string& capability) const;
|
||||
|
||||
// Capability "routes".
|
||||
std::size_t route_count() const;
|
||||
// Capability "di".
|
||||
bool di_has(const std::string& provider) const;
|
||||
// Capability "errors".
|
||||
std::string last_error_code() const;
|
||||
|
||||
private:
|
||||
void require(const std::string& capability) const;
|
||||
|
||||
Application* app_;
|
||||
std::set<std::string> capabilities_;
|
||||
std::string plugin_name_;
|
||||
};
|
||||
|
||||
struct PluginHooks {
|
||||
std::function<void(PluginContext&, const routing::Route&)> route_added;
|
||||
std::function<void(PluginContext&)> app_started;
|
||||
std::function<void(PluginContext&, int, const std::string&)> error_render;
|
||||
};
|
||||
|
||||
struct Plugin {
|
||||
std::string name;
|
||||
std::set<std::string> capabilities;
|
||||
PluginHooks hooks;
|
||||
};
|
||||
|
||||
class PluginRegistry {
|
||||
public:
|
||||
void register_plugin(Plugin plugin) {
|
||||
for (const auto& cap : plugin.capabilities) {
|
||||
if (cap != "routes" && cap != "di" && cap != "errors") {
|
||||
throw PluginAccessError("plugin '" + plugin.name + "' declares unknown capability '" +
|
||||
cap + "'");
|
||||
}
|
||||
}
|
||||
plugins_.push_back(std::move(plugin));
|
||||
}
|
||||
|
||||
const std::vector<Plugin>& plugins() const { return plugins_; }
|
||||
|
||||
void fire_route_added(Application* app, const routing::Route& route) const {
|
||||
for (const Plugin& p : plugins_) {
|
||||
if (p.hooks.route_added) {
|
||||
PluginContext ctx(app, p.capabilities, p.name);
|
||||
p.hooks.route_added(ctx, route);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void fire_app_started(Application* app) const {
|
||||
for (const Plugin& p : plugins_) {
|
||||
if (p.hooks.app_started) {
|
||||
PluginContext ctx(app, p.capabilities, p.name);
|
||||
p.hooks.app_started(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void fire_error_render(Application* app, int status, const std::string& code) const {
|
||||
for (const Plugin& p : plugins_) {
|
||||
if (p.hooks.error_render) {
|
||||
PluginContext ctx(app, p.capabilities, p.name);
|
||||
p.hooks.error_render(ctx, status, code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<Plugin> plugins_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::app
|
||||
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::async::Task. Minimal eager coroutine task used as the
|
||||
// handler return type (plan 05, R1 and section 6 Middleware). Seam note: the
|
||||
// production executor is owned by 01-runtime; this local type keeps the app
|
||||
// layer compilable standalone and has the same co_await shape for ready
|
||||
// values. It runs eagerly and synchronously: every co_await inside app code
|
||||
// awaits an already complete Task. Integration swaps this header for the
|
||||
// runtime task without touching call sites.
|
||||
|
||||
#include <coroutine>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace molo::app::async {
|
||||
|
||||
template <typename T>
|
||||
class Task {
|
||||
public:
|
||||
struct promise_type {
|
||||
std::optional<T> value;
|
||||
std::exception_ptr error;
|
||||
|
||||
Task get_return_object() {
|
||||
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
std::suspend_never initial_suspend() noexcept { return {}; }
|
||||
std::suspend_always final_suspend() noexcept { return {}; }
|
||||
void return_value(T v) { value.emplace(std::move(v)); }
|
||||
void unhandled_exception() { error = std::current_exception(); }
|
||||
};
|
||||
|
||||
using Handle = std::coroutine_handle<promise_type>;
|
||||
|
||||
Task() = default;
|
||||
explicit Task(Handle h) : handle_(h) {}
|
||||
Task(Task&& other) noexcept : handle_(other.handle_) { other.handle_ = nullptr; }
|
||||
Task& operator=(Task&& other) noexcept {
|
||||
if (this != &other) {
|
||||
destroy();
|
||||
handle_ = other.handle_;
|
||||
other.handle_ = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Task(const Task&) = delete;
|
||||
Task& operator=(const Task&) = delete;
|
||||
~Task() { destroy(); }
|
||||
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) const noexcept {}
|
||||
T await_resume() { return value(); }
|
||||
|
||||
T value() && {
|
||||
if (!handle_) throw std::logic_error("molo::app::async::Task: empty task");
|
||||
if (handle_.promise().error) std::rethrow_exception(handle_.promise().error);
|
||||
return std::move(*handle_.promise().value);
|
||||
}
|
||||
T value() & {
|
||||
if (!handle_) throw std::logic_error("molo::app::async::Task: empty task");
|
||||
if (handle_.promise().error) std::rethrow_exception(handle_.promise().error);
|
||||
T out = *handle_.promise().value;
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
void destroy() {
|
||||
if (handle_) handle_.destroy();
|
||||
handle_ = nullptr;
|
||||
}
|
||||
Handle handle_{nullptr};
|
||||
};
|
||||
|
||||
template <>
|
||||
class Task<void> {
|
||||
public:
|
||||
struct promise_type {
|
||||
std::exception_ptr error;
|
||||
|
||||
Task get_return_object() {
|
||||
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
std::suspend_never initial_suspend() noexcept { return {}; }
|
||||
std::suspend_always final_suspend() noexcept { return {}; }
|
||||
void return_void() {}
|
||||
void unhandled_exception() { error = std::current_exception(); }
|
||||
};
|
||||
|
||||
using Handle = std::coroutine_handle<promise_type>;
|
||||
|
||||
Task() = default;
|
||||
explicit Task(Handle h) : handle_(h) {}
|
||||
Task(Task&& other) noexcept : handle_(other.handle_) { other.handle_ = nullptr; }
|
||||
Task& operator=(Task&&) = delete;
|
||||
Task(const Task&) = delete;
|
||||
Task& operator=(const Task&) = delete;
|
||||
~Task() {
|
||||
if (handle_) handle_.destroy();
|
||||
}
|
||||
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) const noexcept {}
|
||||
void await_resume() { value(); }
|
||||
|
||||
void value() {
|
||||
if (!handle_) throw std::logic_error("molo::app::async::Task: empty task");
|
||||
if (handle_.promise().error) std::rethrow_exception(handle_.promise().error);
|
||||
}
|
||||
|
||||
private:
|
||||
Handle handle_{nullptr};
|
||||
};
|
||||
|
||||
// Block on an eager task. Valid only because every awaited task completes
|
||||
// synchronously; the runtime executor replaces this on integration.
|
||||
template <typename T>
|
||||
T run(Task<T>&& task) {
|
||||
return std::move(task).value();
|
||||
}
|
||||
|
||||
inline void run(Task<void>&& task) { task.value(); }
|
||||
|
||||
} // namespace molo::app::async
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::caps. Single home of every static ceiling owned by this
|
||||
// part (plan 05, section 6 plus R11). All values are compile-time constants.
|
||||
// No autotuning, no silent growth. Sibling-owned byte caps (body, headers)
|
||||
// are enforced by 01-runtime before this layer; the values below bind the
|
||||
// app-layer structures only.
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace molo::app::caps {
|
||||
|
||||
// Routing and application (section 6, Global caps).
|
||||
inline constexpr std::size_t kMaxRoutesPerApp = 100000;
|
||||
inline constexpr std::size_t kMaxPathLength = 2048;
|
||||
inline constexpr std::size_t kMaxPathParamsPerRoute = 32;
|
||||
inline constexpr std::size_t kMaxMiddlewareLayers = 64;
|
||||
inline constexpr std::size_t kMaxSubAppNestingDepth = 8;
|
||||
inline constexpr std::size_t kMaxDiProviders = 4096;
|
||||
|
||||
// HTTP message views (standalone parsing; runtime owns wire caps).
|
||||
inline constexpr std::size_t kMaxHeaders = 100;
|
||||
inline constexpr std::size_t kMaxHeaderName = 256;
|
||||
inline constexpr std::size_t kMaxHeaderValue = 8192;
|
||||
inline constexpr std::size_t kMaxQueryParams = 1000;
|
||||
inline constexpr std::size_t kMaxCookies = 200;
|
||||
|
||||
// Validation and forms (section 6, Validation and forms).
|
||||
inline constexpr std::size_t kMaxFormFields = 1000;
|
||||
inline constexpr std::size_t kMaxFieldName = 256;
|
||||
inline constexpr std::size_t kMaxNonFileValue = 1048576; // 1 MiB
|
||||
inline constexpr std::size_t kMaxJsonDepth = 32;
|
||||
inline constexpr std::size_t kMaxJsonDocument = 10485760; // 10 MiB
|
||||
inline constexpr std::size_t kMaxMultipartFiles = 100;
|
||||
inline constexpr std::size_t kMaxFileBytes = 16777216; // 16 MiB default; 03-security owns policy
|
||||
inline constexpr std::size_t kMaxMultipartTotal = 67108864; // 64 MiB
|
||||
|
||||
// Templates (section 6, Templates).
|
||||
inline constexpr std::size_t kMaxTemplateSize = 1048576; // 1 MiB
|
||||
inline constexpr std::size_t kMaxIncludeDepth = 16;
|
||||
inline constexpr std::size_t kMaxExtendsChain = 8;
|
||||
inline constexpr std::size_t kMaxLoopIterations = 100000;
|
||||
inline constexpr std::size_t kMaxRenderOutput = 33554432; // 32 MiB
|
||||
inline constexpr std::size_t kMaxCompiledTemplates = 512;
|
||||
inline constexpr std::size_t kMaxMacroArgs = 32;
|
||||
inline constexpr std::size_t kMaxExprDepth = 128;
|
||||
|
||||
// Errors and misc.
|
||||
inline constexpr std::size_t kMaxErrorDetails = 64;
|
||||
inline constexpr std::size_t kMaxRouteName = 256;
|
||||
inline constexpr std::size_t kMaxFlashMessages = 100;
|
||||
|
||||
} // namespace molo::app::caps
|
||||
@@ -0,0 +1,208 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::di::Container (plan 05, R8, E9). Dependency injection
|
||||
// without globals: named providers with app scope (one per Application) or
|
||||
// request scope (one per request, destroyed after the response). Providers
|
||||
// are factories or values. Declared dependencies feed startup cycle
|
||||
// detection (cycle quoted on failure); resolution carries a dynamic guard
|
||||
// with the same quoting. No service singletons, no file-static mutable
|
||||
// state reachable from handlers.
|
||||
|
||||
#include <any>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
|
||||
namespace molo::app::di {
|
||||
|
||||
enum class Scope { App, Request };
|
||||
|
||||
class DiError : public std::runtime_error {
|
||||
public:
|
||||
explicit DiError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class CycleError : public DiError {
|
||||
public:
|
||||
explicit CycleError(const std::string& msg) : DiError(msg) {}
|
||||
};
|
||||
|
||||
class Container;
|
||||
class RequestScope;
|
||||
|
||||
class Resolver {
|
||||
public:
|
||||
std::any get(const std::string& name);
|
||||
template <typename T>
|
||||
T get_as(const std::string& name) {
|
||||
return std::any_cast<T>(get(name));
|
||||
}
|
||||
|
||||
private:
|
||||
friend class Container;
|
||||
friend class RequestScope;
|
||||
Resolver(Container* owner, std::map<std::string, std::any>* request_cache,
|
||||
std::vector<std::string>* stack)
|
||||
: owner_(owner), request_cache_(request_cache), stack_(stack) {}
|
||||
Container* owner_;
|
||||
std::map<std::string, std::any>* request_cache_;
|
||||
std::vector<std::string>* stack_;
|
||||
};
|
||||
|
||||
struct Provider {
|
||||
std::function<std::any(Resolver&)> factory;
|
||||
Scope scope = Scope::App;
|
||||
std::vector<std::string> deps;
|
||||
std::any cached;
|
||||
bool resolved = false;
|
||||
};
|
||||
|
||||
class Container {
|
||||
public:
|
||||
void provide(std::string name, std::function<std::any(Resolver&)> factory,
|
||||
Scope scope = Scope::App, std::vector<std::string> deps = {}) {
|
||||
if (providers_.count(name)) throw DiError("duplicate DI provider '" + name + "'");
|
||||
if (providers_.size() >= caps::kMaxDiProviders) {
|
||||
throw DiError("too many DI providers");
|
||||
}
|
||||
Provider p;
|
||||
p.factory = std::move(factory);
|
||||
p.scope = scope;
|
||||
p.deps = std::move(deps);
|
||||
providers_[std::move(name)] = std::move(p);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void provide_typed(std::string name, std::function<T(Resolver&)> factory,
|
||||
Scope scope = Scope::App, std::vector<std::string> deps = {}) {
|
||||
provide(std::move(name),
|
||||
[factory = std::move(factory)](Resolver& r) -> std::any {
|
||||
return std::any(factory(r));
|
||||
},
|
||||
scope, std::move(deps));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void provide_value(std::string name, T value) {
|
||||
provide(std::move(name),
|
||||
[v = std::move(value)](Resolver&) -> std::any { return std::any(v); },
|
||||
Scope::App, {});
|
||||
}
|
||||
|
||||
bool has(const std::string& name) const { return providers_.count(name) > 0; }
|
||||
std::size_t size() const { return providers_.size(); }
|
||||
|
||||
void validate_no_cycles() const {
|
||||
std::set<std::string> done;
|
||||
for (const auto& kv : providers_) {
|
||||
std::vector<std::string> path;
|
||||
visit(kv.first, path, done);
|
||||
}
|
||||
}
|
||||
|
||||
RequestScope fork_request();
|
||||
|
||||
private:
|
||||
friend class Resolver;
|
||||
friend class RequestScope;
|
||||
|
||||
std::any resolve_into(const std::string& name, std::map<std::string, std::any>* request_cache,
|
||||
std::vector<std::string>* stack) {
|
||||
auto it = providers_.find(name);
|
||||
if (it == providers_.end()) throw DiError("unknown DI provider '" + name + "'");
|
||||
for (const auto& frame : *stack) {
|
||||
if (frame == name) {
|
||||
std::string cycle;
|
||||
bool started = false;
|
||||
for (const auto& f : *stack) {
|
||||
if (f == name) started = true;
|
||||
if (started) {
|
||||
if (!cycle.empty()) cycle += " -> ";
|
||||
cycle += "'" + f + "'";
|
||||
}
|
||||
}
|
||||
cycle += " -> '" + name + "'";
|
||||
throw CycleError("dependency cycle: " + cycle);
|
||||
}
|
||||
}
|
||||
Provider& p = it->second;
|
||||
if (p.scope == Scope::App && p.resolved) return p.cached;
|
||||
if (p.scope == Scope::Request && request_cache != nullptr) {
|
||||
auto hit = request_cache->find(name);
|
||||
if (hit != request_cache->end()) return hit->second;
|
||||
}
|
||||
stack->push_back(name);
|
||||
Resolver resolver(this, request_cache, stack);
|
||||
std::any value = p.factory(resolver);
|
||||
stack->pop_back();
|
||||
if (p.scope == Scope::App) {
|
||||
p.cached = value;
|
||||
p.resolved = true;
|
||||
} else if (request_cache != nullptr) {
|
||||
(*request_cache)[name] = value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
void visit(const std::string& name, std::vector<std::string>& path,
|
||||
std::set<std::string>& done) const {
|
||||
if (done.count(name)) return;
|
||||
for (const auto& frame : path) {
|
||||
if (frame == name) {
|
||||
std::string cycle;
|
||||
bool started = false;
|
||||
for (const auto& f : path) {
|
||||
if (f == name) started = true;
|
||||
if (started) {
|
||||
if (!cycle.empty()) cycle += " -> ";
|
||||
cycle += "'" + f + "'";
|
||||
}
|
||||
}
|
||||
cycle += " -> '" + name + "'";
|
||||
throw CycleError("dependency cycle: " + cycle);
|
||||
}
|
||||
}
|
||||
auto it = providers_.find(name);
|
||||
if (it == providers_.end()) return;
|
||||
path.push_back(name);
|
||||
for (const auto& dep : it->second.deps) visit(dep, path, done);
|
||||
path.pop_back();
|
||||
done.insert(name);
|
||||
}
|
||||
|
||||
std::map<std::string, Provider> providers_;
|
||||
};
|
||||
|
||||
class RequestScope {
|
||||
public:
|
||||
explicit RequestScope(Container* owner) : owner_(owner) {}
|
||||
|
||||
std::any get(const std::string& name) {
|
||||
return owner_->resolve_into(name, &cache_, &stack_);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T get_as(const std::string& name) {
|
||||
return std::any_cast<T>(get(name));
|
||||
}
|
||||
|
||||
Resolver resolver() { return Resolver(owner_, &cache_, &stack_); }
|
||||
|
||||
private:
|
||||
Container* owner_;
|
||||
std::map<std::string, std::any> cache_;
|
||||
std::vector<std::string> stack_;
|
||||
};
|
||||
|
||||
inline std::any Resolver::get(const std::string& name) {
|
||||
return owner_->resolve_into(name, request_cache_, stack_);
|
||||
}
|
||||
|
||||
inline RequestScope Container::fork_request() { return RequestScope(this); }
|
||||
|
||||
} // namespace molo::app::di
|
||||
@@ -0,0 +1,209 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::errors::ErrorHandler (plan 05, R9, E5). Maps exceptions
|
||||
// to status plus negotiated body. JSON shape:
|
||||
// {"error":{"code":"...","message":"...","request_id":"..."}}.
|
||||
// HTML shape: responsive error page with the same fields, no internals.
|
||||
// ValidationFailed renders the 422 detail shape instead:
|
||||
// {"detail":[{"loc":[...],"msg":"...","type":"..."}]}.
|
||||
// Unknown exceptions become 500; client-visible text is fixed, internals go
|
||||
// to the log sink hook (owned by 02-observability on integration).
|
||||
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "../../audit/redact/redactor.h"
|
||||
#include "../http_msg/html.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../seams/request_id.h"
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/value.h"
|
||||
#include "http_error.h"
|
||||
|
||||
namespace molo::app::errors {
|
||||
|
||||
inline bool wants_html(const http_msg::Request& req) {
|
||||
std::string accept = req.headers().get("accept");
|
||||
std::string low;
|
||||
for (char c : accept) low += (char)std::tolower((unsigned char)c);
|
||||
bool html = low.find("text/html") != std::string::npos;
|
||||
bool json = low.find("application/json") != std::string::npos;
|
||||
if (html && !json) return true;
|
||||
if (html && json) return low.find("text/html") < low.find("application/json");
|
||||
return false;
|
||||
}
|
||||
|
||||
inline std::string error_page_html(int status, const std::string& code, const std::string& message,
|
||||
const std::string& request_id) {
|
||||
std::string html =
|
||||
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
||||
"<title>" +
|
||||
std::to_string(status) + " " + http_msg::escape_html(code) +
|
||||
"</title><style>"
|
||||
"body{font-family:system-ui,sans-serif;margin:0;background:#f6f6f6;color:#222}"
|
||||
".card{max-width:34rem;margin:4rem auto;padding:1.5rem;background:#fff;"
|
||||
"border-radius:.5rem;box-shadow:0 1px 4px rgba(0,0,0,.12)}"
|
||||
"h1{font-size:1.4rem;margin:0 0 .5rem}code{color:#666;font-size:.85rem}"
|
||||
"@media (max-width:40rem){.card{margin:1rem;padding:1rem}}"
|
||||
"</style></head><body><div class=\"card\"><h1>" +
|
||||
std::to_string(status) + " " + http_msg::escape_html(message) + "</h1><p><code>" +
|
||||
http_msg::escape_html(code) + " request " + http_msg::escape_html(request_id) +
|
||||
"</code></p></div></body></html>";
|
||||
return html;
|
||||
}
|
||||
|
||||
inline std::string validation_page_html(const validate::ValidationError& cause,
|
||||
const std::string& request_id) {
|
||||
std::string rows;
|
||||
for (const auto& f : cause.failures()) {
|
||||
std::string loc;
|
||||
for (std::size_t i = 0; i < f.loc.size(); ++i) {
|
||||
if (i) loc += ".";
|
||||
loc += f.loc[i];
|
||||
}
|
||||
rows += "<li><strong>" + http_msg::escape_html(loc) + "</strong> " +
|
||||
http_msg::escape_html(f.msg) + " <code>" + http_msg::escape_html(f.type) +
|
||||
"</code></li>";
|
||||
}
|
||||
std::string html =
|
||||
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
||||
"<title>422 validation failed</title><style>"
|
||||
"body{font-family:system-ui,sans-serif;margin:0;background:#f6f6f6;color:#222}"
|
||||
".card{max-width:34rem;margin:4rem auto;padding:1.5rem;background:#fff;"
|
||||
"border-radius:.5rem;box-shadow:0 1px 4px rgba(0,0,0,.12)}"
|
||||
"@media (max-width:40rem){.card{margin:1rem;padding:1rem}}"
|
||||
"</style></head><body><div class=\"card\"><h1>422 validation failed</h1>"
|
||||
"<ul>" +
|
||||
rows + "</ul><p><code>request " + http_msg::escape_html(request_id) +
|
||||
"</code></p></div></body></html>";
|
||||
return html;
|
||||
}
|
||||
|
||||
class ErrorHandler {
|
||||
public:
|
||||
using LogSink = std::function<void(int status, const std::string& code,
|
||||
const std::string& request_id,
|
||||
const std::string& internal)>;
|
||||
|
||||
void set_log_sink(LogSink sink) { sink_ = std::move(sink); }
|
||||
void set_render_hook(std::function<void(int, const std::string&)> hook) {
|
||||
render_hook_ = std::move(hook);
|
||||
}
|
||||
|
||||
http_msg::Response render(const HttpError& err, const http_msg::Request& req,
|
||||
std::string request_id) const {
|
||||
// Audit patch: user-visible detail and diagnostics pass through the
|
||||
// redactor before they reach the response body and the log sink.
|
||||
const std::string safe_detail =
|
||||
::molo::audit::redact::Redactor::RedactDetail(err.detail_message());
|
||||
log(err.status(), err.code(), request_id, safe_detail);
|
||||
if (render_hook_) render_hook_(err.status(), err.code());
|
||||
if (const auto* vf = dynamic_cast<const ValidationFailed*>(&err)) {
|
||||
if (wants_html(req)) {
|
||||
return http_msg::HtmlResponse(validation_page_html(vf->cause(), request_id), 422);
|
||||
}
|
||||
return http_msg::JsonResponse(vf->cause().to_value(), 422);
|
||||
}
|
||||
if (const auto* na = dynamic_cast<const NotAcceptable*>(&err)) {
|
||||
// Spec 406 shape: {"Detail":{"available":[...]}} (capital D).
|
||||
validate::Array avail;
|
||||
for (const auto& a : na->available()) avail.emplace_back(a);
|
||||
validate::Object inner;
|
||||
inner["available"] = validate::Value(std::move(avail));
|
||||
validate::Object root;
|
||||
root["Detail"] = validate::Value(std::move(inner));
|
||||
if (wants_html(req)) {
|
||||
std::string items;
|
||||
for (const auto& a : na->available()) {
|
||||
items += "<li><code>" + http_msg::escape_html(a) + "</code></li>";
|
||||
}
|
||||
std::string page =
|
||||
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
||||
"<title>406 not acceptable</title><style>"
|
||||
"body{font-family:system-ui,sans-serif;margin:0;background:#f6f6f6;color:#222}"
|
||||
".card{max-width:34rem;margin:4rem auto;padding:1.5rem;background:#fff;"
|
||||
"border-radius:.5rem;box-shadow:0 1px 4px rgba(0,0,0,.12)}"
|
||||
"@media (max-width:40rem){.card{margin:1rem;padding:1rem}}"
|
||||
"</style></head><body><div class=\"card\">"
|
||||
"<h1>406 not acceptable</h1><p>Available types:</p><ul>" +
|
||||
items + "</ul><p><code>request " + http_msg::escape_html(request_id) +
|
||||
"</code></p></div></body></html>";
|
||||
return http_msg::HtmlResponse(page, 406);
|
||||
}
|
||||
return http_msg::JsonResponse(validate::Value(std::move(root)), 406);
|
||||
}
|
||||
http_msg::Response res =
|
||||
wants_html(req)
|
||||
? http_msg::Response(http_msg::HtmlResponse(
|
||||
error_page_html(err.status(), err.code(), safe_detail, request_id),
|
||||
err.status()))
|
||||
: http_msg::Response(http_msg::JsonResponse(
|
||||
validate::Value([&] {
|
||||
validate::Object inner;
|
||||
inner["code"] = validate::Value(err.code());
|
||||
inner["message"] = validate::Value(safe_detail);
|
||||
inner["request_id"] = validate::Value(request_id);
|
||||
validate::Object root;
|
||||
root["error"] = validate::Value(std::move(inner));
|
||||
return root;
|
||||
}()),
|
||||
err.status()));
|
||||
if (const auto* mna = dynamic_cast<const MethodNotAllowed*>(&err)) {
|
||||
res.headers().set("allow", mna->allow_header());
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Governance: RFC 9457 renderer for problem bodies. Copies Retry-After
|
||||
// and Link headers from the source headers map when present.
|
||||
http_msg::Response render_problem(int status, std::string_view type, std::string_view title,
|
||||
std::string_view detail,
|
||||
const http_msg::Headers& extra) const {
|
||||
validate::Object root;
|
||||
root["type"] = validate::Value(std::string(type));
|
||||
root["title"] = validate::Value(std::string(title));
|
||||
root["status"] = validate::Value(static_cast<long long>(status));
|
||||
if (!detail.empty()) root["detail"] = validate::Value(std::string(detail));
|
||||
http_msg::Response res = http_msg::JsonResponse(validate::Value(std::move(root)), status);
|
||||
res.set_content_type("application/problem+json");
|
||||
for (const char* name : {"retry-after", "link"}) {
|
||||
std::string v = extra.get(name);
|
||||
if (!v.empty()) res.headers().set(name, v);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
http_msg::Response render_unknown(const http_msg::Request& req, std::string request_id,
|
||||
const std::string& internal) const {
|
||||
const std::string safe_internal =
|
||||
::molo::audit::redact::Redactor::RedactDetail(internal);
|
||||
log(500, "internal_error", request_id, safe_internal);
|
||||
InternalError err;
|
||||
if (wants_html(req)) {
|
||||
return http_msg::HtmlResponse(
|
||||
error_page_html(500, err.code(), err.detail_message(), request_id), 500);
|
||||
}
|
||||
validate::Object inner;
|
||||
inner["code"] = validate::Value(err.code());
|
||||
inner["message"] = validate::Value(err.detail_message());
|
||||
inner["request_id"] = validate::Value(request_id);
|
||||
validate::Object root;
|
||||
root["error"] = validate::Value(std::move(inner));
|
||||
return http_msg::JsonResponse(validate::Value(std::move(root)), 500);
|
||||
}
|
||||
|
||||
private:
|
||||
void log(int status, const std::string& code, const std::string& request_id,
|
||||
const std::string& internal) const {
|
||||
if (sink_) sink_(status, code, request_id, internal);
|
||||
}
|
||||
LogSink sink_;
|
||||
std::function<void(int, const std::string&)> render_hook_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::errors
|
||||
@@ -0,0 +1,178 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::errors HttpError hierarchy (plan 05, R9, section 6
|
||||
// Errors). Every framework exception maps to exactly one HTTP status via
|
||||
// this table. Unmapped exceptions become 500 in ErrorHandler.
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../validate/errors.h"
|
||||
|
||||
namespace molo::app::errors {
|
||||
|
||||
class HttpError : public std::exception {
|
||||
public:
|
||||
HttpError(int status, std::string code, std::string message)
|
||||
: status_(status), code_(std::move(code)), message_(std::move(message)) {}
|
||||
|
||||
const char* what() const noexcept override { return message_.c_str(); }
|
||||
|
||||
int status() const { return status_; }
|
||||
const std::string& code() const { return code_; }
|
||||
const std::string& detail_message() const { return message_; }
|
||||
const std::string& request_id() const { return request_id_; }
|
||||
void set_request_id(std::string id) { request_id_ = std::move(id); }
|
||||
|
||||
private:
|
||||
int status_;
|
||||
std::string code_;
|
||||
std::string message_;
|
||||
std::string request_id_;
|
||||
};
|
||||
|
||||
class BadRequest : public HttpError {
|
||||
public:
|
||||
explicit BadRequest(std::string message = "bad request")
|
||||
: HttpError(400, "bad_request", std::move(message)) {}
|
||||
};
|
||||
|
||||
class Unauthorized : public HttpError {
|
||||
public:
|
||||
explicit Unauthorized(std::string message = "unauthorized")
|
||||
: HttpError(401, "unauthorized", std::move(message)) {}
|
||||
};
|
||||
|
||||
class Forbidden : public HttpError {
|
||||
public:
|
||||
explicit Forbidden(std::string message = "forbidden")
|
||||
: HttpError(403, "forbidden", std::move(message)) {}
|
||||
};
|
||||
|
||||
class NotFound : public HttpError {
|
||||
public:
|
||||
explicit NotFound(std::string message = "not found")
|
||||
: HttpError(404, "not_found", std::move(message)) {}
|
||||
};
|
||||
|
||||
class MethodNotAllowed : public HttpError {
|
||||
public:
|
||||
explicit MethodNotAllowed(std::vector<std::string> allow,
|
||||
std::string message = "method not allowed")
|
||||
: HttpError(405, "method_not_allowed", std::move(message)), allow_(std::move(allow)) {}
|
||||
const std::vector<std::string>& allow() const { return allow_; }
|
||||
std::string allow_header() const {
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < allow_.size(); ++i) {
|
||||
if (i) out += ", ";
|
||||
out += allow_[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::string> allow_;
|
||||
};
|
||||
|
||||
class NotAcceptable : public HttpError {
|
||||
public:
|
||||
explicit NotAcceptable(std::vector<std::string> available = {},
|
||||
std::string message = "not acceptable")
|
||||
: HttpError(406, "not_acceptable", std::move(message)), available_(std::move(available)) {}
|
||||
const std::vector<std::string>& available() const { return available_; }
|
||||
|
||||
private:
|
||||
std::vector<std::string> available_;
|
||||
};
|
||||
|
||||
class RequestTimeout : public HttpError {
|
||||
public:
|
||||
explicit RequestTimeout(std::string message = "request timeout")
|
||||
: HttpError(408, "request_timeout", std::move(message)) {}
|
||||
};
|
||||
|
||||
class PayloadTooLarge : public HttpError {
|
||||
public:
|
||||
explicit PayloadTooLarge(std::string message = "payload too large")
|
||||
: HttpError(413, "payload_too_large", std::move(message)) {}
|
||||
};
|
||||
|
||||
class UriTooLong : public HttpError {
|
||||
public:
|
||||
explicit UriTooLong(std::string message = "uri too long")
|
||||
: HttpError(414, "uri_too_long", std::move(message)) {}
|
||||
};
|
||||
|
||||
class HeaderFieldsTooLarge : public HttpError {
|
||||
public:
|
||||
explicit HeaderFieldsTooLarge(std::string message = "header fields too large")
|
||||
: HttpError(431, "header_fields_too_large", std::move(message)) {}
|
||||
};
|
||||
|
||||
class UnsupportedMediaType : public HttpError {
|
||||
public:
|
||||
explicit UnsupportedMediaType(std::string message = "unsupported media type")
|
||||
: HttpError(415, "unsupported_media_type", std::move(message)) {}
|
||||
};
|
||||
|
||||
class ValidationFailed : public HttpError {
|
||||
public:
|
||||
explicit ValidationFailed(validate::ValidationError cause)
|
||||
: HttpError(422, "validation_failed", "validation failed"), cause_(std::move(cause)) {}
|
||||
const validate::ValidationError& cause() const { return cause_; }
|
||||
|
||||
private:
|
||||
validate::ValidationError cause_;
|
||||
};
|
||||
|
||||
class TooManyRequests : public HttpError {
|
||||
public:
|
||||
explicit TooManyRequests(std::string message = "too many requests")
|
||||
: HttpError(429, "too_many_requests", std::move(message)) {}
|
||||
};
|
||||
|
||||
class Gone : public HttpError {
|
||||
public:
|
||||
explicit Gone(std::string message = "gone")
|
||||
: HttpError(410, "gone", std::move(message)) {}
|
||||
};
|
||||
|
||||
// Tenant errors (PATCHES 11.13), real subclass style.
|
||||
class TenantUnknown : public HttpError {
|
||||
public:
|
||||
explicit TenantUnknown(std::string message = "tenant unknown")
|
||||
: HttpError(404, "tenant_unknown", std::move(message)) {}
|
||||
};
|
||||
|
||||
class TenantSuspended : public HttpError {
|
||||
public:
|
||||
explicit TenantSuspended(std::string message = "tenant suspended")
|
||||
: HttpError(403, "tenant_suspended", std::move(message)) {}
|
||||
};
|
||||
|
||||
class TenantConflict : public HttpError {
|
||||
public:
|
||||
explicit TenantConflict(std::string message = "tenant conflict")
|
||||
: HttpError(400, "tenant_conflict", std::move(message)) {}
|
||||
};
|
||||
|
||||
class InsufficientStorage : public HttpError {
|
||||
public:
|
||||
explicit InsufficientStorage(std::string message = "insufficient storage")
|
||||
: HttpError(507, "insufficient_storage", std::move(message)) {}
|
||||
};
|
||||
|
||||
class InternalError : public HttpError {
|
||||
public:
|
||||
explicit InternalError(std::string message = "internal server error")
|
||||
: HttpError(500, "internal_error", std::move(message)) {}
|
||||
};
|
||||
|
||||
class Unavailable : public HttpError {
|
||||
public:
|
||||
explicit Unavailable(std::string message = "service unavailable")
|
||||
: HttpError(503, "unavailable", std::move(message)) {}
|
||||
};
|
||||
|
||||
} // namespace molo::app::errors
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::forms::Form. Binds application/json,
|
||||
// application/x-www-form-urlencoded and multipart/form-data into a
|
||||
// validate::Model (plan 05, R2, E10). One entry point, content-type
|
||||
// dispatch inside. Status policy: malformed shape, bad JSON and depth
|
||||
// overrun yield 400; size and count overruns (document, value, file,
|
||||
// total, field count) yield 413.
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../validate/errors.h"
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/model.h"
|
||||
#include "../validate/value.h"
|
||||
#include "multipart.h"
|
||||
#include "urlencoded.h"
|
||||
|
||||
namespace molo::app::forms {
|
||||
|
||||
struct FormData {
|
||||
validate::Object fields;
|
||||
std::vector<FileUpload> files;
|
||||
};
|
||||
|
||||
class Form {
|
||||
public:
|
||||
static FormData parse_body(const http_msg::Request& req,
|
||||
std::size_t max_json_document = caps::kMaxJsonDocument) {
|
||||
std::string ctype = req.content_type();
|
||||
if (ctype == "application/json") return parse_json_body(req.body(), max_json_document);
|
||||
if (ctype == "application/x-www-form-urlencoded") {
|
||||
FormData out;
|
||||
try {
|
||||
out.fields = parse_urlencoded(req.body());
|
||||
} catch (const std::length_error& e) {
|
||||
throw errors::PayloadTooLarge(e.what());
|
||||
} catch (const std::exception& e) {
|
||||
throw errors::BadRequest(e.what());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (ctype == "multipart/form-data") {
|
||||
FormData out;
|
||||
try {
|
||||
MultipartBody body =
|
||||
parse_multipart(req.headers().get("content-type"), req.body());
|
||||
out.fields = std::move(body.fields);
|
||||
out.files = std::move(body.files);
|
||||
} catch (const std::length_error& e) {
|
||||
throw errors::PayloadTooLarge(e.what());
|
||||
} catch (const errors::HttpError&) {
|
||||
throw;
|
||||
} catch (const std::exception& e) {
|
||||
throw errors::BadRequest(e.what());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
throw errors::UnsupportedMediaType("unsupported form content type: " + ctype);
|
||||
}
|
||||
|
||||
// Parse then validate into a clean object. Throws ValidationFailed (422)
|
||||
// carrying every field failure (R3).
|
||||
static validate::Object bind(const http_msg::Request& req, const validate::Model& model,
|
||||
const std::string& source = "body",
|
||||
std::size_t max_json_document = caps::kMaxJsonDocument) {
|
||||
FormData data = parse_body(req, max_json_document);
|
||||
try {
|
||||
return model.validate(data.fields, source);
|
||||
} catch (const validate::ValidationError& e) {
|
||||
throw errors::ValidationFailed(e);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static FormData parse_json_body(const std::string& body, std::size_t max_doc) {
|
||||
if (max_doc == 0 && !body.empty()) {
|
||||
throw errors::PayloadTooLarge("route rejects bodies");
|
||||
}
|
||||
if (body.size() > max_doc) throw errors::PayloadTooLarge("JSON document too large");
|
||||
FormData out;
|
||||
validate::Value v;
|
||||
try {
|
||||
v = validate::parse_json(body);
|
||||
} catch (const validate::JsonError& e) {
|
||||
throw errors::BadRequest(e.what());
|
||||
}
|
||||
if (!v.is_object()) throw errors::BadRequest("JSON body must be an object");
|
||||
out.fields = *std::get_if<validate::Object>(&v.storage());
|
||||
if (out.fields.size() > caps::kMaxFormFields) {
|
||||
throw errors::BadRequest("too many JSON fields");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::app::forms
|
||||
@@ -0,0 +1,127 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::forms multipart binding. Parses multipart/form-data field
|
||||
// parts into an Object; file parts become FileUpload records (bytes held in
|
||||
// memory under the standalone caps; quota policy and scanning belong to
|
||||
// 03-security, wired through Application on integration).
|
||||
|
||||
#include <cctype>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "../validate/value.h"
|
||||
|
||||
namespace molo::app::forms {
|
||||
|
||||
struct FileUpload {
|
||||
std::string field;
|
||||
std::string filename;
|
||||
std::string content_type = "application/octet-stream";
|
||||
std::string data;
|
||||
};
|
||||
|
||||
struct MultipartBody {
|
||||
validate::Object fields;
|
||||
std::vector<FileUpload> files;
|
||||
};
|
||||
|
||||
inline std::string multipart_boundary(std::string_view content_type_header) {
|
||||
std::string lower(content_type_header);
|
||||
for (char& c : lower) c = (char)std::tolower((unsigned char)c);
|
||||
std::string::size_type pos = lower.find("boundary=");
|
||||
if (pos == std::string::npos) return "";
|
||||
std::string b(content_type_header.substr(pos + 9));
|
||||
while (!b.empty() && (b.back() == ' ' || b.back() == '\t' || b.back() == '"')) b.pop_back();
|
||||
while (!b.empty() && (b.front() == ' ' || b.front() == '\t' || b.front() == '"'))
|
||||
b.erase(b.begin());
|
||||
return b;
|
||||
}
|
||||
|
||||
inline std::string part_header_attr(std::string_view headers, std::string_view attr) {
|
||||
std::string lower(headers);
|
||||
for (char& c : lower) c = (char)std::tolower((unsigned char)c);
|
||||
std::string key(attr);
|
||||
for (char& c : key) c = (char)std::tolower((unsigned char)c);
|
||||
key += "=\"";
|
||||
std::string::size_type pos = lower.find(key);
|
||||
if (pos == std::string::npos) {
|
||||
key = std::string(attr) + "=";
|
||||
for (char& c : key) c = (char)std::tolower((unsigned char)c);
|
||||
pos = lower.find(key);
|
||||
if (pos == std::string::npos) return "";
|
||||
std::string::size_type start = pos + key.size();
|
||||
std::string::size_type end = lower.find_first_of("; \t\r\n", start);
|
||||
return std::string(headers.substr(start, end - start));
|
||||
}
|
||||
std::string::size_type start = pos + key.size();
|
||||
std::string::size_type end = headers.find('"', start);
|
||||
if (end == std::string_view::npos) return "";
|
||||
return std::string(headers.substr(start, end - start));
|
||||
}
|
||||
|
||||
inline MultipartBody parse_multipart(std::string_view content_type_header, std::string_view body) {
|
||||
std::string boundary = multipart_boundary(content_type_header);
|
||||
if (boundary.empty()) throw std::runtime_error("multipart body without boundary");
|
||||
if (body.size() > caps::kMaxMultipartTotal) throw std::length_error("multipart body too large");
|
||||
MultipartBody out;
|
||||
std::string delim = "--" + boundary;
|
||||
std::string end_delim = delim + "--";
|
||||
std::size_t pos = 0;
|
||||
std::size_t field_count = 0;
|
||||
while (true) {
|
||||
std::size_t start = body.find(delim, pos);
|
||||
if (start == std::string_view::npos) break;
|
||||
start += delim.size();
|
||||
if (body.substr(start, 2) == "--") break;
|
||||
if (body.substr(start, 2) == "\r\n") start += 2;
|
||||
std::size_t head_end = body.find("\r\n\r\n", start);
|
||||
if (head_end == std::string_view::npos) break;
|
||||
std::string_view headers = body.substr(start, head_end - start);
|
||||
std::size_t data_start = head_end + 4;
|
||||
std::size_t next = body.find(delim, data_start);
|
||||
if (next == std::string_view::npos) break;
|
||||
std::size_t data_end = next;
|
||||
if (data_end >= 2 && body.substr(data_end - 2, 2) == "\r\n") data_end -= 2;
|
||||
std::string data(body.substr(data_start, data_end - data_start));
|
||||
std::string name = part_header_attr(headers, "name");
|
||||
std::string filename = part_header_attr(headers, "filename");
|
||||
if (name.size() > caps::kMaxFieldName) throw std::length_error("form field name too long");
|
||||
if (filename.empty()) {
|
||||
if (field_count >= caps::kMaxFormFields) throw std::length_error("too many form fields");
|
||||
if (data.size() > caps::kMaxNonFileValue) throw std::length_error("form value too large");
|
||||
out.fields[std::move(name)] = validate::Value(std::move(data));
|
||||
++field_count;
|
||||
} else {
|
||||
if (out.files.size() >= caps::kMaxMultipartFiles) {
|
||||
throw std::length_error("too many uploaded files");
|
||||
}
|
||||
if (data.size() > caps::kMaxFileBytes) throw std::length_error("uploaded file too large");
|
||||
FileUpload upload;
|
||||
upload.field = std::move(name);
|
||||
upload.filename = std::move(filename);
|
||||
std::string ctype = part_header_attr(headers, "content-type");
|
||||
// Content-Type of a part is a full header line, not an attr; parse it.
|
||||
std::string lower(headers);
|
||||
for (char& c : lower) c = (char)std::tolower((unsigned char)c);
|
||||
std::string::size_type cpos = lower.find("content-type:");
|
||||
if (cpos != std::string::npos) {
|
||||
std::string::size_type vstart = cpos + 13;
|
||||
while (vstart < headers.size() && (headers[vstart] == ' ' || headers[vstart] == '\t'))
|
||||
++vstart;
|
||||
std::string::size_type vend = headers.find("\r", vstart);
|
||||
ctype = std::string(headers.substr(vstart, vend - vstart));
|
||||
std::string::size_type semi = ctype.find(';');
|
||||
if (semi != std::string::npos) ctype = ctype.substr(0, semi);
|
||||
}
|
||||
if (!ctype.empty()) upload.content_type = ctype;
|
||||
upload.data = std::move(data);
|
||||
out.files.push_back(std::move(upload));
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::forms
|
||||
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::forms urlencoded binding. Parses
|
||||
// application/x-www-form-urlencoded into an Object (last value wins per key,
|
||||
// full multimap available). Caps from caps.h.
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "../http_msg/query.h"
|
||||
#include "../validate/value.h"
|
||||
|
||||
namespace molo::app::forms {
|
||||
|
||||
inline validate::Object parse_urlencoded(std::string_view body) {
|
||||
validate::Object out;
|
||||
std::size_t count = 0;
|
||||
std::size_t i = 0;
|
||||
while (i <= body.size()) {
|
||||
std::size_t amp = body.find('&', i);
|
||||
if (amp == std::string_view::npos) amp = body.size();
|
||||
std::string_view pair = body.substr(i, amp - i);
|
||||
if (!pair.empty()) {
|
||||
if (count >= caps::kMaxFormFields) throw std::length_error("too many form fields");
|
||||
std::size_t eq = pair.find('=');
|
||||
std::string_view k = (eq == std::string_view::npos) ? pair : pair.substr(0, eq);
|
||||
std::string_view v = (eq == std::string_view::npos) ? "" : pair.substr(eq + 1);
|
||||
std::string key = http_msg::percent_decode(k, true);
|
||||
std::string val = http_msg::percent_decode(v, true);
|
||||
if (key.size() > caps::kMaxFieldName) throw std::length_error("form field name too long");
|
||||
if (val.size() > caps::kMaxNonFileValue) throw std::length_error("form value too large");
|
||||
out[std::move(key)] = validate::Value(std::move(val));
|
||||
++count;
|
||||
}
|
||||
if (amp == body.size()) break;
|
||||
i = amp + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::vector<std::pair<std::string, std::string>> parse_urlencoded_multi(
|
||||
std::string_view body) {
|
||||
std::vector<std::pair<std::string, std::string>> out;
|
||||
std::size_t i = 0;
|
||||
while (i <= body.size()) {
|
||||
std::size_t amp = body.find('&', i);
|
||||
if (amp == std::string_view::npos) amp = body.size();
|
||||
std::string_view pair = body.substr(i, amp - i);
|
||||
if (!pair.empty()) {
|
||||
if (out.size() >= caps::kMaxFormFields) throw std::length_error("too many form fields");
|
||||
std::size_t eq = pair.find('=');
|
||||
std::string_view k = (eq == std::string_view::npos) ? pair : pair.substr(0, eq);
|
||||
std::string_view v = (eq == std::string_view::npos) ? "" : pair.substr(eq + 1);
|
||||
out.emplace_back(http_msg::percent_decode(k, true), http_msg::percent_decode(v, true));
|
||||
}
|
||||
if (amp == body.size()) break;
|
||||
i = amp + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::forms
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::Cookies. Read-only cookie view parsed from the
|
||||
// Cookie header. Signing and encryption live in 03-security; this is the
|
||||
// plain view plus a Set-Cookie builder for simple values.
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "query.h"
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
class Cookies {
|
||||
public:
|
||||
static Cookies parse(std::string_view header) {
|
||||
Cookies c;
|
||||
std::size_t i = 0;
|
||||
while (i < header.size()) {
|
||||
while (i < header.size() && (header[i] == ' ' || header[i] == ';')) ++i;
|
||||
if (i >= header.size()) break;
|
||||
std::size_t semi = header.find(';', i);
|
||||
if (semi == std::string_view::npos) semi = header.size();
|
||||
std::string_view pair = header.substr(i, semi - i);
|
||||
std::size_t eq = pair.find('=');
|
||||
std::string name = eq == std::string_view::npos
|
||||
? std::string(pair)
|
||||
: std::string(pair.substr(0, eq));
|
||||
std::string value =
|
||||
eq == std::string_view::npos ? "" : percent_decode(pair.substr(eq + 1), false);
|
||||
while (!name.empty() && name.back() == ' ') name.pop_back();
|
||||
if (!name.empty()) {
|
||||
if (c.items_.size() >= caps::kMaxCookies) break;
|
||||
c.items_.emplace_back(name, value);
|
||||
}
|
||||
i = semi + 1;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
std::string get(std::string_view name) const {
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == name) return kv.second;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
bool has(std::string_view name) const {
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == name) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::vector<std::pair<std::string, std::string>>& items() const { return items_; }
|
||||
|
||||
private:
|
||||
std::vector<std::pair<std::string, std::string>> items_;
|
||||
};
|
||||
|
||||
struct SetCookie {
|
||||
std::string name;
|
||||
std::string value;
|
||||
std::string path = "/";
|
||||
std::string same_site = "Lax";
|
||||
bool http_only = true;
|
||||
bool secure = false;
|
||||
long max_age = -1;
|
||||
|
||||
std::string render() const {
|
||||
std::string out = name + "=" + percent_encode(value) + "; Path=" + path;
|
||||
if (max_age >= 0) out += "; Max-Age=" + std::to_string(max_age);
|
||||
if (http_only) out += "; HttpOnly";
|
||||
if (secure) out += "; Secure";
|
||||
out += "; SameSite=" + same_site;
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,95 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::Headers. Case-insensitive header multimap.
|
||||
// Lookup lowercases the name. Count and size caps from caps.h guard
|
||||
// standalone parsing; the runtime enforces wire caps first.
|
||||
|
||||
#include <cctype>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
inline std::string lower_header_name(std::string_view name) {
|
||||
std::string out(name);
|
||||
for (char& c : out) c = (char)std::tolower((unsigned char)c);
|
||||
return out;
|
||||
}
|
||||
|
||||
class Headers {
|
||||
public:
|
||||
void set(std::string name, std::string value) {
|
||||
if (name.size() > caps::kMaxHeaderName) throw std::length_error("header name too long");
|
||||
if (value.size() > caps::kMaxHeaderValue) throw std::length_error("header value too long");
|
||||
std::string key = lower_header_name(name);
|
||||
for (auto& kv : items_) {
|
||||
if (kv.first == key) {
|
||||
kv.second = value;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (items_.size() >= caps::kMaxHeaders) throw std::length_error("too many headers");
|
||||
items_.emplace_back(key, value);
|
||||
}
|
||||
|
||||
void add(std::string name, std::string value) {
|
||||
if (name.size() > caps::kMaxHeaderName) throw std::length_error("header name too long");
|
||||
if (value.size() > caps::kMaxHeaderValue) throw std::length_error("header value too long");
|
||||
if (items_.size() >= caps::kMaxHeaders) throw std::length_error("too many headers");
|
||||
items_.emplace_back(lower_header_name(name), value);
|
||||
}
|
||||
|
||||
std::string get(std::string_view name) const {
|
||||
std::string key = lower_header_name(name);
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == key) return kv.second;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string get_or(std::string_view name, std::string fallback) const {
|
||||
std::string key = lower_header_name(name);
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == key) return kv.second;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
bool contains(std::string_view name) const {
|
||||
std::string key = lower_header_name(name);
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == key) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::string> get_all(std::string_view name) const {
|
||||
std::string key = lower_header_name(name);
|
||||
std::vector<std::string> out;
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first == key) out.push_back(kv.second);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void remove(std::string_view name) {
|
||||
std::string key = lower_header_name(name);
|
||||
std::vector<std::pair<std::string, std::string>> kept;
|
||||
for (const auto& kv : items_) {
|
||||
if (kv.first != key) kept.push_back(kv);
|
||||
}
|
||||
items_.swap(kept);
|
||||
}
|
||||
|
||||
const std::vector<std::pair<std::string, std::string>>& items() const { return items_; }
|
||||
std::size_t size() const { return items_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<std::pair<std::string, std::string>> items_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::escape_html. Shared HTML escaper for error
|
||||
// pages and template filters (one implementation, plan 05 section 9).
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
inline std::string escape_html(std::string_view s) {
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (char c : s) {
|
||||
switch (c) {
|
||||
case '&': out += "&"; break;
|
||||
case '<': out += "<"; break;
|
||||
case '>': out += ">"; break;
|
||||
case '"': out += """; break;
|
||||
case '\'': out += "'"; break;
|
||||
default: out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string escape_xml(std::string_view s) {
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (char c : s) {
|
||||
switch (c) {
|
||||
case '&': out += "&"; break;
|
||||
case '<': out += "<"; break;
|
||||
case '>': out += ">"; break;
|
||||
case '"': out += """; break;
|
||||
case '\'': out += "'"; break;
|
||||
default: out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::Method. HTTP methods supported on routes.
|
||||
// Covers server methods; WebDAV extras arrive with 06-realtime.
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
enum class Method { GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS };
|
||||
|
||||
inline std::string to_string(Method m) {
|
||||
switch (m) {
|
||||
case Method::GET: return "GET";
|
||||
case Method::POST: return "POST";
|
||||
case Method::PUT: return "PUT";
|
||||
case Method::PATCH: return "PATCH";
|
||||
case Method::DELETE: return "DELETE";
|
||||
case Method::HEAD: return "HEAD";
|
||||
case Method::OPTIONS: return "OPTIONS";
|
||||
}
|
||||
return "GET";
|
||||
}
|
||||
|
||||
inline std::optional<Method> parse_method(std::string_view s) {
|
||||
if (s == "GET") return Method::GET;
|
||||
if (s == "POST") return Method::POST;
|
||||
if (s == "PUT") return Method::PUT;
|
||||
if (s == "PATCH") return Method::PATCH;
|
||||
if (s == "DELETE") return Method::DELETE;
|
||||
if (s == "HEAD") return Method::HEAD;
|
||||
if (s == "OPTIONS") return Method::OPTIONS;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg percent-decoding and Query multimap.
|
||||
// Query holds repeated keys in arrival order. Parsing caps come from caps.h.
|
||||
|
||||
#include <cctype>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
inline int hex_val(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline std::string percent_decode(std::string_view s, bool plus_is_space) {
|
||||
std::string out;
|
||||
out.reserve(s.size());
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
char c = s[i];
|
||||
if (c == '+' && plus_is_space) {
|
||||
out += ' ';
|
||||
} else if (c == '%' && i + 2 < s.size()) {
|
||||
int hi = hex_val(s[i + 1]);
|
||||
int lo = hex_val(s[i + 2]);
|
||||
if (hi >= 0 && lo >= 0) {
|
||||
out += (char)((hi << 4) | lo);
|
||||
i += 2;
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::string percent_encode(std::string_view s) {
|
||||
static const char* kHex = "0123456789ABCDEF";
|
||||
std::string out;
|
||||
for (unsigned char c : s) {
|
||||
bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||
c == '-' || c == '_' || c == '.' || c == '~';
|
||||
if (plain) {
|
||||
out += (char)c;
|
||||
} else {
|
||||
out += '%';
|
||||
out += kHex[c >> 4];
|
||||
out += kHex[c & 15];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
class Query {
|
||||
public:
|
||||
static Query parse(std::string_view raw) {
|
||||
Query q;
|
||||
std::size_t i = 0;
|
||||
if (!raw.empty() && raw[0] == '?') i = 1;
|
||||
while (i <= raw.size()) {
|
||||
std::size_t amp = raw.find('&', i);
|
||||
if (amp == std::string_view::npos) amp = raw.size();
|
||||
std::string_view pair = raw.substr(i, amp - i);
|
||||
if (!pair.empty()) {
|
||||
if (q.params_.size() >= caps::kMaxQueryParams) {
|
||||
throw std::length_error("too many query params");
|
||||
}
|
||||
std::size_t eq = pair.find('=');
|
||||
std::string_view k = (eq == std::string_view::npos) ? pair : pair.substr(0, eq);
|
||||
std::string_view v = (eq == std::string_view::npos) ? "" : pair.substr(eq + 1);
|
||||
q.params_.emplace_back(percent_decode(k, true), percent_decode(v, true));
|
||||
}
|
||||
if (amp == raw.size()) break;
|
||||
i = amp + 1;
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
void add(std::string key, std::string value) {
|
||||
if (params_.size() >= caps::kMaxQueryParams) throw std::length_error("too many query params");
|
||||
params_.emplace_back(std::move(key), std::move(value));
|
||||
}
|
||||
|
||||
std::string get_first(std::string_view key) const {
|
||||
for (const auto& kv : params_) {
|
||||
if (kv.first == key) return kv.second;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
bool has(std::string_view key) const {
|
||||
for (const auto& kv : params_) {
|
||||
if (kv.first == key) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::string> get_all(std::string_view key) const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& kv : params_) {
|
||||
if (kv.first == key) out.push_back(kv.second);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::vector<std::pair<std::string, std::string>>& items() const { return params_; }
|
||||
std::size_t size() const { return params_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<std::pair<std::string, std::string>> params_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,138 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::Request. One request object per handler call
|
||||
// (plan 05, R1). Carries method, path, parsed query, headers, cookie view,
|
||||
// body, matched route plus path params, owning app pointer, request ID, and
|
||||
// a typed extension map for middleware, DI and validation results.
|
||||
// Body and header byte caps are enforced by 01-runtime before this layer.
|
||||
|
||||
#include <any>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "../validate/value.h"
|
||||
#include "cookies.h"
|
||||
#include "headers.h"
|
||||
#include "method.h"
|
||||
#include "query.h"
|
||||
|
||||
namespace molo::app::routing {
|
||||
class Route;
|
||||
}
|
||||
|
||||
namespace molo::app::app {
|
||||
class Application;
|
||||
}
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
class Request {
|
||||
public:
|
||||
Request() = default;
|
||||
Request(Method method, std::string path, Query query = Query(),
|
||||
Headers headers = Headers(), std::string body = "")
|
||||
: method_(method),
|
||||
path_(std::move(path)),
|
||||
query_(std::move(query)),
|
||||
headers_(std::move(headers)),
|
||||
body_(std::move(body)),
|
||||
cookies_(Cookies::parse(headers_.get("cookie"))) {}
|
||||
|
||||
Method method() const { return method_; }
|
||||
std::string method_string() const { return to_string(method_); }
|
||||
const std::string& path() const { return path_; }
|
||||
void set_path(std::string p) { path_ = std::move(p); }
|
||||
const Query& query() const { return query_; }
|
||||
Query& query() { return query_; }
|
||||
const std::string& query_raw() const { return query_raw_; }
|
||||
void set_query_raw(std::string q) { query_raw_ = std::move(q); }
|
||||
const Headers& headers() const { return headers_; }
|
||||
Headers& headers() { return headers_; }
|
||||
const Cookies& cookies() const { return cookies_; }
|
||||
const std::string& body() const { return body_; }
|
||||
void set_body(std::string b) { body_ = std::move(b); }
|
||||
|
||||
// Query shortcut: first value or fallback.
|
||||
std::string get(std::string_view key, std::string fallback = "") const {
|
||||
if (query_.has(key)) return query_.get_first(key);
|
||||
return fallback;
|
||||
}
|
||||
std::string header(std::string_view name) const { return headers_.get(name); }
|
||||
std::string cookie(std::string_view name) const { return cookies_.get(name); }
|
||||
|
||||
// Content-Type without parameters, lowercased.
|
||||
std::string content_type() const {
|
||||
std::string ct = headers_.get("content-type");
|
||||
std::size_t semi = ct.find(';');
|
||||
if (semi != std::string::npos) ct = ct.substr(0, semi);
|
||||
while (!ct.empty() && (ct.back() == ' ' || ct.back() == '\t')) ct.pop_back();
|
||||
std::size_t start = 0;
|
||||
while (start < ct.size() && (ct[start] == ' ' || ct[start] == '\t')) ++start;
|
||||
std::string out = ct.substr(start);
|
||||
for (char& c : out) c = (char)std::tolower((unsigned char)c);
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::map<std::string, std::string>& path_params() const { return path_params_; }
|
||||
std::string path_param(std::string_view name) const {
|
||||
auto it = path_params_.find(std::string(name));
|
||||
return it == path_params_.end() ? "" : it->second;
|
||||
}
|
||||
void set_path_param(std::string name, std::string value) {
|
||||
path_params_[std::move(name)] = std::move(value);
|
||||
}
|
||||
|
||||
const routing::Route* route() const { return route_; }
|
||||
void set_route(const routing::Route* r) { route_ = r; }
|
||||
|
||||
app::Application* app() const { return app_; }
|
||||
void set_app(app::Application* a) { app_ = a; }
|
||||
|
||||
const std::string& request_id() const { return request_id_; }
|
||||
void set_request_id(std::string id) { request_id_ = std::move(id); }
|
||||
|
||||
// Validated binding results, keyed by source ("query", "body", ...).
|
||||
void set_validated(std::string source, validate::Object obj) {
|
||||
validated_[std::move(source)] = std::move(obj);
|
||||
}
|
||||
const validate::Object* validated(std::string_view source) const {
|
||||
auto it = validated_.find(std::string(source));
|
||||
return it == validated_.end() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
// Typed extension slot for middleware and DI.
|
||||
template <typename T>
|
||||
void set_ext(std::string key, T value) {
|
||||
ext_[std::move(key)] = std::any(std::move(value));
|
||||
}
|
||||
template <typename T>
|
||||
T* get_ext(const std::string& key) {
|
||||
auto it = ext_.find(key);
|
||||
if (it == ext_.end()) return nullptr;
|
||||
return std::any_cast<T>(&it->second);
|
||||
}
|
||||
template <typename T>
|
||||
const T* get_ext(const std::string& key) const {
|
||||
auto it = ext_.find(key);
|
||||
if (it == ext_.end()) return nullptr;
|
||||
return std::any_cast<T>(&it->second);
|
||||
}
|
||||
void clear_ext(const std::string& key) { ext_.erase(key); }
|
||||
|
||||
private:
|
||||
Method method_ = Method::GET;
|
||||
std::string path_ = "/";
|
||||
std::string query_raw_;
|
||||
Query query_;
|
||||
Headers headers_;
|
||||
std::string body_;
|
||||
Cookies cookies_;
|
||||
std::map<std::string, std::string> path_params_;
|
||||
const routing::Route* route_ = nullptr;
|
||||
app::Application* app_ = nullptr;
|
||||
std::string request_id_;
|
||||
std::map<std::string, validate::Object> validated_;
|
||||
std::map<std::string, std::any> ext_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,155 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::http_msg::Response hierarchy (plan 05, R1, R4, E1).
|
||||
// Response is a value type: status, headers, body, plus an extension payload
|
||||
// for streaming and negotiated variants, so returning by value never slices.
|
||||
// Subclasses only preset fields. All string-taking constructors are explicit
|
||||
// (R4: no implicit conversion of a raw string to a 200 text response).
|
||||
|
||||
#include <any>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/value.h"
|
||||
#include "headers.h"
|
||||
|
||||
namespace molo::app::http_msg {
|
||||
|
||||
class Response {
|
||||
public:
|
||||
explicit Response(int status = 200, std::string body = "",
|
||||
std::string content_type = "text/plain; charset=utf-8")
|
||||
: status_(status), body_(std::move(body)) {
|
||||
headers_.set("content-type", std::move(content_type));
|
||||
}
|
||||
|
||||
int status() const { return status_; }
|
||||
void set_status(int s) { status_ = s; }
|
||||
const std::string& body() const { return body_; }
|
||||
void set_body(std::string b) { body_ = std::move(b); }
|
||||
const Headers& headers() const { return headers_; }
|
||||
Headers& headers() { return headers_; }
|
||||
std::string content_type() const { return headers_.get("content-type"); }
|
||||
void set_content_type(std::string ct) { headers_.set("content-type", std::move(ct)); }
|
||||
|
||||
template <typename T>
|
||||
void set_payload(T value) {
|
||||
payload_ = std::any(std::move(value));
|
||||
}
|
||||
template <typename T>
|
||||
T* get_payload() {
|
||||
return std::any_cast<T>(&payload_);
|
||||
}
|
||||
template <typename T>
|
||||
const T* get_payload() const {
|
||||
return std::any_cast<T>(&payload_);
|
||||
}
|
||||
bool has_payload() const { return payload_.has_value(); }
|
||||
|
||||
protected:
|
||||
int status_ = 200;
|
||||
Headers headers_;
|
||||
std::string body_;
|
||||
std::any payload_;
|
||||
};
|
||||
|
||||
class TextResponse : public Response {
|
||||
public:
|
||||
explicit TextResponse(std::string body, int status = 200)
|
||||
: Response(status, std::move(body), "text/plain; charset=utf-8") {}
|
||||
};
|
||||
|
||||
class HtmlResponse : public Response {
|
||||
public:
|
||||
explicit HtmlResponse(std::string body, int status = 200)
|
||||
: Response(status, std::move(body), "text/html; charset=utf-8") {}
|
||||
};
|
||||
|
||||
class XmlResponse : public Response {
|
||||
public:
|
||||
explicit XmlResponse(std::string body, int status = 200)
|
||||
: Response(status, std::move(body), "application/xml; charset=utf-8") {}
|
||||
};
|
||||
|
||||
class JsonResponse : public Response {
|
||||
public:
|
||||
explicit JsonResponse(validate::Value value, int status = 200)
|
||||
: Response(status, validate::to_json(value), "application/json") {}
|
||||
explicit JsonResponse(std::string raw_json, int status = 200)
|
||||
: Response(status, std::move(raw_json), "application/json") {}
|
||||
};
|
||||
|
||||
class RedirectResponse : public Response {
|
||||
public:
|
||||
// Method-preserving redirects: 308 permanent, 307 temporary.
|
||||
explicit RedirectResponse(std::string url, bool permanent = false)
|
||||
: Response(permanent ? 308 : 307, "") {
|
||||
headers_.set("location", std::move(url));
|
||||
}
|
||||
static RedirectResponse temporary(std::string url) { return RedirectResponse(std::move(url), false); }
|
||||
static RedirectResponse permanent(std::string url) { return RedirectResponse(std::move(url), true); }
|
||||
};
|
||||
|
||||
class FileResponse : public Response {
|
||||
public:
|
||||
explicit FileResponse(std::string content, std::string content_type,
|
||||
std::string filename = "", int status = 200)
|
||||
: Response(status, std::move(content), std::move(content_type)) {
|
||||
if (!filename.empty()) {
|
||||
headers_.set("content-disposition", "attachment; filename=\"" + filename + "\"");
|
||||
}
|
||||
headers_.set("accept-ranges", "bytes");
|
||||
}
|
||||
};
|
||||
|
||||
// Streaming shell: chunk mechanics live in 06-realtime; the class shell
|
||||
// lives here (plan 05, section 3). The producer returns the next chunk or
|
||||
// nullopt when done. collect() materializes with a byte cap.
|
||||
struct StreamPayload {
|
||||
std::function<std::optional<std::string>()> producer;
|
||||
};
|
||||
|
||||
class StreamingResponse : public Response {
|
||||
public:
|
||||
explicit StreamingResponse(std::function<std::optional<std::string>()> producer,
|
||||
std::string content_type = "text/plain; charset=utf-8",
|
||||
int status = 200)
|
||||
: Response(status, "", std::move(content_type)) {
|
||||
set_payload(StreamPayload{std::move(producer)});
|
||||
}
|
||||
|
||||
std::string collect(std::size_t max_bytes) {
|
||||
auto* p = get_payload<StreamPayload>();
|
||||
if (p == nullptr) return body_;
|
||||
std::string out;
|
||||
while (true) {
|
||||
std::optional<std::string> chunk = p->producer();
|
||||
if (!chunk.has_value()) break;
|
||||
if (out.size() + chunk->size() > max_bytes) break;
|
||||
out += *chunk;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
// Negotiated variant: holds one data value plus the media types the route
|
||||
// can render it as. NegotiationMiddleware (molo::app::middleware) replaces
|
||||
// the body and content type with the negotiated representation, or answers
|
||||
// 406 when nothing matches. Concrete responses pass through untouched.
|
||||
struct VariantPayload {
|
||||
validate::Value data;
|
||||
std::vector<std::string> available;
|
||||
};
|
||||
|
||||
class VariantResponse : public Response {
|
||||
public:
|
||||
explicit VariantResponse(validate::Value data, std::vector<std::string> available)
|
||||
: Response(200, "") {
|
||||
set_payload(VariantPayload{std::move(data), std::move(available)});
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::app::http_msg
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::middleware built-ins (plan 05, section 6 Middleware).
|
||||
// ExceptionMappingMiddleware (outermost, category Errors) converts thrown
|
||||
// errors to rendered responses. NegotiationMiddleware (RouterAdjacent)
|
||||
// enforces consumes (415) and renders VariantResponse in the negotiated
|
||||
// format (406 when nothing matches). CORS policy belongs to 03-security;
|
||||
// these layers only preserve headers they do not own.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../errors/handler.h"
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../negotiate/negotiator.h"
|
||||
#include "../routing/route.h"
|
||||
#include "../seams/request_id.h"
|
||||
#include "middleware.h"
|
||||
|
||||
namespace molo::app::middleware {
|
||||
|
||||
class ExceptionMappingMiddleware : public Middleware {
|
||||
public:
|
||||
explicit ExceptionMappingMiddleware(
|
||||
std::shared_ptr<errors::ErrorHandler> handler = std::make_shared<errors::ErrorHandler>())
|
||||
: handler_(std::move(handler)) {}
|
||||
|
||||
Category category() const override { return Category::Errors; }
|
||||
std::string name() const override { return "exception_mapping"; }
|
||||
|
||||
async::Task<http_msg::Response> handle(http_msg::Request& req, Next next) override {
|
||||
std::string rid = req.request_id().empty() ? seams::generate_request_id() : req.request_id();
|
||||
try {
|
||||
http_msg::Response res = co_await next(req);
|
||||
res.headers().set(seams::kRequestIdHeader, rid);
|
||||
co_return res;
|
||||
} catch (const errors::HttpError& e) {
|
||||
http_msg::Response res = handler_->render(e, req, rid);
|
||||
res.headers().set(seams::kRequestIdHeader, rid);
|
||||
co_return res;
|
||||
} catch (const validate::ValidationError& e) {
|
||||
errors::ValidationFailed wrapped(e);
|
||||
http_msg::Response res = handler_->render(wrapped, req, rid);
|
||||
res.headers().set(seams::kRequestIdHeader, rid);
|
||||
co_return res;
|
||||
} catch (const std::exception& e) {
|
||||
http_msg::Response res = handler_->render_unknown(req, rid, e.what());
|
||||
res.headers().set(seams::kRequestIdHeader, rid);
|
||||
co_return res;
|
||||
} catch (...) {
|
||||
http_msg::Response res = handler_->render_unknown(req, rid, "non-standard exception");
|
||||
res.headers().set(seams::kRequestIdHeader, rid);
|
||||
co_return res;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<errors::ErrorHandler> handler_;
|
||||
};
|
||||
|
||||
class NegotiationMiddleware : public Middleware {
|
||||
public:
|
||||
Category category() const override { return Category::RouterAdjacent; }
|
||||
std::string name() const override { return "negotiation"; }
|
||||
|
||||
async::Task<http_msg::Response> handle(http_msg::Request& req, Next next) override {
|
||||
const routing::Route* route = req.route();
|
||||
if (route == nullptr) {
|
||||
co_return co_await next(req);
|
||||
}
|
||||
negotiate::Negotiator::check_consumes(req.content_type(), route->options().consumes);
|
||||
http_msg::Response res = co_await next(req);
|
||||
auto* variant = res.get_payload<http_msg::VariantPayload>();
|
||||
if (variant == nullptr) co_return res;
|
||||
std::vector<std::string> produces = route->options().produces;
|
||||
if (produces.empty()) produces = variant->available;
|
||||
if (produces.empty()) produces = {"application/json"};
|
||||
std::string chosen = negotiate::Negotiator::select(
|
||||
req.headers().get("accept"), produces, route->options().allow_format_override,
|
||||
req.query().get_first("format"));
|
||||
auto rendered = negotiate::render_variant(variant->data, chosen);
|
||||
res.set_body(std::move(rendered.first));
|
||||
res.set_content_type(std::move(rendered.second));
|
||||
co_return res;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::app::middleware
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::middleware::Chain. Composes middleware in registration
|
||||
// order around a terminal handler. Category order is enforced at use():
|
||||
// adding a layer with a lower category than the previous one throws
|
||||
// ChainOrderError (startup error, R7). Layer count capped at 64.
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../caps.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "middleware.h"
|
||||
|
||||
namespace molo::app::middleware {
|
||||
|
||||
class ChainOrderError : public std::runtime_error {
|
||||
public:
|
||||
explicit ChainOrderError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class Chain {
|
||||
public:
|
||||
void use(std::shared_ptr<Middleware> layer) {
|
||||
if (layers_.size() >= caps::kMaxMiddlewareLayers) {
|
||||
throw ChainOrderError("too many middleware layers");
|
||||
}
|
||||
if (!layers_.empty() && layer->category() < layers_.back()->category()) {
|
||||
throw ChainOrderError(
|
||||
"middleware order violation: '" + layer->name() + "' (" +
|
||||
category_name(layer->category()) + ") registered after '" +
|
||||
layers_.back()->name() + "' (" + category_name(layers_.back()->category()) + ")");
|
||||
}
|
||||
layers_.push_back(std::move(layer));
|
||||
}
|
||||
|
||||
async::Task<http_msg::Response> run(
|
||||
http_msg::Request& req,
|
||||
std::function<async::Task<http_msg::Response>(http_msg::Request&)> terminal) {
|
||||
std::function<async::Task<http_msg::Response>(http_msg::Request&)> next = terminal;
|
||||
for (std::size_t i = layers_.size(); i-- > 0;) {
|
||||
std::shared_ptr<Middleware> layer = layers_[i];
|
||||
auto inner = next;
|
||||
next = [layer, inner](http_msg::Request& r) -> async::Task<http_msg::Response> {
|
||||
Next guard(inner);
|
||||
co_return co_await layer->handle(r, guard);
|
||||
};
|
||||
}
|
||||
co_return co_await next(req);
|
||||
}
|
||||
|
||||
const std::vector<std::shared_ptr<Middleware>>& layers() const { return layers_; }
|
||||
std::size_t size() const { return layers_.size(); }
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Middleware>> layers_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::middleware
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::middleware base (plan 05, R7, E8). Signature:
|
||||
// Task<Response> handle(Request, Next). Next invokes the remainder exactly
|
||||
// once; calling twice throws MiddlewareError. Category order is fixed:
|
||||
// Errors, Observability, Security, SessionAuth, User, RouterAdjacent.
|
||||
// Middleware must preserve the correlation/request ID.
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
|
||||
namespace molo::app::middleware {
|
||||
|
||||
enum class Category {
|
||||
Errors = 0,
|
||||
Observability = 1,
|
||||
Security = 2,
|
||||
SessionAuth = 3,
|
||||
User = 4,
|
||||
RouterAdjacent = 5
|
||||
};
|
||||
|
||||
inline std::string category_name(Category c) {
|
||||
switch (c) {
|
||||
case Category::Errors: return "errors";
|
||||
case Category::Observability: return "observability";
|
||||
case Category::Security: return "security";
|
||||
case Category::SessionAuth: return "session_auth";
|
||||
case Category::User: return "user";
|
||||
case Category::RouterAdjacent: return "router_adjacent";
|
||||
}
|
||||
return "user";
|
||||
}
|
||||
|
||||
class MiddlewareError : public std::runtime_error {
|
||||
public:
|
||||
explicit MiddlewareError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class Next {
|
||||
public:
|
||||
explicit Next(std::function<async::Task<http_msg::Response>(http_msg::Request&)> fn)
|
||||
: fn_(std::move(fn)), called_(std::make_shared<bool>(false)) {}
|
||||
|
||||
async::Task<http_msg::Response> operator()(http_msg::Request& req) const {
|
||||
if (*called_) throw MiddlewareError("Next invoked twice in one middleware");
|
||||
*called_ = true;
|
||||
co_return co_await fn_(req);
|
||||
}
|
||||
|
||||
private:
|
||||
std::function<async::Task<http_msg::Response>(http_msg::Request&)> fn_;
|
||||
std::shared_ptr<bool> called_;
|
||||
};
|
||||
|
||||
class Middleware {
|
||||
public:
|
||||
virtual ~Middleware() = default;
|
||||
virtual Category category() const = 0;
|
||||
virtual std::string name() const = 0;
|
||||
virtual async::Task<http_msg::Response> handle(http_msg::Request& req, Next next) = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::app::middleware
|
||||
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::negotiate Accept parser. Parses an Accept header into
|
||||
// media ranges (type, subtype, q, params). Missing or empty header means
|
||||
// */*. Invalid q values are treated as weight 0 (entry ignored), documented
|
||||
// leniency choice. Range params other than q are parsed and ignored for
|
||||
// matching (documented gap vs RFC 9110 section 12).
|
||||
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::app::negotiate {
|
||||
|
||||
struct MediaRange {
|
||||
std::string type;
|
||||
std::string subtype;
|
||||
double q = 1.0;
|
||||
std::vector<std::pair<std::string, std::string>> params;
|
||||
std::size_t order = 0;
|
||||
};
|
||||
|
||||
inline std::string trim_ws(std::string_view s) {
|
||||
std::size_t a = 0;
|
||||
while (a < s.size() && (s[a] == ' ' || s[a] == '\t')) ++a;
|
||||
std::size_t b = s.size();
|
||||
while (b > a && (s[b - 1] == ' ' || s[b - 1] == '\t')) --b;
|
||||
std::string out(s.substr(a, b - a));
|
||||
for (char& c : out) c = (char)std::tolower((unsigned char)c);
|
||||
return out;
|
||||
}
|
||||
|
||||
inline double parse_q(std::string_view s) {
|
||||
if (s.empty() || s.size() > 5) return 0.0;
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
double v = std::stod(std::string(s), &used);
|
||||
if (used != s.size() || v < 0.0 || v > 1.0) return 0.0;
|
||||
return v;
|
||||
} catch (...) {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
inline std::vector<MediaRange> parse_accept(std::string_view header) {
|
||||
std::vector<MediaRange> out;
|
||||
if (trim_ws(header).empty()) {
|
||||
out.push_back(MediaRange{"*", "*", 1.0, {}, 0});
|
||||
return out;
|
||||
}
|
||||
std::size_t i = 0;
|
||||
std::size_t order = 0;
|
||||
while (i <= header.size()) {
|
||||
std::size_t comma = header.find(',', i);
|
||||
if (comma == std::string_view::npos) comma = header.size();
|
||||
std::string_view entry = header.substr(i, comma - i);
|
||||
std::size_t semi = entry.find(';');
|
||||
std::string_view full = (semi == std::string_view::npos) ? entry : entry.substr(0, semi);
|
||||
std::size_t slash = full.find('/');
|
||||
if (slash != std::string_view::npos) {
|
||||
MediaRange range;
|
||||
range.type = trim_ws(full.substr(0, slash));
|
||||
range.subtype = trim_ws(full.substr(slash + 1));
|
||||
range.order = order++;
|
||||
if (!range.type.empty() && !range.subtype.empty()) {
|
||||
if (semi != std::string_view::npos) {
|
||||
std::string_view rest = entry.substr(semi + 1);
|
||||
std::size_t j = 0;
|
||||
while (j <= rest.size()) {
|
||||
std::size_t s2 = rest.find(';', j);
|
||||
if (s2 == std::string_view::npos) s2 = rest.size();
|
||||
std::string_view kv = rest.substr(j, s2 - j);
|
||||
std::size_t eq = kv.find('=');
|
||||
if (eq != std::string_view::npos) {
|
||||
std::string k = trim_ws(kv.substr(0, eq));
|
||||
std::string v = trim_ws(kv.substr(eq + 1));
|
||||
if (k == "q") {
|
||||
range.q = parse_q(v);
|
||||
} else {
|
||||
range.params.emplace_back(k, v);
|
||||
}
|
||||
}
|
||||
if (s2 == rest.size()) break;
|
||||
j = s2 + 1;
|
||||
}
|
||||
}
|
||||
out.push_back(std::move(range));
|
||||
}
|
||||
}
|
||||
if (comma == header.size()) break;
|
||||
i = comma + 1;
|
||||
}
|
||||
if (out.empty()) out.push_back(MediaRange{"*", "*", 1.0, {}, 0});
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::negotiate
|
||||
@@ -0,0 +1,137 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::negotiate::Negotiator (plan 05, R6, E6). Server-driven
|
||||
// content negotiation: sorts Accept ranges by q desc, then specificity
|
||||
// (exact beats type star beats star star), then Accept order; matches
|
||||
// against handler-declared produces in declaration order. Explicit ?format=
|
||||
// or suffix override applies only when the route sets allow_format_override
|
||||
// (Q2 answer: off by default). No match throws NotAcceptable carrying the
|
||||
// available list. Consumes check throws UnsupportedMediaType (415).
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/html.h"
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/value.h"
|
||||
#include "accept.h"
|
||||
|
||||
namespace molo::app::negotiate {
|
||||
|
||||
inline int range_specificity(const MediaRange& r) {
|
||||
if (r.type == "*" && r.subtype == "*") return 0;
|
||||
if (r.subtype == "*") return 1;
|
||||
return 2;
|
||||
}
|
||||
|
||||
inline bool range_matches(const MediaRange& r, std::string_view candidate) {
|
||||
std::size_t slash = candidate.find('/');
|
||||
if (slash == std::string_view::npos) return false;
|
||||
std::string_view ct = candidate.substr(0, slash);
|
||||
std::string_view cs = candidate.substr(slash + 1);
|
||||
if (r.type != "*" && r.type != ct) return false;
|
||||
if (r.subtype != "*" && r.subtype != cs) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline std::string format_name_to_media(std::string_view name) {
|
||||
std::string low(name);
|
||||
for (char& c : low) c = (char)std::tolower((unsigned char)c);
|
||||
if (low == "json") return "application/json";
|
||||
if (low == "html") return "text/html";
|
||||
if (low == "xml") return "application/xml";
|
||||
if (low == "text" || low == "txt") return "text/plain";
|
||||
return "";
|
||||
}
|
||||
|
||||
class Negotiator {
|
||||
public:
|
||||
static std::string select(std::string_view accept_header,
|
||||
const std::vector<std::string>& produces,
|
||||
bool allow_format_override = false,
|
||||
std::string_view format_param = "") {
|
||||
if (produces.empty()) return "";
|
||||
if (allow_format_override && !format_param.empty()) {
|
||||
std::string mapped = format_name_to_media(format_param);
|
||||
for (const auto& p : produces) {
|
||||
if (p == mapped) return p;
|
||||
}
|
||||
throw errors::NotAcceptable(produces);
|
||||
}
|
||||
std::vector<MediaRange> ranges = parse_accept(accept_header);
|
||||
std::sort(ranges.begin(), ranges.end(), [](const MediaRange& a, const MediaRange& b) {
|
||||
if (a.q != b.q) return a.q > b.q;
|
||||
int sa = range_specificity(a);
|
||||
int sb = range_specificity(b);
|
||||
if (sa != sb) return sa > sb;
|
||||
return a.order < b.order;
|
||||
});
|
||||
for (const MediaRange& r : ranges) {
|
||||
if (r.q <= 0.0) continue;
|
||||
for (const auto& p : produces) {
|
||||
if (range_matches(r, p)) return p;
|
||||
}
|
||||
}
|
||||
throw errors::NotAcceptable(produces);
|
||||
}
|
||||
|
||||
static void check_consumes(std::string_view content_type,
|
||||
const std::vector<std::string>& consumes) {
|
||||
if (consumes.empty()) return;
|
||||
for (const auto& c : consumes) {
|
||||
if (c == content_type) return;
|
||||
}
|
||||
throw errors::UnsupportedMediaType("content type not consumed by this route");
|
||||
}
|
||||
};
|
||||
|
||||
// Render one data value into a concrete (body, content type) pair for the
|
||||
// negotiated media type. Used by NegotiationMiddleware for VariantResponse.
|
||||
inline std::pair<std::string, std::string> render_variant(const validate::Value& data,
|
||||
std::string_view media) {
|
||||
if (media == "application/json") {
|
||||
return {validate::to_json(data), "application/json"};
|
||||
}
|
||||
if (media == "application/xml") {
|
||||
std::string body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><value>";
|
||||
if (const auto* o = std::get_if<validate::Object>(&data.storage())) {
|
||||
for (const auto& kv : *o) {
|
||||
body += "<" + kv.first + ">" + http_msg::escape_xml(validate::to_json(kv.second)) +
|
||||
"</" + kv.first + ">";
|
||||
}
|
||||
} else {
|
||||
body += http_msg::escape_xml(validate::to_json(data));
|
||||
}
|
||||
body += "</value>";
|
||||
return {body, "application/xml; charset=utf-8"};
|
||||
}
|
||||
if (media == "text/html") {
|
||||
std::string rows;
|
||||
if (const auto* o = std::get_if<validate::Object>(&data.storage())) {
|
||||
for (const auto& kv : *o) {
|
||||
rows += "<tr><th>" + http_msg::escape_html(kv.first) + "</th><td>" +
|
||||
http_msg::escape_html(validate::to_json(kv.second)) + "</td></tr>";
|
||||
}
|
||||
} else {
|
||||
rows = "<tr><td>" + http_msg::escape_html(validate::to_json(data)) + "</td></tr>";
|
||||
}
|
||||
std::string body =
|
||||
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
||||
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
||||
"<title>response</title><style>"
|
||||
"body{font-family:system-ui,sans-serif;margin:1rem}"
|
||||
"table{border-collapse:collapse;max-width:100%}"
|
||||
"th,td{border:1px solid #ccc;padding:.4rem .6rem;text-align:left}"
|
||||
"@media (max-width:40rem){table{width:100%}}</style>"
|
||||
"</head><body><table>" +
|
||||
rows + "</table></body></html>";
|
||||
return {body, "text/html; charset=utf-8"};
|
||||
}
|
||||
std::string text = data.is_string() ? data.as_text() : validate::to_json(data);
|
||||
return {text, "text/plain; charset=utf-8"};
|
||||
}
|
||||
|
||||
} // namespace molo::app::negotiate
|
||||
@@ -0,0 +1,227 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::routing path compiler (plan 05, section 6 Route matching).
|
||||
// Path syntax: /users/{id:int} with converters int, float, str (single
|
||||
// segment), path (remainder, must be last). Unknown converter is a startup
|
||||
// error naming the route. Trailing slash is strict.
|
||||
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "../errors/http_error.h"
|
||||
#include "../validate/errors.h"
|
||||
|
||||
namespace molo::app::routing {
|
||||
|
||||
class PathCompileError : public std::runtime_error {
|
||||
public:
|
||||
explicit PathCompileError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
enum class Converter { Int, Float, Str, Path };
|
||||
|
||||
struct Segment {
|
||||
bool is_param = false;
|
||||
std::string literal;
|
||||
std::string name;
|
||||
Converter converter = Converter::Str;
|
||||
};
|
||||
|
||||
struct CompiledPath {
|
||||
std::vector<Segment> segments;
|
||||
bool has_catchall = false;
|
||||
std::size_t static_count = 0;
|
||||
};
|
||||
|
||||
inline std::vector<std::string> split_path(std::string_view path) {
|
||||
std::vector<std::string> out;
|
||||
std::size_t i = 0;
|
||||
if (!path.empty() && path[0] == '/') i = 1;
|
||||
while (true) {
|
||||
std::size_t slash = path.find('/', i);
|
||||
if (slash == std::string_view::npos) {
|
||||
out.emplace_back(path.substr(i));
|
||||
break;
|
||||
}
|
||||
out.emplace_back(path.substr(i, slash - i));
|
||||
i = slash + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline CompiledPath compile_path(std::string_view pattern, std::string_view route_label) {
|
||||
if (pattern.empty() || pattern[0] != '/') {
|
||||
throw PathCompileError("route '" + std::string(route_label) + "': pattern must start with /");
|
||||
}
|
||||
CompiledPath out;
|
||||
std::vector<std::string> parts = split_path(pattern);
|
||||
std::size_t param_count = 0;
|
||||
for (std::size_t idx = 0; idx < parts.size(); ++idx) {
|
||||
const std::string& part = parts[idx];
|
||||
if (part.size() >= 2 && part.front() == '{' && part.back() == '}') {
|
||||
std::string inner = part.substr(1, part.size() - 2);
|
||||
std::string name = inner;
|
||||
std::string conv = "str";
|
||||
std::size_t colon = inner.find(':');
|
||||
if (colon != std::string::npos) {
|
||||
name = inner.substr(0, colon);
|
||||
conv = inner.substr(colon + 1);
|
||||
}
|
||||
if (name.empty()) {
|
||||
throw PathCompileError("route '" + std::string(route_label) + "': empty param name");
|
||||
}
|
||||
Segment seg;
|
||||
seg.is_param = true;
|
||||
seg.name = name;
|
||||
if (conv == "int") {
|
||||
seg.converter = Converter::Int;
|
||||
} else if (conv == "float") {
|
||||
seg.converter = Converter::Float;
|
||||
} else if (conv == "str") {
|
||||
seg.converter = Converter::Str;
|
||||
} else if (conv == "path") {
|
||||
seg.converter = Converter::Path;
|
||||
if (idx != parts.size() - 1) {
|
||||
throw PathCompileError("route '" + std::string(route_label) +
|
||||
"': path converter must be last");
|
||||
}
|
||||
out.has_catchall = true;
|
||||
} else {
|
||||
throw PathCompileError("route '" + std::string(route_label) + "': unknown converter '" +
|
||||
conv + "'");
|
||||
}
|
||||
++param_count;
|
||||
if (param_count > caps::kMaxPathParamsPerRoute) {
|
||||
throw PathCompileError("route '" + std::string(route_label) + "': too many path params");
|
||||
}
|
||||
out.segments.push_back(std::move(seg));
|
||||
} else {
|
||||
Segment seg;
|
||||
seg.literal = part;
|
||||
out.segments.push_back(std::move(seg));
|
||||
++out.static_count;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline bool strict_int(std::string_view s) {
|
||||
if (s.empty()) return false;
|
||||
std::size_t i = 0;
|
||||
if (s[0] == '+' || s[0] == '-') i = 1;
|
||||
if (i == s.size()) return false;
|
||||
for (std::size_t j = i; j < s.size(); ++j) {
|
||||
if (!std::isdigit((unsigned char)s[j])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool strict_float(std::string_view s) {
|
||||
if (s.empty()) return false;
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
std::stod(std::string(s), &used);
|
||||
return used == s.size();
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
struct PathMatch {
|
||||
bool full = false;
|
||||
bool skeleton = false;
|
||||
std::map<std::string, std::string> params;
|
||||
std::vector<validate::FieldFailure> errors;
|
||||
};
|
||||
|
||||
inline PathMatch match_compiled(const CompiledPath& cp, std::string_view path) {
|
||||
PathMatch m;
|
||||
if (path.empty() || path[0] != '/') return m;
|
||||
std::vector<std::string> parts = split_path(path);
|
||||
std::size_t need = cp.segments.size();
|
||||
bool count_ok = cp.has_catchall ? (parts.size() >= need - 1) : (parts.size() == need);
|
||||
// Skeleton pass: converters match any single segment, catch-all the rest.
|
||||
bool skeleton = count_ok;
|
||||
if (skeleton) {
|
||||
for (std::size_t i = 0; i < cp.segments.size() && skeleton; ++i) {
|
||||
const Segment& seg = cp.segments[i];
|
||||
if (seg.is_param) {
|
||||
if (seg.converter == Converter::Path) break;
|
||||
continue;
|
||||
}
|
||||
if (i >= parts.size() || parts[i] != seg.literal) skeleton = false;
|
||||
}
|
||||
}
|
||||
m.skeleton = skeleton;
|
||||
if (!skeleton) return m;
|
||||
// Full pass with converter checks.
|
||||
for (std::size_t i = 0; i < cp.segments.size(); ++i) {
|
||||
const Segment& seg = cp.segments[i];
|
||||
if (!seg.is_param) continue;
|
||||
if (seg.converter == Converter::Path) {
|
||||
std::string rest;
|
||||
for (std::size_t j = i; j < parts.size(); ++j) {
|
||||
if (j > i) rest += '/';
|
||||
rest += parts[j];
|
||||
}
|
||||
m.params[seg.name] = rest;
|
||||
break;
|
||||
}
|
||||
const std::string& raw = parts[i];
|
||||
if (seg.converter == Converter::Str) {
|
||||
if (raw.empty()) {
|
||||
m.errors.push_back({{"path", seg.name}, "empty path segment", "string_type"});
|
||||
return m;
|
||||
}
|
||||
m.params[seg.name] = raw;
|
||||
} else if (seg.converter == Converter::Int) {
|
||||
if (!strict_int(raw)) {
|
||||
m.errors.push_back({{"path", seg.name}, "invalid integer", "int_parsing"});
|
||||
return m;
|
||||
}
|
||||
m.params[seg.name] = raw;
|
||||
} else if (seg.converter == Converter::Float) {
|
||||
if (!strict_float(raw)) {
|
||||
m.errors.push_back({{"path", seg.name}, "invalid number", "float_parsing"});
|
||||
return m;
|
||||
}
|
||||
m.params[seg.name] = raw;
|
||||
}
|
||||
}
|
||||
m.full = true;
|
||||
return m;
|
||||
}
|
||||
|
||||
inline std::string render_compiled(const CompiledPath& cp,
|
||||
const std::map<std::string, std::string>& params,
|
||||
std::string_view route_name) {
|
||||
std::string out;
|
||||
for (const Segment& seg : cp.segments) {
|
||||
out += '/';
|
||||
if (!seg.is_param) {
|
||||
out += seg.literal;
|
||||
} else {
|
||||
auto it = params.find(seg.name);
|
||||
if (it == params.end()) {
|
||||
throw errors::NotFound("url_for: route '" + std::string(route_name) +
|
||||
"' missing param '" + seg.name + "'");
|
||||
}
|
||||
out += it->second;
|
||||
}
|
||||
}
|
||||
if (out.empty()) out = "/";
|
||||
// Collapse the "/"+"" root case back to "/".
|
||||
if (out.size() > 1 && out.back() == '/' && cp.segments.size() == 1 &&
|
||||
!cp.segments[0].is_param && cp.segments[0].literal.empty()) {
|
||||
out = "/";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::routing
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::routing::Route. One route record: methods, compiled path,
|
||||
// handler, name, tags, validation models, negotiation declarations,
|
||||
// slash policy (plan 05, section 3). Handler takes Request and returns
|
||||
// Task<Response> (R1). slash_insensitive registers the declared route plus a
|
||||
// companion 308 redirect route for the alternate trailing-slash form.
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../caps.h"
|
||||
#include "../http_msg/method.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../validate/model.h"
|
||||
#include "path_compiler.h"
|
||||
|
||||
namespace molo::app::routing {
|
||||
|
||||
using Handler = std::function<async::Task<http_msg::Response>(http_msg::Request&)>;
|
||||
|
||||
struct RouteOptions {
|
||||
std::string name;
|
||||
std::vector<std::string> tags;
|
||||
std::vector<std::string> produces;
|
||||
std::vector<std::string> consumes;
|
||||
bool allow_format_override = false;
|
||||
bool slash_insensitive = false;
|
||||
std::size_t max_body = caps::kMaxJsonDocument;
|
||||
// Governance (molo::govern): auth and lifecycle for this route.
|
||||
enum class GovAuth { kNone, kKey, kKeyScopes, kSession };
|
||||
GovAuth gov_auth = GovAuth::kNone;
|
||||
std::vector<std::string> gov_required_scopes;
|
||||
int gov_api_version = 0; // 0 = derived from the /v{n} prefix
|
||||
long gov_deprecation_unix = 0;
|
||||
std::string gov_sunset_httpdate;
|
||||
std::string gov_tier_override; // "", "free", "pro", "enterprise"
|
||||
bool gov_has_summary = false;
|
||||
bool gov_has_example = false;
|
||||
std::shared_ptr<validate::Model> query_model;
|
||||
std::shared_ptr<validate::Model> body_model;
|
||||
std::shared_ptr<validate::Model> header_model;
|
||||
std::shared_ptr<validate::Model> cookie_model;
|
||||
// Internal: non-empty on slash-redirect companions (target declared path).
|
||||
std::string redirect_target;
|
||||
};
|
||||
|
||||
class Route {
|
||||
public:
|
||||
Route(std::set<http_msg::Method> methods, std::string pattern, Handler handler,
|
||||
RouteOptions options = {}, std::size_t index = 0)
|
||||
: methods_(std::move(methods)),
|
||||
pattern_(std::move(pattern)),
|
||||
handler_(std::move(handler)),
|
||||
options_(std::move(options)),
|
||||
index_(index) {
|
||||
if (options_.name.size() > caps::kMaxRouteName) {
|
||||
throw PathCompileError("route name too long: " + options_.name);
|
||||
}
|
||||
compiled_ = compile_path(pattern_, options_.name.empty() ? pattern_ : options_.name);
|
||||
}
|
||||
|
||||
const std::set<http_msg::Method>& methods() const { return methods_; }
|
||||
const std::string& pattern() const { return pattern_; }
|
||||
const CompiledPath& compiled() const { return compiled_; }
|
||||
const Handler& handler() const { return handler_; }
|
||||
const RouteOptions& options() const { return options_; }
|
||||
std::size_t index() const { return index_; }
|
||||
bool is_slash_redirect() const { return !options_.redirect_target.empty(); }
|
||||
|
||||
bool allows(http_msg::Method m) const { return methods_.count(m) > 0; }
|
||||
|
||||
std::vector<std::string> allow_list() const {
|
||||
std::vector<std::string> out;
|
||||
for (auto m : methods_) out.push_back(http_msg::to_string(m));
|
||||
return out;
|
||||
}
|
||||
|
||||
Route with_prefix(const std::string& prefix,
|
||||
const std::vector<std::string>& extra_tags) const {
|
||||
std::string clean = prefix;
|
||||
if (clean == "/") clean = "";
|
||||
RouteOptions opts = options_;
|
||||
for (const auto& t : extra_tags) opts.tags.push_back(t);
|
||||
std::string new_pattern = clean + pattern_;
|
||||
Handler h = handler_;
|
||||
if (!opts.redirect_target.empty()) {
|
||||
opts.redirect_target = clean + opts.redirect_target;
|
||||
std::string target = opts.redirect_target;
|
||||
h = [target](http_msg::Request& req) -> async::Task<http_msg::Response> {
|
||||
std::string url = target;
|
||||
if (!req.query_raw().empty()) url += "?" + req.query_raw();
|
||||
co_return http_msg::RedirectResponse::permanent(url);
|
||||
};
|
||||
}
|
||||
return Route(methods_, new_pattern, h, opts, index_);
|
||||
}
|
||||
|
||||
private:
|
||||
std::set<http_msg::Method> methods_;
|
||||
std::string pattern_;
|
||||
Handler handler_;
|
||||
RouteOptions options_;
|
||||
CompiledPath compiled_;
|
||||
std::size_t index_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::app::routing
|
||||
@@ -0,0 +1,319 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::routing::Router (plan 05, E2). FastAPI-style router:
|
||||
// get/post/put/patch/delete/head/options, nested include_router with prefix
|
||||
// and tags, match with 404/405/422 precedence, url_for reversal.
|
||||
// Match order: static segments first (more static wins), then converters in
|
||||
// registration order, then path catch-alls. Precedence: full match, then
|
||||
// 405 (skeleton path exists, method missing), then 422 (path converter
|
||||
// failure), then 404. Method mismatch sets the Allow header.
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../../governance/caps.h"
|
||||
#include "../../governance/versions/ApiVersion.h"
|
||||
#include "../../tenancy/resolver.h"
|
||||
#include "../caps.h"
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/method.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../validate/errors.h"
|
||||
#include "path_compiler.h"
|
||||
#include "route.h"
|
||||
|
||||
namespace molo::app::routing {
|
||||
|
||||
namespace detail {
|
||||
|
||||
// Strict IMF-fixdate ("Wed, 21 Oct 2015 07:28:00 GMT") to unix seconds.
|
||||
// Returns -1 when unparseable. Self-contained so router.h gains no deps.
|
||||
inline long ParseImfFixdate(const std::string& text) {
|
||||
if (text.size() != 29) return -1;
|
||||
if (text[3] != ',' || text[4] != ' ' || text[7] != ' ' || text[11] != ' ' ||
|
||||
text[16] != ' ' || text[19] != ':' || text[22] != ':' || text[25] != ' ') {
|
||||
return -1;
|
||||
}
|
||||
if (text.compare(26, 3, "GMT") != 0) return -1;
|
||||
auto digits = [&](std::size_t pos, std::size_t len, int& out) {
|
||||
int v = 0;
|
||||
for (std::size_t i = 0; i < len; ++i) {
|
||||
char c = text[pos + i];
|
||||
if (c < '0' || c > '9') return false;
|
||||
v = v * 10 + (c - '0');
|
||||
}
|
||||
out = v;
|
||||
return true;
|
||||
};
|
||||
int day, year, hh, mm, ss;
|
||||
if (!digits(5, 2, day) || !digits(12, 4, year) || !digits(17, 2, hh) ||
|
||||
!digits(20, 2, mm) || !digits(23, 2, ss)) {
|
||||
return -1;
|
||||
}
|
||||
static const char* kMonths[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
||||
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
|
||||
int mon = 0;
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
if (text.compare(8, 3, kMonths[i]) == 0) {
|
||||
mon = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mon == 0 || day < 1 || day > 31 || hh > 23 || mm > 59 || ss > 60) return -1;
|
||||
// Days from civil (Howard Hinnant), 1970-01-01 based.
|
||||
int y = year;
|
||||
unsigned m = static_cast<unsigned>(mon);
|
||||
unsigned d = static_cast<unsigned>(day);
|
||||
y -= (m <= 2);
|
||||
const int era = (y >= 0 ? y : y - 399) / 400;
|
||||
const unsigned yoe = static_cast<unsigned>(y - era * 400);
|
||||
const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
|
||||
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
const long days = static_cast<long>(era) * 146097 + static_cast<long>(doe) - 719468;
|
||||
return days * 86400L + hh * 3600L + mm * 60L + ss;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
struct MatchResult {
|
||||
const Route* route = nullptr;
|
||||
std::map<std::string, std::string> params;
|
||||
std::vector<std::string> allow;
|
||||
std::vector<validate::FieldFailure> path_errors;
|
||||
bool skeleton_matched = false;
|
||||
};
|
||||
|
||||
class Router {
|
||||
public:
|
||||
const Route& add(std::set<http_msg::Method> methods, std::string pattern, Handler handler,
|
||||
RouteOptions options = {}) {
|
||||
if (frozen_) throw PathCompileError("router frozen: cannot add routes after startup");
|
||||
if (routes_.size() + 1 > caps::kMaxRoutesPerApp) {
|
||||
throw PathCompileError("too many routes in router");
|
||||
}
|
||||
std::size_t index = next_index_++;
|
||||
std::size_t at = routes_.size();
|
||||
routes_.emplace_back(std::move(methods), pattern, std::move(handler), options, index);
|
||||
const Route& added = routes_.at(at);
|
||||
if (options.slash_insensitive) {
|
||||
std::string alt;
|
||||
if (pattern.size() > 1 && pattern.back() == '/') {
|
||||
alt = pattern.substr(0, pattern.size() - 1);
|
||||
} else if (pattern == "/") {
|
||||
alt = "";
|
||||
} else {
|
||||
alt = pattern + "/";
|
||||
}
|
||||
if (!alt.empty()) {
|
||||
if (routes_.size() + 1 > caps::kMaxRoutesPerApp) {
|
||||
throw PathCompileError("too many routes in router");
|
||||
}
|
||||
RouteOptions redirect_opts;
|
||||
redirect_opts.redirect_target = pattern;
|
||||
std::string target = pattern;
|
||||
Handler redirect = [target](http_msg::Request& req)
|
||||
-> async::Task<http_msg::Response> {
|
||||
std::string url = target;
|
||||
if (!req.query_raw().empty()) url += "?" + req.query_raw();
|
||||
co_return http_msg::RedirectResponse::permanent(url);
|
||||
};
|
||||
routes_.emplace_back(added.methods(), alt, std::move(redirect), redirect_opts,
|
||||
next_index_++);
|
||||
}
|
||||
}
|
||||
rebuild_order();
|
||||
return routes_.at(at);
|
||||
}
|
||||
|
||||
const Route& get(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::GET}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& post(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::POST}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& put(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::PUT}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& patch(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::PATCH}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& del(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::DELETE}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& head(std::string pattern, Handler handler, RouteOptions options = {}) {
|
||||
return add({http_msg::Method::HEAD}, std::move(pattern), std::move(handler),
|
||||
std::move(options));
|
||||
}
|
||||
const Route& options(std::string pattern, Handler handler, RouteOptions opts = {}) {
|
||||
return add({http_msg::Method::OPTIONS}, std::move(pattern), std::move(handler),
|
||||
std::move(opts));
|
||||
}
|
||||
|
||||
void include_router(std::string prefix, const Router& other,
|
||||
std::vector<std::string> extra_tags = {}) {
|
||||
if (frozen_) throw PathCompileError("router frozen: cannot include after startup");
|
||||
if (prefix.empty() || prefix[0] != '/') {
|
||||
throw PathCompileError("include_router prefix must start with /");
|
||||
}
|
||||
for (const Route& r : other.routes_) {
|
||||
if (routes_.size() + 1 > caps::kMaxRoutesPerApp) {
|
||||
throw PathCompileError("too many routes in router");
|
||||
}
|
||||
Route merged = r.with_prefix(prefix, extra_tags);
|
||||
routes_.emplace_back(merged.methods(), merged.pattern(), merged.handler(),
|
||||
merged.options(), next_index_++);
|
||||
}
|
||||
rebuild_order();
|
||||
}
|
||||
|
||||
MatchResult match(http_msg::Method method, std::string_view path) const {
|
||||
if (path.size() > caps::kMaxPathLength) {
|
||||
throw errors::UriTooLong("path exceeds length cap");
|
||||
}
|
||||
MatchResult out;
|
||||
std::set<std::string> allow_set;
|
||||
for (const Route* route : order_) {
|
||||
PathMatch pm = match_compiled(route->compiled(), path);
|
||||
if (pm.full) {
|
||||
if (route->allows(method)) {
|
||||
out.route = route;
|
||||
out.params = std::move(pm.params);
|
||||
return out;
|
||||
}
|
||||
out.skeleton_matched = true;
|
||||
for (const auto& a : route->allow_list()) allow_set.insert(a);
|
||||
continue;
|
||||
}
|
||||
if (pm.skeleton) {
|
||||
out.skeleton_matched = true;
|
||||
if (!route->allows(method)) {
|
||||
for (const auto& a : route->allow_list()) allow_set.insert(a);
|
||||
} else if (out.path_errors.empty() && !pm.errors.empty()) {
|
||||
out.path_errors = std::move(pm.errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.allow.assign(allow_set.begin(), allow_set.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string url_for(std::string_view name,
|
||||
const std::map<std::string, std::string>& params = {},
|
||||
std::string_view query = "") const {
|
||||
for (const Route& r : routes_) {
|
||||
if (r.options().name == name && !r.is_slash_redirect()) {
|
||||
std::string url = render_compiled(r.compiled(), params, name);
|
||||
if (!query.empty()) {
|
||||
url += '?';
|
||||
url += query;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
}
|
||||
throw errors::NotFound("url_for: unknown route '" + std::string(name) + "'");
|
||||
}
|
||||
|
||||
bool has_route_name(std::string_view name) const {
|
||||
for (const Route& r : routes_) {
|
||||
if (!r.is_slash_redirect() && r.options().name == name) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tenant-aware helpers (PATCHES 11.14): strip the /t/<slug> prefix and
|
||||
// build URLs that carry the tenant.
|
||||
static std::pair<std::string, std::string> strip_tenant_prefix(
|
||||
const std::string& path) {
|
||||
return ::molo::tenancy::Resolver::StripTenantPrefix(path);
|
||||
}
|
||||
|
||||
std::string url_for_tenant(const std::string& tenant, std::string_view name,
|
||||
const std::map<std::string, std::string>& params = {},
|
||||
std::string_view query = "") const {
|
||||
return "/t/" + tenant + url_for(name, params, query);
|
||||
}
|
||||
|
||||
const std::vector<Route>& routes() const { return routes_; }
|
||||
std::size_t size() const { return routes_.size(); }
|
||||
|
||||
// Application::startup freezes the router so match pointers stay stable.
|
||||
void freeze() { frozen_ = true; }
|
||||
bool frozen() const { return frozen_; }
|
||||
|
||||
// Governance hook: validates /v{n} prefixes, at most 3 live majors,
|
||||
// Sunset >= Deprecation, and declared scopes on scoped routes. Routes
|
||||
// without governance fields set are skipped. Throws std::runtime_error
|
||||
// (Application::startup rethrows as StartupError).
|
||||
void validate_governance() const {
|
||||
std::set<int> live_majors;
|
||||
for (const Route& r : routes_) {
|
||||
if (r.is_slash_redirect()) continue;
|
||||
const RouteOptions& o = r.options();
|
||||
const bool managed = o.gov_auth != RouteOptions::GovAuth::kNone ||
|
||||
o.gov_api_version != 0 || o.gov_deprecation_unix != 0 ||
|
||||
!o.gov_sunset_httpdate.empty() || !o.gov_tier_override.empty();
|
||||
if (!managed) continue;
|
||||
const int major =
|
||||
::molo::govern::versions::ApiVersion::ParseMajor(r.pattern());
|
||||
if (major == 0) {
|
||||
throw std::runtime_error("governance: route '" + r.pattern() +
|
||||
"' is gov-managed but has no /v{n} prefix");
|
||||
}
|
||||
if (o.gov_api_version != 0 && o.gov_api_version != major) {
|
||||
throw std::runtime_error("governance: route '" + r.pattern() +
|
||||
"' gov_api_version does not match its /v{n} prefix");
|
||||
}
|
||||
live_majors.insert(major);
|
||||
if (o.gov_auth == RouteOptions::GovAuth::kKeyScopes &&
|
||||
o.gov_required_scopes.empty()) {
|
||||
throw std::runtime_error("governance: route '" + r.pattern() +
|
||||
"' requires scopes but declares none");
|
||||
}
|
||||
if (!o.gov_sunset_httpdate.empty()) {
|
||||
const long sunset = detail::ParseImfFixdate(o.gov_sunset_httpdate);
|
||||
if (sunset < 0) {
|
||||
throw std::runtime_error("governance: route '" + r.pattern() +
|
||||
"' has an unparseable gov_sunset_httpdate");
|
||||
}
|
||||
if (o.gov_deprecation_unix != 0 && sunset < o.gov_deprecation_unix) {
|
||||
throw std::runtime_error("governance: route '" + r.pattern() +
|
||||
"' sunset predates deprecation");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (static_cast<int>(live_majors.size()) >
|
||||
::molo::govern::Caps::kMaxLiveMajors) {
|
||||
throw std::runtime_error("governance: more than 3 live API majors");
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void rebuild_order() {
|
||||
order_.clear();
|
||||
for (const Route& r : routes_) order_.push_back(&r);
|
||||
std::stable_sort(order_.begin(), order_.end(), [](const Route* a, const Route* b) {
|
||||
int ca = a->compiled().has_catchall ? 1 : 0;
|
||||
int cb = b->compiled().has_catchall ? 1 : 0;
|
||||
if (ca != cb) return ca < cb;
|
||||
if (a->compiled().static_count != b->compiled().static_count) {
|
||||
return a->compiled().static_count > b->compiled().static_count;
|
||||
}
|
||||
return a->index() < b->index();
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<Route> routes_;
|
||||
std::vector<const Route*> order_;
|
||||
std::size_t next_index_ = 0;
|
||||
bool frozen_ = false;
|
||||
};
|
||||
|
||||
} // namespace molo::app::routing
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::seams::request_id. Correlation ID seam owned by
|
||||
// 02-observability. Request ID is read from X-Request-ID when present, else
|
||||
// generated. Middleware must preserve it (plan 05, section 6 Middleware).
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace molo::app::seams {
|
||||
|
||||
inline std::string generate_request_id() {
|
||||
static std::atomic<std::uint64_t> counter{1};
|
||||
std::uint64_t n = counter.fetch_add(1, std::memory_order_relaxed);
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "req-%016llx", (unsigned long long)n);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
inline constexpr const char* kRequestIdHeader = "X-Request-ID";
|
||||
|
||||
} // namespace molo::app::seams
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::seams::session. Session storage seam owned by
|
||||
// 03-security. The app layer (flash messages, views) programs against
|
||||
// SessionStore only. InMemorySessionStore is the standalone default so this
|
||||
// part compiles and tests without siblings; production wires the security
|
||||
// store through Application::set_session_store.
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
|
||||
namespace molo::app::seams {
|
||||
|
||||
struct FlashMessage {
|
||||
std::string level;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
class SessionStore {
|
||||
public:
|
||||
virtual ~SessionStore() = default;
|
||||
virtual void add_flash(const std::string& session_id, FlashMessage msg) = 0;
|
||||
virtual std::vector<FlashMessage> take_flashes(const std::string& session_id) = 0;
|
||||
virtual void clear(const std::string& session_id) = 0;
|
||||
};
|
||||
|
||||
class InMemorySessionStore : public SessionStore {
|
||||
public:
|
||||
void add_flash(const std::string& session_id, FlashMessage msg) override {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto& vec = flashes_[session_id];
|
||||
if (vec.size() < caps::kMaxFlashMessages) vec.push_back(std::move(msg));
|
||||
}
|
||||
|
||||
std::vector<FlashMessage> take_flashes(const std::string& session_id) override {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = flashes_.find(session_id);
|
||||
if (it == flashes_.end()) return {};
|
||||
std::vector<FlashMessage> out = std::move(it->second);
|
||||
flashes_.erase(it);
|
||||
return out;
|
||||
}
|
||||
|
||||
void clear(const std::string& session_id) override {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
flashes_.erase(session_id);
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
std::map<std::string, std::vector<FlashMessage>> flashes_;
|
||||
};
|
||||
|
||||
inline std::shared_ptr<SessionStore> default_session_store() {
|
||||
return std::make_shared<InMemorySessionStore>();
|
||||
}
|
||||
|
||||
} // namespace molo::app::seams
|
||||
@@ -0,0 +1,116 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates AST. Plain data nodes built by the parser,
|
||||
// executed by the renderer. Expressions cover literals, names, attribute
|
||||
// and index access, calls, arithmetic, comparisons, logic, membership,
|
||||
// filters and tests. Gaps vs Jinja (documented): no ternary, no ** power,
|
||||
// no string % formatting, no super(), no block-level set.
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../validate/value.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
struct Expr;
|
||||
using ExprPtr = std::shared_ptr<Expr>;
|
||||
|
||||
struct Expr {
|
||||
enum class Kind {
|
||||
Literal,
|
||||
Name,
|
||||
Attr,
|
||||
Index,
|
||||
Call,
|
||||
Unary,
|
||||
Binary,
|
||||
Compare,
|
||||
BoolOp,
|
||||
Not,
|
||||
In,
|
||||
Filter,
|
||||
Test,
|
||||
List,
|
||||
Dict
|
||||
};
|
||||
Kind kind = Kind::Literal;
|
||||
validate::Value literal;
|
||||
std::string name; // Name, Attr attribute, Call callee, Filter/Test name
|
||||
ExprPtr left;
|
||||
ExprPtr right;
|
||||
ExprPtr operand;
|
||||
ExprPtr seq; // In: left in seq
|
||||
std::string op;
|
||||
bool negated = false; // In (not in), Test (is not)
|
||||
std::vector<ExprPtr> args;
|
||||
std::vector<std::pair<std::string, ExprPtr>> kwargs;
|
||||
std::vector<std::pair<ExprPtr, ExprPtr>> pairs; // Dict
|
||||
};
|
||||
|
||||
struct Node;
|
||||
using NodePtr = std::shared_ptr<Node>;
|
||||
|
||||
struct IfBranch {
|
||||
ExprPtr cond; // null cond means else
|
||||
std::vector<NodePtr> body;
|
||||
};
|
||||
|
||||
struct Node {
|
||||
enum class Kind {
|
||||
Text,
|
||||
Output,
|
||||
If,
|
||||
For,
|
||||
Block,
|
||||
Extends,
|
||||
Include,
|
||||
Set,
|
||||
Macro,
|
||||
Autoescape
|
||||
};
|
||||
Kind kind = Kind::Text;
|
||||
std::string text; // Text content, Block/Macro/Set name
|
||||
ExprPtr expr; // Output, Extends, Include, Set value
|
||||
std::vector<IfBranch> branches; // If
|
||||
std::vector<std::string> targets; // For
|
||||
ExprPtr seq; // For
|
||||
std::vector<NodePtr> body; // For, Block, Macro, Autoescape
|
||||
std::vector<NodePtr> else_body; // For
|
||||
std::vector<std::string> params; // Macro
|
||||
std::vector<std::optional<validate::Value>> defaults; // Macro
|
||||
bool flag = false; // Autoescape enabled
|
||||
};
|
||||
|
||||
struct MacroDef {
|
||||
std::string name;
|
||||
std::vector<std::string> params;
|
||||
std::vector<std::optional<validate::Value>> defaults;
|
||||
std::vector<NodePtr> body;
|
||||
};
|
||||
|
||||
inline ExprPtr lit(validate::Value v) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Literal;
|
||||
e->literal = std::move(v);
|
||||
return e;
|
||||
}
|
||||
|
||||
inline ExprPtr name_expr(std::string n) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Name;
|
||||
e->name = std::move(n);
|
||||
return e;
|
||||
}
|
||||
|
||||
inline NodePtr text_node(std::string t) {
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Text;
|
||||
n->text = std::move(t);
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates compiled-template cache. LRU with max 512
|
||||
// entries (caps.h). Keyed by template name.
|
||||
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "ast.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
struct CompiledTemplate {
|
||||
std::string name;
|
||||
std::vector<NodePtr> nodes;
|
||||
bool autoescape = false;
|
||||
};
|
||||
|
||||
class TemplateCache {
|
||||
public:
|
||||
std::shared_ptr<CompiledTemplate> get(const std::string& name) {
|
||||
auto it = entries_.find(name);
|
||||
if (it == entries_.end()) return nullptr;
|
||||
order_.erase(it->second.second);
|
||||
order_.push_front(name);
|
||||
it->second.second = order_.begin();
|
||||
return it->second.first;
|
||||
}
|
||||
|
||||
void put(std::string name, std::shared_ptr<CompiledTemplate> compiled) {
|
||||
auto it = entries_.find(name);
|
||||
if (it != entries_.end()) {
|
||||
order_.erase(it->second.second);
|
||||
entries_.erase(it);
|
||||
}
|
||||
order_.push_front(name);
|
||||
entries_[name] = {std::move(compiled), order_.begin()};
|
||||
while (entries_.size() > caps::kMaxCompiledTemplates) {
|
||||
entries_.erase(order_.back());
|
||||
order_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
entries_.clear();
|
||||
order_.clear();
|
||||
}
|
||||
|
||||
std::size_t size() const { return entries_.size(); }
|
||||
|
||||
private:
|
||||
std::map<std::string, std::pair<std::shared_ptr<CompiledTemplate>,
|
||||
std::list<std::string>::iterator>>
|
||||
entries_;
|
||||
std::list<std::string> order_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates::Context. Lexical scopes for rendering: a stack
|
||||
// of variable scopes plus macro definitions. set writes the innermost
|
||||
// scope; loops, includes and macro calls push and pop.
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../validate/value.h"
|
||||
#include "ast.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
struct Scope {
|
||||
validate::Object vars;
|
||||
std::map<std::string, std::shared_ptr<MacroDef>> macros;
|
||||
};
|
||||
|
||||
class Context {
|
||||
public:
|
||||
Context() { scopes_.emplace_back(); }
|
||||
|
||||
explicit Context(validate::Object globals) {
|
||||
Scope root;
|
||||
root.vars = std::move(globals);
|
||||
scopes_.push_back(std::move(root));
|
||||
}
|
||||
|
||||
void push() { scopes_.emplace_back(); }
|
||||
void pop() {
|
||||
if (scopes_.size() > 1) scopes_.pop_back();
|
||||
}
|
||||
|
||||
void set(const std::string& name, validate::Value value) {
|
||||
scopes_.back().vars[name] = std::move(value);
|
||||
}
|
||||
|
||||
void define_macro(std::shared_ptr<MacroDef> macro) {
|
||||
scopes_.back().macros[macro->name] = std::move(macro);
|
||||
}
|
||||
|
||||
validate::Value lookup(const std::string& name) const {
|
||||
for (std::size_t i = scopes_.size(); i-- > 0;) {
|
||||
auto it = scopes_[i].vars.find(name);
|
||||
if (it != scopes_[i].vars.end()) return it->second;
|
||||
}
|
||||
return validate::Value::undefined();
|
||||
}
|
||||
|
||||
std::shared_ptr<MacroDef> lookup_macro(const std::string& name) const {
|
||||
for (std::size_t i = scopes_.size(); i-- > 0;) {
|
||||
auto it = scopes_[i].macros.find(name);
|
||||
if (it != scopes_[i].macros.end()) return it->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const std::vector<Scope>& scopes() const { return scopes_; }
|
||||
|
||||
private:
|
||||
std::vector<Scope> scopes_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,129 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates::Environment. Reusable template environment
|
||||
// holding loaders, filters, tests and globals (plan 05, E11). Autoescape is
|
||||
// ON for .html, .htm, .xml; there is deliberately no global disable flag
|
||||
// (R5). Undefined policy defaults to Strict (dev default per spec); Chain
|
||||
// renders empty plus a stats counter. dev_reload bypasses the compiled
|
||||
// cache so disk edits show on the next render.
|
||||
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "../validate/value.h"
|
||||
#include "cache.h"
|
||||
#include "filters.h"
|
||||
#include "lexer.h"
|
||||
#include "loaders.h"
|
||||
#include "parser.h"
|
||||
#include "predicates.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
class Renderer;
|
||||
|
||||
enum class UndefinedPolicy { Chain, Strict };
|
||||
|
||||
struct TemplateStats {
|
||||
std::size_t renders = 0;
|
||||
std::size_t cache_hits = 0;
|
||||
std::size_t undefined_hits = 0;
|
||||
std::size_t errors = 0;
|
||||
};
|
||||
|
||||
class Environment {
|
||||
public:
|
||||
Environment() : filters_(builtin_filters()), tests_(builtin_tests()) {}
|
||||
|
||||
void add_loader(std::shared_ptr<Loader> loader) { loaders_.push_back(std::move(loader)); }
|
||||
|
||||
void set_global(const std::string& name, validate::Value value) {
|
||||
globals_[name] = std::move(value);
|
||||
}
|
||||
void add_filter(const std::string& name, FilterFn fn) { filters_[name] = std::move(fn); }
|
||||
void add_test(const std::string& name, TestFn fn) { tests_[name] = std::move(fn); }
|
||||
|
||||
void set_undefined_policy(UndefinedPolicy p) { undefined_policy_ = p; }
|
||||
UndefinedPolicy undefined_policy() const { return undefined_policy_; }
|
||||
void set_dev_reload(bool on) { dev_reload_ = on; }
|
||||
bool dev_reload() const { return dev_reload_; }
|
||||
|
||||
const validate::Object& globals() const { return globals_; }
|
||||
const std::map<std::string, FilterFn>& filters() const { return filters_; }
|
||||
const std::map<std::string, TestFn>& tests() const { return tests_; }
|
||||
TemplateStats& stats() { return stats_; }
|
||||
const TemplateStats& stats() const { return stats_; }
|
||||
TemplateCache& cache() { return cache_; }
|
||||
|
||||
bool autoescape_for(const std::string& name) const {
|
||||
std::size_t dot = name.rfind('.');
|
||||
if (dot == std::string::npos) return false;
|
||||
std::string ext = name.substr(dot + 1);
|
||||
for (char& c : ext) c = (char)std::tolower((unsigned char)c);
|
||||
return ext == "html" || ext == "htm" || ext == "xml";
|
||||
}
|
||||
|
||||
std::string load_source(const std::string& name) const {
|
||||
for (const auto& loader : loaders_) {
|
||||
std::optional<std::string> hit = loader->load(name);
|
||||
if (hit.has_value()) {
|
||||
if (hit->size() > caps::kMaxTemplateSize) {
|
||||
throw TemplateError("template too large: " + name);
|
||||
}
|
||||
return *hit;
|
||||
}
|
||||
}
|
||||
throw TemplateError("template not found: " + name);
|
||||
}
|
||||
|
||||
std::shared_ptr<CompiledTemplate> compile_source(const std::string& source,
|
||||
const std::string& name) const {
|
||||
if (source.size() > caps::kMaxTemplateSize) {
|
||||
throw TemplateError("template too large: " + name);
|
||||
}
|
||||
std::vector<Token> toks = lex_template(source, name);
|
||||
std::vector<NodePtr> nodes = parse_template(toks, name);
|
||||
auto compiled = std::make_shared<CompiledTemplate>();
|
||||
compiled->name = name;
|
||||
compiled->nodes = std::move(nodes);
|
||||
compiled->autoescape = autoescape_for(name);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
std::shared_ptr<CompiledTemplate> get_compiled(const std::string& name) {
|
||||
if (!dev_reload_) {
|
||||
std::shared_ptr<CompiledTemplate> hit = cache_.get(name);
|
||||
if (hit) {
|
||||
++stats_.cache_hits;
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
std::string source = load_source(name);
|
||||
std::shared_ptr<CompiledTemplate> compiled = compile_source(source, name);
|
||||
if (!dev_reload_) cache_.put(name, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
// Defined in renderer.h (needs the full Renderer).
|
||||
std::string render(const std::string& name, validate::Object context = {});
|
||||
std::string render_source(const std::string& source, const std::string& name,
|
||||
validate::Object context = {});
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<Loader>> loaders_;
|
||||
validate::Object globals_;
|
||||
std::map<std::string, FilterFn> filters_;
|
||||
std::map<std::string, TestFn> tests_;
|
||||
TemplateCache cache_;
|
||||
UndefinedPolicy undefined_policy_ = UndefinedPolicy::Strict;
|
||||
bool dev_reload_ = false;
|
||||
TemplateStats stats_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::templates
|
||||
|
||||
#include "renderer.h"
|
||||
@@ -0,0 +1,163 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates shipped filters (plan 05, section 6 Templates):
|
||||
// escape, safe, upper, lower, trim, striptags, urlencode, length, default,
|
||||
// join, date, tojson. Case conversion is ASCII-only (documented gap).
|
||||
|
||||
#include <cctype>
|
||||
#include <ctime>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../http_msg/html.h"
|
||||
#include "../http_msg/query.h"
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/value.h"
|
||||
#include "lexer.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
using FilterFn =
|
||||
std::function<validate::Value(const validate::Value&, const std::vector<validate::Value>&)>;
|
||||
|
||||
inline std::string value_to_text(const validate::Value& v) {
|
||||
if (v.is_string() || v.is_safe()) return v.as_text();
|
||||
if (v.is_null()) return "None";
|
||||
if (v.is_undefined()) return "";
|
||||
if (const auto* b = std::get_if<bool>(&v.storage())) return *b ? "True" : "False";
|
||||
if (const auto* i = std::get_if<long long>(&v.storage())) return std::to_string(*i);
|
||||
if (const auto* d = std::get_if<double>(&v.storage())) {
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "%.17g", *d);
|
||||
return std::string(buf);
|
||||
}
|
||||
return validate::to_json(v);
|
||||
}
|
||||
|
||||
inline std::string strip_tags_impl(std::string_view s) {
|
||||
std::string out;
|
||||
bool in_tag = false;
|
||||
bool in_comment = false;
|
||||
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||
if (!in_tag && !in_comment && s.substr(i, 4) == "<!--") {
|
||||
in_comment = true;
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
if (in_comment) {
|
||||
if (s.substr(i, 3) == "-->") {
|
||||
in_comment = false;
|
||||
i += 2;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!in_tag && s[i] == '<') {
|
||||
in_tag = true;
|
||||
continue;
|
||||
}
|
||||
if (in_tag && s[i] == '>') {
|
||||
in_tag = false;
|
||||
continue;
|
||||
}
|
||||
if (!in_tag) out += s[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline std::map<std::string, FilterFn> builtin_filters() {
|
||||
std::map<std::string, FilterFn> f;
|
||||
f["escape"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
if (v.is_safe()) return v;
|
||||
return validate::Value::safe(http_msg::escape_html(value_to_text(v)));
|
||||
};
|
||||
f["e"] = f["escape"];
|
||||
f["safe"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return validate::Value::safe(value_to_text(v));
|
||||
};
|
||||
f["upper"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
std::string s = value_to_text(v);
|
||||
for (char& c : s) c = (char)std::toupper((unsigned char)c);
|
||||
return validate::Value(s);
|
||||
};
|
||||
f["lower"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
std::string s = value_to_text(v);
|
||||
for (char& c : s) c = (char)std::tolower((unsigned char)c);
|
||||
return validate::Value(s);
|
||||
};
|
||||
f["trim"] = [](const validate::Value& v, const std::vector<validate::Value>& args) {
|
||||
std::string chars = " \t\r\n";
|
||||
if (!args.empty()) chars = value_to_text(args[0]);
|
||||
std::string s = value_to_text(v);
|
||||
std::size_t a = s.find_first_not_of(chars);
|
||||
if (a == std::string::npos) return validate::Value(std::string(""));
|
||||
std::size_t b = s.find_last_not_of(chars);
|
||||
return validate::Value(s.substr(a, b - a + 1));
|
||||
};
|
||||
f["striptags"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return validate::Value(strip_tags_impl(value_to_text(v)));
|
||||
};
|
||||
f["urlencode"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return validate::Value(http_msg::percent_encode(value_to_text(v)));
|
||||
};
|
||||
f["length"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
if (v.is_string() || v.is_safe()) return validate::Value((long long)v.as_text().size());
|
||||
if (const auto* a = std::get_if<validate::Array>(&v.storage())) {
|
||||
return validate::Value((long long)a->size());
|
||||
}
|
||||
if (const auto* o = std::get_if<validate::Object>(&v.storage())) {
|
||||
return validate::Value((long long)o->size());
|
||||
}
|
||||
throw TemplateError("length filter needs string, sequence or mapping");
|
||||
};
|
||||
f["count"] = f["length"];
|
||||
f["default"] = [](const validate::Value& v, const std::vector<validate::Value>& args) {
|
||||
validate::Value fallback = args.empty() ? validate::Value("") : args[0];
|
||||
bool boolean = args.size() > 1 && args[1].truthy();
|
||||
if (v.is_undefined() || v.is_null()) return fallback;
|
||||
if (boolean && !v.truthy()) return fallback;
|
||||
return v;
|
||||
};
|
||||
f["d"] = f["default"];
|
||||
f["join"] = [](const validate::Value& v, const std::vector<validate::Value>& args) {
|
||||
std::string delim = args.empty() ? "" : value_to_text(args[0]);
|
||||
std::string attr;
|
||||
if (args.size() > 1) attr = value_to_text(args[1]);
|
||||
const auto* a = std::get_if<validate::Array>(&v.storage());
|
||||
if (a == nullptr) throw TemplateError("join filter needs a sequence");
|
||||
std::string out;
|
||||
bool first = true;
|
||||
for (const auto& item : *a) {
|
||||
if (!first) out += delim;
|
||||
first = false;
|
||||
if (!attr.empty() && item.is_object()) {
|
||||
const auto* o = std::get_if<validate::Object>(&item.storage());
|
||||
auto it = o->find(attr);
|
||||
out += (it == o->end()) ? "" : value_to_text(it->second);
|
||||
} else {
|
||||
out += value_to_text(item);
|
||||
}
|
||||
}
|
||||
return validate::Value(out);
|
||||
};
|
||||
f["date"] = [](const validate::Value& v, const std::vector<validate::Value>& args) {
|
||||
if (!v.is_number()) throw TemplateError("date filter needs an epoch number");
|
||||
std::string fmt = args.empty() ? "%Y-%m-%d %H:%M:%S" : value_to_text(args[0]);
|
||||
std::time_t t = (std::time_t)v.as_number();
|
||||
std::tm tmv{};
|
||||
#if defined(_WIN32)
|
||||
gmtime_s(&tmv, &t);
|
||||
#else
|
||||
gmtime_r(&t, &tmv);
|
||||
#endif
|
||||
char buf[256];
|
||||
if (std::strftime(buf, sizeof(buf), fmt.c_str(), &tmv) == 0) return validate::Value("");
|
||||
return validate::Value(std::string(buf));
|
||||
};
|
||||
f["tojson"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return validate::Value::safe(validate::to_json(v));
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,139 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates lexer. Splits source into Text, Var ({{ }}),
|
||||
// Block ({% %}) tokens; comments ({# #}) are dropped. Whitespace control
|
||||
// dashes ({{- , -}}) strip adjacent whitespace runs. Tag close search
|
||||
// respects single and double quoted strings.
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
class TemplateError : public std::runtime_error {
|
||||
public:
|
||||
explicit TemplateError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class UndefinedError : public TemplateError {
|
||||
public:
|
||||
explicit UndefinedError(const std::string& msg) : TemplateError(msg) {}
|
||||
};
|
||||
|
||||
enum class TokenKind { Text, Var, Block };
|
||||
|
||||
struct Token {
|
||||
TokenKind kind = TokenKind::Text;
|
||||
std::string text;
|
||||
std::size_t line = 1;
|
||||
};
|
||||
|
||||
inline bool is_space_char(char c) {
|
||||
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
|
||||
}
|
||||
|
||||
inline void rstrip_token(std::string& s) {
|
||||
while (!s.empty() && is_space_char(s.back())) s.pop_back();
|
||||
}
|
||||
|
||||
inline std::size_t find_tag_close(std::string_view src, std::size_t from, char close_first,
|
||||
char close_second) {
|
||||
char quote = 0;
|
||||
for (std::size_t i = from; i + 1 < src.size(); ++i) {
|
||||
char c = src[i];
|
||||
if (quote) {
|
||||
if (c == '\\') {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (c == quote) quote = 0;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'' || c == '"') {
|
||||
quote = c;
|
||||
continue;
|
||||
}
|
||||
if (c == close_first && src[i + 1] == close_second) return i;
|
||||
}
|
||||
return std::string_view::npos;
|
||||
}
|
||||
|
||||
inline std::vector<Token> lex_template(std::string_view src, std::string_view source_name) {
|
||||
std::vector<Token> out;
|
||||
std::size_t line = 1;
|
||||
std::size_t i = 0;
|
||||
auto push_text = [&](std::string_view t) {
|
||||
if (t.empty()) return;
|
||||
Token tok;
|
||||
tok.kind = TokenKind::Text;
|
||||
tok.text = std::string(t);
|
||||
tok.line = line;
|
||||
for (char c : t) {
|
||||
if (c == '\n') ++line;
|
||||
}
|
||||
out.push_back(std::move(tok));
|
||||
};
|
||||
while (i < src.size()) {
|
||||
std::size_t var_at = src.find("{{", i);
|
||||
std::size_t blk_at = src.find("{%", i);
|
||||
std::size_t com_at = src.find("{#", i);
|
||||
std::size_t next = std::string_view::npos;
|
||||
if (var_at != std::string_view::npos) next = var_at;
|
||||
if (blk_at != std::string_view::npos && (next == std::string_view::npos || blk_at < next)) {
|
||||
next = blk_at;
|
||||
}
|
||||
if (com_at != std::string_view::npos && (next == std::string_view::npos || com_at < next)) {
|
||||
next = com_at;
|
||||
}
|
||||
if (next == std::string_view::npos) {
|
||||
push_text(src.substr(i));
|
||||
break;
|
||||
}
|
||||
push_text(src.substr(i, next - i));
|
||||
if (next == com_at) {
|
||||
std::size_t end = src.find("#}", next + 2);
|
||||
if (end == std::string_view::npos) {
|
||||
throw TemplateError("unterminated comment in " + std::string(source_name));
|
||||
}
|
||||
for (std::size_t k = next; k < end + 2; ++k) {
|
||||
if (src[k] == '\n') ++line;
|
||||
}
|
||||
i = end + 2;
|
||||
continue;
|
||||
}
|
||||
bool is_var = (next == var_at);
|
||||
char cf = is_var ? '}' : '%';
|
||||
std::size_t open_end = next + 2;
|
||||
bool lstrip = open_end < src.size() && src[open_end] == '-';
|
||||
if (lstrip) ++open_end;
|
||||
std::size_t close = find_tag_close(src, open_end, cf, '}');
|
||||
if (close == std::string_view::npos) {
|
||||
throw TemplateError("unterminated tag in " + std::string(source_name));
|
||||
}
|
||||
std::size_t inner_end = close;
|
||||
bool rstrip = inner_end > open_end && src[inner_end - 1] == '-';
|
||||
if (rstrip) --inner_end;
|
||||
if (lstrip && !out.empty() && out.back().kind == TokenKind::Text) {
|
||||
rstrip_token(out.back().text);
|
||||
}
|
||||
Token tok;
|
||||
tok.kind = is_var ? TokenKind::Var : TokenKind::Block;
|
||||
tok.text = std::string(src.substr(open_end, inner_end - open_end));
|
||||
tok.line = line;
|
||||
for (std::size_t k = next; k < close + 2; ++k) {
|
||||
if (src[k] == '\n') ++line;
|
||||
}
|
||||
out.push_back(std::move(tok));
|
||||
i = close + 2;
|
||||
if (rstrip) {
|
||||
while (i < src.size() && is_space_char(src[i])) {
|
||||
if (src[i] == '\n') ++line;
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates loaders. DictLoader (in-memory map),
|
||||
// EmbeddedLoader (populated by the 09-cli-ops asset embedder) and
|
||||
// FileLoader (directory root with path traversal protection: rejects
|
||||
// absolute paths, drive letters, backslashes, null bytes and .. segments).
|
||||
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "lexer.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
class Loader {
|
||||
public:
|
||||
virtual ~Loader() = default;
|
||||
virtual std::optional<std::string> load(const std::string& name) = 0;
|
||||
virtual std::string kind() const = 0;
|
||||
};
|
||||
|
||||
class DictLoader : public Loader {
|
||||
public:
|
||||
explicit DictLoader(std::map<std::string, std::string> templates = {})
|
||||
: templates_(std::move(templates)) {}
|
||||
|
||||
void set(const std::string& name, std::string source) { templates_[name] = std::move(source); }
|
||||
|
||||
std::optional<std::string> load(const std::string& name) override {
|
||||
auto it = templates_.find(name);
|
||||
if (it == templates_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::string kind() const override { return "dict"; }
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> templates_;
|
||||
};
|
||||
|
||||
class EmbeddedLoader : public Loader {
|
||||
public:
|
||||
void embed(const std::string& name, std::string source) {
|
||||
assets_[name] = std::move(source);
|
||||
}
|
||||
|
||||
std::optional<std::string> load(const std::string& name) override {
|
||||
auto it = assets_.find(name);
|
||||
if (it == assets_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::string kind() const override { return "embedded"; }
|
||||
|
||||
private:
|
||||
std::map<std::string, std::string> assets_;
|
||||
};
|
||||
|
||||
class FileLoader : public Loader {
|
||||
public:
|
||||
explicit FileLoader(std::string root) : root_(std::move(root)) {}
|
||||
|
||||
std::optional<std::string> load(const std::string& name) override {
|
||||
std::string safe = sanitize(name);
|
||||
if (safe.empty()) throw TemplateError("unsafe template path: " + name);
|
||||
std::string full = root_ + "/" + safe;
|
||||
std::ifstream in(full, std::ios::binary);
|
||||
if (!in) return std::nullopt;
|
||||
std::ostringstream ss;
|
||||
ss << in.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
std::string kind() const override { return "file"; }
|
||||
|
||||
// Exposed for tests: sanitized relative path or "" when rejected.
|
||||
static std::string sanitize(std::string_view name) {
|
||||
if (name.empty() || name.size() > 1024) return "";
|
||||
if (name[0] == '/' || name[0] == '\\') return "";
|
||||
if (name.size() >= 2 && name[1] == ':') return "";
|
||||
std::vector<std::string> parts;
|
||||
std::size_t i = 0;
|
||||
while (i <= name.size()) {
|
||||
std::size_t slash = name.find('/', i);
|
||||
if (slash == std::string_view::npos) slash = name.size();
|
||||
std::string_view seg = name.substr(i, slash - i);
|
||||
if (seg.empty() || seg == ".") {
|
||||
// Skip.
|
||||
} else if (seg == "..") {
|
||||
return "";
|
||||
} else {
|
||||
for (char c : seg) {
|
||||
if (c == '\\' || c == '\0') return "";
|
||||
}
|
||||
parts.emplace_back(seg);
|
||||
}
|
||||
if (slash == name.size()) break;
|
||||
i = slash + 1;
|
||||
}
|
||||
if (parts.empty()) return "";
|
||||
std::string out;
|
||||
for (std::size_t k = 0; k < parts.size(); ++k) {
|
||||
if (k) out += '/';
|
||||
out += parts[k];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string root_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,823 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates parser. Builds the AST from lexer tokens:
|
||||
// extends, block/endblock, include, if/elif/else/endif, for/else/endfor,
|
||||
// set, macro/endmacro, autoescape/endautoescape, plus {{ }} output.
|
||||
// Expression grammar with precedence: or, and, not, comparison (== != < >
|
||||
// <= >= in not-in is is-not), additive (+ - ~), multiplicative (* / // %),
|
||||
// unary, postfix (.attr [index] (call) |filter), primary.
|
||||
|
||||
#include <cctype>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "ast.h"
|
||||
#include "lexer.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
struct ExprToken {
|
||||
enum class Kind { End, Number, String, Name, Op, Punct };
|
||||
Kind kind = Kind::End;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
inline std::vector<ExprToken> lex_expr(std::string_view s, std::string_view source_name) {
|
||||
std::vector<ExprToken> out;
|
||||
std::size_t i = 0;
|
||||
while (i < s.size()) {
|
||||
char c = s[i];
|
||||
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (std::isdigit((unsigned char)c) || (c == '.' && i + 1 < s.size() &&
|
||||
std::isdigit((unsigned char)s[i + 1]))) {
|
||||
std::size_t start = i;
|
||||
while (i < s.size() && std::isdigit((unsigned char)s[i])) ++i;
|
||||
if (i < s.size() && s[i] == '.') {
|
||||
++i;
|
||||
while (i < s.size() && std::isdigit((unsigned char)s[i])) ++i;
|
||||
}
|
||||
if (i < s.size() && (s[i] == 'e' || s[i] == 'E')) {
|
||||
std::size_t save = i;
|
||||
++i;
|
||||
if (i < s.size() && (s[i] == '+' || s[i] == '-')) ++i;
|
||||
if (i < s.size() && std::isdigit((unsigned char)s[i])) {
|
||||
while (i < s.size() && std::isdigit((unsigned char)s[i])) ++i;
|
||||
} else {
|
||||
i = save;
|
||||
}
|
||||
}
|
||||
out.push_back({ExprToken::Kind::Number, std::string(s.substr(start, i - start))});
|
||||
continue;
|
||||
}
|
||||
if (c == '\'' || c == '"') {
|
||||
char quote = c;
|
||||
++i;
|
||||
std::string val;
|
||||
bool closed = false;
|
||||
while (i < s.size()) {
|
||||
char d = s[i++];
|
||||
if (d == '\\' && i < s.size()) {
|
||||
char e = s[i++];
|
||||
switch (e) {
|
||||
case 'n': val += '\n'; break;
|
||||
case 't': val += '\t'; break;
|
||||
case 'r': val += '\r'; break;
|
||||
case '\\': val += '\\'; break;
|
||||
case '\'': val += '\''; break;
|
||||
case '"': val += '"'; break;
|
||||
default: val += e; break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (d == quote) {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
val += d;
|
||||
}
|
||||
if (!closed) throw TemplateError("unterminated string in " + std::string(source_name));
|
||||
out.push_back({ExprToken::Kind::String, val});
|
||||
continue;
|
||||
}
|
||||
if (std::isalpha((unsigned char)c) || c == '_') {
|
||||
std::size_t start = i;
|
||||
while (i < s.size() && (std::isalnum((unsigned char)s[i]) || s[i] == '_')) ++i;
|
||||
out.push_back({ExprToken::Kind::Name, std::string(s.substr(start, i - start))});
|
||||
continue;
|
||||
}
|
||||
if (c == '=' && i + 1 < s.size() && s[i + 1] == '=') {
|
||||
out.push_back({ExprToken::Kind::Op, "=="});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '!' && i + 1 < s.size() && s[i + 1] == '=') {
|
||||
out.push_back({ExprToken::Kind::Op, "!="});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '<' && i + 1 < s.size() && s[i + 1] == '=') {
|
||||
out.push_back({ExprToken::Kind::Op, "<="});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '>' && i + 1 < s.size() && s[i + 1] == '=') {
|
||||
out.push_back({ExprToken::Kind::Op, ">="});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < s.size() && s[i + 1] == '/') {
|
||||
out.push_back({ExprToken::Kind::Op, "//"});
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '<' || c == '>' || c == '+' || c == '-' || c == '*' || c == '/' || c == '%' ||
|
||||
c == '~' || c == '=') {
|
||||
out.push_back({ExprToken::Kind::Op, std::string(1, c)});
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' ||
|
||||
c == '.' || c == '|' || c == ':') {
|
||||
out.push_back({ExprToken::Kind::Punct, std::string(1, c)});
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
throw TemplateError("bad character in expression in " + std::string(source_name));
|
||||
}
|
||||
out.push_back({ExprToken::Kind::End, ""});
|
||||
return out;
|
||||
}
|
||||
|
||||
class ExprParser {
|
||||
public:
|
||||
ExprParser(const std::vector<ExprToken>& toks, std::string_view source_name)
|
||||
: toks_(toks), source_(source_name) {}
|
||||
|
||||
ExprPtr parse() {
|
||||
ExprPtr e = parse_or(0);
|
||||
if (peek().kind != ExprToken::Kind::End) {
|
||||
throw TemplateError("trailing tokens in expression in " + std::string(source_));
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
private:
|
||||
const ExprToken& peek() const { return toks_[pos_]; }
|
||||
const ExprToken& peek_at(std::size_t ahead) const {
|
||||
std::size_t p = pos_ + ahead;
|
||||
return toks_[p < toks_.size() ? p : toks_.size() - 1];
|
||||
}
|
||||
bool accept_name(const std::string& w) {
|
||||
if (peek().kind == ExprToken::Kind::Name && peek().text == w) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool accept_op(const std::string& o) {
|
||||
if (peek().kind == ExprToken::Kind::Op && peek().text == o) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool accept_punct(const std::string& p) {
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == p) {
|
||||
++pos_;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void expect_punct(const std::string& p) {
|
||||
if (!accept_punct(p)) {
|
||||
throw TemplateError("expected '" + p + "' in " + std::string(source_));
|
||||
}
|
||||
}
|
||||
|
||||
void guard_depth(std::size_t depth) {
|
||||
if (depth > caps::kMaxExprDepth) {
|
||||
throw TemplateError("expression too deep in " + std::string(source_));
|
||||
}
|
||||
}
|
||||
|
||||
ExprPtr parse_or(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr left = parse_and(depth + 1);
|
||||
while (accept_name("or")) {
|
||||
ExprPtr right = parse_and(depth + 1);
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::BoolOp;
|
||||
e->op = "or";
|
||||
e->left = left;
|
||||
e->right = right;
|
||||
left = e;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
ExprPtr parse_and(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr left = parse_not(depth + 1);
|
||||
while (accept_name("and")) {
|
||||
ExprPtr right = parse_not(depth + 1);
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::BoolOp;
|
||||
e->op = "and";
|
||||
e->left = left;
|
||||
e->right = right;
|
||||
left = e;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
ExprPtr parse_not(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
if (accept_name("not")) {
|
||||
// "not in" is handled in comparison; rewind if followed by "in".
|
||||
ExprPtr inner = parse_not(depth + 1);
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Not;
|
||||
e->operand = inner;
|
||||
return e;
|
||||
}
|
||||
return parse_comparison(depth + 1);
|
||||
}
|
||||
|
||||
ExprPtr parse_comparison(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr left = parse_additive(depth + 1);
|
||||
if (peek().kind == ExprToken::Kind::Op &&
|
||||
(peek().text == "==" || peek().text == "!=" || peek().text == "<" ||
|
||||
peek().text == ">" || peek().text == "<=" || peek().text == ">=")) {
|
||||
std::string op = peek().text;
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Compare;
|
||||
e->op = op;
|
||||
e->left = left;
|
||||
e->right = parse_additive(depth + 1);
|
||||
return e;
|
||||
}
|
||||
if (peek().kind == ExprToken::Kind::Name && peek().text == "in") {
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::In;
|
||||
e->left = left;
|
||||
e->seq = parse_additive(depth + 1);
|
||||
return e;
|
||||
}
|
||||
if (peek().kind == ExprToken::Kind::Name && peek().text == "not" &&
|
||||
peek_at(1).kind == ExprToken::Kind::Name && peek_at(1).text == "in") {
|
||||
pos_ += 2;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::In;
|
||||
e->negated = true;
|
||||
e->left = left;
|
||||
e->seq = parse_additive(depth + 1);
|
||||
return e;
|
||||
}
|
||||
if (peek().kind == ExprToken::Kind::Name && peek().text == "is") {
|
||||
++pos_;
|
||||
bool neg = accept_name("not");
|
||||
if (peek().kind != ExprToken::Kind::Name) {
|
||||
throw TemplateError("expected test name after 'is' in " + std::string(source_));
|
||||
}
|
||||
std::string test = peek().text;
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Test;
|
||||
e->name = test;
|
||||
e->negated = neg;
|
||||
e->operand = left;
|
||||
if (accept_punct("(")) {
|
||||
e->args = parse_args();
|
||||
expect_punct(")");
|
||||
}
|
||||
return e;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
ExprPtr parse_additive(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr left = parse_multiplicative(depth + 1);
|
||||
while (peek().kind == ExprToken::Kind::Op &&
|
||||
(peek().text == "+" || peek().text == "-" || peek().text == "~")) {
|
||||
std::string op = peek().text;
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Binary;
|
||||
e->op = op;
|
||||
e->left = left;
|
||||
e->right = parse_multiplicative(depth + 1);
|
||||
left = e;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
ExprPtr parse_multiplicative(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr left = parse_unary(depth + 1);
|
||||
while (peek().kind == ExprToken::Kind::Op &&
|
||||
(peek().text == "*" || peek().text == "/" || peek().text == "//" ||
|
||||
peek().text == "%")) {
|
||||
std::string op = peek().text;
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Binary;
|
||||
e->op = op;
|
||||
e->left = left;
|
||||
e->right = parse_unary(depth + 1);
|
||||
left = e;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
ExprPtr parse_unary(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
if (accept_op("-")) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Unary;
|
||||
e->op = "-";
|
||||
e->operand = parse_unary(depth + 1);
|
||||
return e;
|
||||
}
|
||||
if (accept_op("+")) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Unary;
|
||||
e->op = "+";
|
||||
e->operand = parse_unary(depth + 1);
|
||||
return e;
|
||||
}
|
||||
return parse_postfix(depth + 1);
|
||||
}
|
||||
|
||||
ExprPtr parse_postfix(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
ExprPtr base = parse_primary(depth + 1);
|
||||
while (true) {
|
||||
if (accept_punct(".")) {
|
||||
if (peek().kind != ExprToken::Kind::Name) {
|
||||
throw TemplateError("expected attribute name in " + std::string(source_));
|
||||
}
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Attr;
|
||||
e->operand = base;
|
||||
e->name = peek().text;
|
||||
++pos_;
|
||||
base = e;
|
||||
continue;
|
||||
}
|
||||
if (accept_punct("[")) {
|
||||
ExprPtr idx = parse_or(depth + 1);
|
||||
expect_punct("]");
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Index;
|
||||
e->operand = base;
|
||||
e->right = idx;
|
||||
base = e;
|
||||
continue;
|
||||
}
|
||||
if (accept_punct("(")) {
|
||||
std::vector<ExprPtr> args;
|
||||
std::vector<std::pair<std::string, ExprPtr>> kwargs;
|
||||
parse_call_args(args, kwargs, depth + 1);
|
||||
expect_punct(")");
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Call;
|
||||
e->operand = base;
|
||||
e->args = std::move(args);
|
||||
e->kwargs = std::move(kwargs);
|
||||
base = e;
|
||||
continue;
|
||||
}
|
||||
if (accept_punct("|")) {
|
||||
if (peek().kind != ExprToken::Kind::Name) {
|
||||
throw TemplateError("expected filter name in " + std::string(source_));
|
||||
}
|
||||
std::string fname = peek().text;
|
||||
++pos_;
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Filter;
|
||||
e->name = fname;
|
||||
e->operand = base;
|
||||
if (accept_punct("(")) {
|
||||
e->args = parse_args(depth + 1);
|
||||
expect_punct(")");
|
||||
}
|
||||
base = e;
|
||||
continue;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
}
|
||||
|
||||
ExprPtr parse_primary(std::size_t depth) {
|
||||
guard_depth(depth);
|
||||
const ExprToken& t = peek();
|
||||
if (t.kind == ExprToken::Kind::Number) {
|
||||
++pos_;
|
||||
if (t.text.find_first_of(".eE") == std::string::npos) {
|
||||
return lit(validate::Value((long long)std::stoll(t.text)));
|
||||
}
|
||||
return lit(validate::Value(std::stod(t.text)));
|
||||
}
|
||||
if (t.kind == ExprToken::Kind::String) {
|
||||
++pos_;
|
||||
return lit(validate::Value(t.text));
|
||||
}
|
||||
if (t.kind == ExprToken::Kind::Name) {
|
||||
++pos_;
|
||||
if (t.text == "true" || t.text == "True") return lit(validate::Value(true));
|
||||
if (t.text == "false" || t.text == "False") return lit(validate::Value(false));
|
||||
if (t.text == "none" || t.text == "None" || t.text == "null") {
|
||||
return lit(validate::Value::null());
|
||||
}
|
||||
return name_expr(t.text);
|
||||
}
|
||||
if (accept_punct("(")) {
|
||||
ExprPtr e = parse_or(depth + 1);
|
||||
expect_punct(")");
|
||||
return e;
|
||||
}
|
||||
if (accept_punct("[")) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::List;
|
||||
if (!accept_punct("]")) {
|
||||
while (true) {
|
||||
e->args.push_back(parse_or(depth + 1));
|
||||
if (accept_punct("]")) break;
|
||||
expect_punct(",");
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == "]") {
|
||||
++pos_;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
if (accept_punct("{")) {
|
||||
ExprPtr e = std::make_shared<Expr>();
|
||||
e->kind = Expr::Kind::Dict;
|
||||
if (!accept_punct("}")) {
|
||||
while (true) {
|
||||
ExprPtr k = parse_or(depth + 1);
|
||||
expect_punct(":");
|
||||
ExprPtr v = parse_or(depth + 1);
|
||||
e->pairs.emplace_back(k, v);
|
||||
if (accept_punct("}")) break;
|
||||
expect_punct(",");
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == "}") {
|
||||
++pos_;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
throw TemplateError("unexpected token in expression in " + std::string(source_));
|
||||
}
|
||||
|
||||
std::vector<ExprPtr> parse_args(std::size_t depth = 0) {
|
||||
std::vector<ExprPtr> args;
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == ")") return args;
|
||||
while (true) {
|
||||
args.push_back(parse_or(depth + 1));
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == ")") return args;
|
||||
expect_punct(",");
|
||||
}
|
||||
}
|
||||
|
||||
void parse_call_args(std::vector<ExprPtr>& args,
|
||||
std::vector<std::pair<std::string, ExprPtr>>& kwargs, std::size_t depth) {
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == ")") return;
|
||||
while (true) {
|
||||
if (peek().kind == ExprToken::Kind::Name && peek_at(1).kind == ExprToken::Kind::Op &&
|
||||
peek_at(1).text == "=") {
|
||||
std::string key = peek().text;
|
||||
pos_ += 2;
|
||||
kwargs.emplace_back(key, parse_or(depth + 1));
|
||||
} else {
|
||||
args.push_back(parse_or(depth + 1));
|
||||
}
|
||||
if (peek().kind == ExprToken::Kind::Punct && peek().text == ")") return;
|
||||
expect_punct(",");
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<ExprToken>& toks_;
|
||||
std::string_view source_;
|
||||
std::size_t pos_ = 0;
|
||||
};
|
||||
|
||||
inline ExprPtr parse_expression(std::string_view text, std::string_view source_name) {
|
||||
std::vector<ExprToken> toks = lex_expr(text, source_name);
|
||||
ExprParser parser(toks, source_name);
|
||||
return parser.parse();
|
||||
}
|
||||
|
||||
class TemplateParser {
|
||||
public:
|
||||
TemplateParser(const std::vector<Token>& toks, std::string_view source_name)
|
||||
: toks_(toks), source_(source_name) {}
|
||||
|
||||
std::vector<NodePtr> parse() {
|
||||
std::vector<NodePtr> body = parse_body({});
|
||||
if (pos_ != toks_.size()) {
|
||||
throw TemplateError("unexpected end tag in " + std::string(source_));
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string_view first_word(std::string_view s) {
|
||||
std::size_t i = 0;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
std::size_t start = i;
|
||||
while (i < s.size() && s[i] != ' ' && s[i] != '\t') ++i;
|
||||
return s.substr(start, i - start);
|
||||
}
|
||||
|
||||
static std::string_view rest_after_first(std::string_view s) {
|
||||
std::size_t i = 0;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
while (i < s.size() && s[i] != ' ' && s[i] != '\t') ++i;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
return s.substr(i);
|
||||
}
|
||||
|
||||
std::vector<NodePtr> parse_body(const std::set<std::string>& stop) {
|
||||
std::vector<NodePtr> body;
|
||||
while (pos_ < toks_.size()) {
|
||||
const Token& tok = toks_[pos_];
|
||||
if (tok.kind == TokenKind::Text) {
|
||||
body.push_back(text_node(tok.text));
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
if (tok.kind == TokenKind::Var) {
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Output;
|
||||
n->expr = parse_expression(tok.text, source_);
|
||||
body.push_back(n);
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
std::string kw(first_word(tok.text));
|
||||
if (stop.count(kw)) return body;
|
||||
if (kw == "if") {
|
||||
body.push_back(parse_if());
|
||||
} else if (kw == "for") {
|
||||
body.push_back(parse_for());
|
||||
} else if (kw == "block") {
|
||||
body.push_back(parse_block());
|
||||
} else if (kw == "extends") {
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Extends;
|
||||
n->expr = parse_expression(rest_after_first(tok.text), source_);
|
||||
body.push_back(n);
|
||||
++pos_;
|
||||
} else if (kw == "include") {
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Include;
|
||||
n->expr = parse_expression(rest_after_first(tok.text), source_);
|
||||
body.push_back(n);
|
||||
++pos_;
|
||||
} else if (kw == "set") {
|
||||
body.push_back(parse_set());
|
||||
} else if (kw == "macro") {
|
||||
body.push_back(parse_macro());
|
||||
} else if (kw == "autoescape") {
|
||||
body.push_back(parse_autoescape());
|
||||
} else {
|
||||
throw TemplateError("unknown tag '" + kw + "' in " + std::string(source_));
|
||||
}
|
||||
}
|
||||
if (!stop.empty()) {
|
||||
throw TemplateError("missing end tag in " + std::string(source_));
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
NodePtr parse_if() {
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::If;
|
||||
IfBranch first;
|
||||
first.cond = parse_expression(rest_after_first(toks_[pos_].text), source_);
|
||||
++pos_;
|
||||
first.body = parse_body({"elif", "else", "endif"});
|
||||
n->branches.push_back(std::move(first));
|
||||
while (pos_ < toks_.size()) {
|
||||
std::string kw(first_word(toks_[pos_].text));
|
||||
if (kw == "elif") {
|
||||
IfBranch b;
|
||||
b.cond = parse_expression(rest_after_first(toks_[pos_].text), source_);
|
||||
++pos_;
|
||||
b.body = parse_body({"elif", "else", "endif"});
|
||||
n->branches.push_back(std::move(b));
|
||||
} else if (kw == "else") {
|
||||
++pos_;
|
||||
IfBranch b;
|
||||
b.body = parse_body({"endif"});
|
||||
n->branches.push_back(std::move(b));
|
||||
break;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect_kw("endif");
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr parse_for() {
|
||||
std::string rest(rest_after_first(toks_[pos_].text));
|
||||
std::size_t in_at = rest.find(" in ");
|
||||
if (in_at == std::string::npos) {
|
||||
throw TemplateError("for tag needs 'in' in " + std::string(source_));
|
||||
}
|
||||
std::string targets = rest.substr(0, in_at);
|
||||
std::string seq = rest.substr(in_at + 4);
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::For;
|
||||
std::size_t i = 0;
|
||||
while (i < targets.size()) {
|
||||
while (i < targets.size() && (targets[i] == ' ' || targets[i] == '\t' || targets[i] == ',')) {
|
||||
++i;
|
||||
}
|
||||
std::size_t start = i;
|
||||
while (i < targets.size() && targets[i] != ' ' && targets[i] != '\t' &&
|
||||
targets[i] != ',') {
|
||||
++i;
|
||||
}
|
||||
if (i > start) n->targets.push_back(targets.substr(start, i - start));
|
||||
}
|
||||
if (n->targets.empty() || n->targets.size() > 2) {
|
||||
throw TemplateError("for tag needs one or two targets in " + std::string(source_));
|
||||
}
|
||||
n->seq = parse_expression(seq, source_);
|
||||
++pos_;
|
||||
n->body = parse_body({"else", "endfor"});
|
||||
if (pos_ < toks_.size() && first_word(toks_[pos_].text) == "else") {
|
||||
++pos_;
|
||||
n->else_body = parse_body({"endfor"});
|
||||
}
|
||||
expect_kw("endfor");
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr parse_block() {
|
||||
std::string rest(rest_after_first(toks_[pos_].text));
|
||||
std::string name(first_word(rest));
|
||||
if (name.empty()) throw TemplateError("block tag needs a name in " + std::string(source_));
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Block;
|
||||
n->text = name;
|
||||
++pos_;
|
||||
n->body = parse_body({"endblock"});
|
||||
expect_kw("endblock");
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr parse_set() {
|
||||
std::string rest(rest_after_first(toks_[pos_].text));
|
||||
std::size_t eq = rest.find('=');
|
||||
if (eq == std::string::npos || eq + 1 >= rest.size() || rest[eq + 1] == '=') {
|
||||
throw TemplateError("set tag needs name = value in " + std::string(source_));
|
||||
}
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Set;
|
||||
std::string name(rest.substr(0, eq));
|
||||
while (!name.empty() && (name.back() == ' ' || name.back() == '\t')) name.pop_back();
|
||||
n->text = name;
|
||||
n->expr = parse_expression(rest.substr(eq + 1), source_);
|
||||
++pos_;
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr parse_macro() {
|
||||
std::string rest(rest_after_first(toks_[pos_].text));
|
||||
std::size_t paren = rest.find('(');
|
||||
std::size_t close = rest.rfind(')');
|
||||
if (paren == std::string::npos || close == std::string::npos || close < paren) {
|
||||
throw TemplateError("macro tag needs name(args) in " + std::string(source_));
|
||||
}
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Macro;
|
||||
std::string name = rest.substr(0, paren);
|
||||
while (!name.empty() && (name.back() == ' ' || name.back() == '\t')) name.pop_back();
|
||||
n->text = name;
|
||||
std::string arglist = rest.substr(paren + 1, close - paren - 1);
|
||||
std::size_t i = 0;
|
||||
while (i < arglist.size()) {
|
||||
while (i < arglist.size() && (arglist[i] == ' ' || arglist[i] == '\t' || arglist[i] == ',')) {
|
||||
++i;
|
||||
}
|
||||
if (i >= arglist.size()) break;
|
||||
std::size_t start = i;
|
||||
int depth = 0;
|
||||
char quote = 0;
|
||||
while (i < arglist.size()) {
|
||||
char c = arglist[i];
|
||||
if (quote) {
|
||||
if (c == '\\') {
|
||||
++i;
|
||||
} else if (c == quote) {
|
||||
quote = 0;
|
||||
}
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'' || c == '"') {
|
||||
quote = c;
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (c == '(' || c == '[' || c == '{') ++depth;
|
||||
if (c == ')' || c == ']' || c == '}') --depth;
|
||||
if (c == ',' && depth == 0) break;
|
||||
++i;
|
||||
}
|
||||
std::string piece = arglist.substr(start, i - start);
|
||||
if (i < arglist.size() && arglist[i] == ',') ++i;
|
||||
std::size_t eq = piece.find('=');
|
||||
if (eq == std::string::npos) {
|
||||
std::string pname = piece;
|
||||
while (!pname.empty() && (pname.back() == ' ' || pname.back() == '\t')) pname.pop_back();
|
||||
std::size_t s = 0;
|
||||
while (s < pname.size() && (pname[s] == ' ' || pname[s] == '\t')) ++s;
|
||||
n->params.push_back(pname.substr(s));
|
||||
n->defaults.push_back(std::nullopt);
|
||||
} else {
|
||||
std::string pname = piece.substr(0, eq);
|
||||
while (!pname.empty() && (pname.back() == ' ' || pname.back() == '\t')) pname.pop_back();
|
||||
std::size_t s = 0;
|
||||
while (s < pname.size() && (pname[s] == ' ' || pname[s] == '\t')) ++s;
|
||||
n->params.push_back(pname.substr(s));
|
||||
// Defaults are literal-only at definition; full expressions are a
|
||||
// documented gap (use set plus call with explicit args instead).
|
||||
std::string def = piece.substr(eq + 1);
|
||||
n->defaults.push_back(eval_literal_default(def));
|
||||
}
|
||||
if (n->params.size() > caps::kMaxMacroArgs) {
|
||||
throw TemplateError("too many macro args in " + std::string(source_));
|
||||
}
|
||||
}
|
||||
++pos_;
|
||||
n->body = parse_body({"endmacro"});
|
||||
expect_kw("endmacro");
|
||||
return n;
|
||||
}
|
||||
|
||||
validate::Value eval_literal_default(std::string_view def) {
|
||||
std::string t(def);
|
||||
std::size_t s = 0;
|
||||
while (s < t.size() && (t[s] == ' ' || t[s] == '\t')) ++s;
|
||||
std::size_t e = t.size();
|
||||
while (e > s && (t[e - 1] == ' ' || t[e - 1] == '\t')) --e;
|
||||
std::string v = t.substr(s, e - s);
|
||||
if (v.size() >= 2 && ((v.front() == '"' && v.back() == '"') ||
|
||||
(v.front() == '\'' && v.back() == '\''))) {
|
||||
return validate::Value(v.substr(1, v.size() - 2));
|
||||
}
|
||||
if (v == "true" || v == "True") return validate::Value(true);
|
||||
if (v == "false" || v == "False") return validate::Value(false);
|
||||
if (v == "none" || v == "None" || v == "null") return validate::Value::null();
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
long long i = std::stoll(v, &used);
|
||||
if (used == v.size()) return validate::Value(i);
|
||||
} catch (...) {
|
||||
}
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
double d = std::stod(v, &used);
|
||||
if (used == v.size()) return validate::Value(d);
|
||||
} catch (...) {
|
||||
}
|
||||
throw TemplateError("macro default must be a literal in " + std::string(source_));
|
||||
}
|
||||
|
||||
NodePtr parse_autoescape() {
|
||||
std::string rest(rest_after_first(toks_[pos_].text));
|
||||
std::string word(first_word(rest));
|
||||
NodePtr n = std::make_shared<Node>();
|
||||
n->kind = Node::Kind::Autoescape;
|
||||
if (word == "true" || word == "True") {
|
||||
n->flag = true;
|
||||
} else if (word == "false" || word == "False") {
|
||||
n->flag = false;
|
||||
} else {
|
||||
throw TemplateError("autoescape needs true or false in " + std::string(source_));
|
||||
}
|
||||
++pos_;
|
||||
n->body = parse_body({"endautoescape"});
|
||||
expect_kw("endautoescape");
|
||||
return n;
|
||||
}
|
||||
|
||||
void expect_kw(const std::string& kw) {
|
||||
if (pos_ >= toks_.size() || toks_[pos_].kind != TokenKind::Block ||
|
||||
first_word(toks_[pos_].text) != kw) {
|
||||
throw TemplateError("expected '" + kw + "' in " + std::string(source_));
|
||||
}
|
||||
++pos_;
|
||||
}
|
||||
|
||||
const std::vector<Token>& toks_;
|
||||
std::string_view source_;
|
||||
std::size_t pos_ = 0;
|
||||
};
|
||||
|
||||
inline std::vector<NodePtr> parse_template(const std::vector<Token>& toks,
|
||||
std::string_view source_name) {
|
||||
TemplateParser parser(toks, source_name);
|
||||
return parser.parse();
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates shipped tests (plan 05, section 6 Templates):
|
||||
// defined, none, string, number, sequence, mapping, even, odd.
|
||||
// Used as `x is <test>` with optional `not`.
|
||||
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../validate/value.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
using TestFn =
|
||||
std::function<bool(const validate::Value&, const std::vector<validate::Value>&)>;
|
||||
|
||||
inline std::map<std::string, TestFn> builtin_tests() {
|
||||
std::map<std::string, TestFn> t;
|
||||
t["defined"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return !v.is_undefined();
|
||||
};
|
||||
t["none"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return v.is_null();
|
||||
};
|
||||
t["string"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return v.is_string() || v.is_safe();
|
||||
};
|
||||
t["number"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return v.is_number();
|
||||
};
|
||||
t["sequence"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return v.is_array() || v.is_string() || v.is_safe();
|
||||
};
|
||||
t["mapping"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
return v.is_object();
|
||||
};
|
||||
t["even"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
if (!v.is_int()) return false;
|
||||
return (*std::get_if<long long>(&v.storage()) % 2) == 0;
|
||||
};
|
||||
t["odd"] = [](const validate::Value& v, const std::vector<validate::Value>&) {
|
||||
if (!v.is_int()) return false;
|
||||
return (*std::get_if<long long>(&v.storage()) % 2) != 0;
|
||||
};
|
||||
return t;
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,639 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates::Renderer. Executes compiled templates:
|
||||
// extends/block override chains, includes, if/for with loop variable,
|
||||
// set, macros, filters, tests, autoescape and the undefined policy.
|
||||
// Caps enforced per render: include depth 16, extends chain 8, loop
|
||||
// iterations 100000, output 32 MiB. Recursion beyond depth aborts with
|
||||
// TemplateError (mapped to 500 upstream), never a stack overflow.
|
||||
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "../http_msg/html.h"
|
||||
#include "../validate/json.h"
|
||||
#include "../validate/value.h"
|
||||
#include "ast.h"
|
||||
#include "context.h"
|
||||
#include "environment.h"
|
||||
#include "filters.h"
|
||||
#include "lexer.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
class Renderer {
|
||||
public:
|
||||
explicit Renderer(Environment* env) : env_(env) {}
|
||||
|
||||
std::string render_template(const std::string& name, validate::Object context = {}) {
|
||||
++env_->stats().renders;
|
||||
include_depth_ = 0;
|
||||
try {
|
||||
std::shared_ptr<CompiledTemplate> compiled = env_->get_compiled(name);
|
||||
Context ctx(env_->globals());
|
||||
for (const auto& kv : context) ctx.set(kv.first, kv.second);
|
||||
std::map<std::string, std::vector<NodePtr>> no_overrides;
|
||||
render_with_inheritance(compiled, ctx, no_overrides, 0);
|
||||
return output_;
|
||||
} catch (...) {
|
||||
++env_->stats().errors;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
std::string render_nodes_source(const std::string& source, const std::string& name,
|
||||
validate::Object context = {}) {
|
||||
++env_->stats().renders;
|
||||
include_depth_ = 0;
|
||||
try {
|
||||
std::shared_ptr<CompiledTemplate> compiled = env_->compile_source(source, name);
|
||||
Context ctx(env_->globals());
|
||||
for (const auto& kv : context) ctx.set(kv.first, kv.second);
|
||||
std::map<std::string, std::vector<NodePtr>> no_overrides;
|
||||
render_with_inheritance(compiled, ctx, no_overrides, 0);
|
||||
return output_;
|
||||
} catch (...) {
|
||||
++env_->stats().errors;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void render_nodes(const std::vector<NodePtr>& nodes, Context& ctx, bool autoescape,
|
||||
const std::map<std::string, std::vector<NodePtr>>& overrides) {
|
||||
for (const NodePtr& node : nodes) {
|
||||
render_node(node, ctx, autoescape, overrides);
|
||||
}
|
||||
}
|
||||
|
||||
validate::Value eval(const ExprPtr& expr, Context& ctx) {
|
||||
switch (expr->kind) {
|
||||
case Expr::Kind::Literal:
|
||||
return expr->literal;
|
||||
case Expr::Kind::Name:
|
||||
return ctx.lookup(expr->name);
|
||||
case Expr::Kind::Attr:
|
||||
return eval_attr(expr, ctx);
|
||||
case Expr::Kind::Index:
|
||||
return eval_index(expr, ctx);
|
||||
case Expr::Kind::Call:
|
||||
return eval_call(expr, ctx);
|
||||
case Expr::Kind::Unary:
|
||||
return eval_unary(expr, ctx);
|
||||
case Expr::Kind::Binary:
|
||||
return eval_binary(expr, ctx);
|
||||
case Expr::Kind::Compare:
|
||||
return eval_compare(expr, ctx);
|
||||
case Expr::Kind::BoolOp: {
|
||||
validate::Value left = eval(expr->left, ctx);
|
||||
if (expr->op == "and") {
|
||||
if (!left.truthy()) return left;
|
||||
return eval(expr->right, ctx);
|
||||
}
|
||||
if (left.truthy()) return left;
|
||||
return eval(expr->right, ctx);
|
||||
}
|
||||
case Expr::Kind::Not:
|
||||
return validate::Value(!eval(expr->operand, ctx).truthy());
|
||||
case Expr::Kind::In:
|
||||
return eval_in(expr, ctx);
|
||||
case Expr::Kind::Filter: {
|
||||
validate::Value base = eval(expr->operand, ctx);
|
||||
std::vector<validate::Value> args;
|
||||
for (const auto& a : expr->args) args.push_back(eval(a, ctx));
|
||||
auto it = env_->filters().find(expr->name);
|
||||
if (it == env_->filters().end()) {
|
||||
throw TemplateError("unknown filter '" + expr->name + "'");
|
||||
}
|
||||
return it->second(base, args);
|
||||
}
|
||||
case Expr::Kind::Test: {
|
||||
validate::Value base = eval(expr->operand, ctx);
|
||||
std::vector<validate::Value> args;
|
||||
for (const auto& a : expr->args) args.push_back(eval(a, ctx));
|
||||
auto it = env_->tests().find(expr->name);
|
||||
if (it == env_->tests().end()) {
|
||||
throw TemplateError("unknown test '" + expr->name + "'");
|
||||
}
|
||||
bool result = it->second(base, args);
|
||||
return validate::Value(expr->negated ? !result : result);
|
||||
}
|
||||
case Expr::Kind::List: {
|
||||
validate::Array arr;
|
||||
for (const auto& a : expr->args) arr.push_back(eval(a, ctx));
|
||||
return validate::Value(std::move(arr));
|
||||
}
|
||||
case Expr::Kind::Dict: {
|
||||
validate::Object obj;
|
||||
for (const auto& kv : expr->pairs) {
|
||||
validate::Value k = eval(kv.first, ctx);
|
||||
obj[value_to_text(k)] = eval(kv.second, ctx);
|
||||
}
|
||||
return validate::Value(std::move(obj));
|
||||
}
|
||||
}
|
||||
return validate::Value::undefined();
|
||||
}
|
||||
|
||||
private:
|
||||
void write(std::string_view s) {
|
||||
if (output_.size() + s.size() > caps::kMaxRenderOutput) {
|
||||
throw TemplateError("render output exceeds size cap");
|
||||
}
|
||||
output_.append(s.data(), s.size());
|
||||
}
|
||||
|
||||
void write_value(const validate::Value& v, bool autoescape) {
|
||||
if (v.is_undefined()) {
|
||||
if (env_->undefined_policy() == UndefinedPolicy::Strict) {
|
||||
throw UndefinedError("undefined variable rendered");
|
||||
}
|
||||
++env_->stats().undefined_hits;
|
||||
return;
|
||||
}
|
||||
if (v.is_safe()) {
|
||||
write(v.as_text());
|
||||
return;
|
||||
}
|
||||
if (v.is_string()) {
|
||||
if (autoescape) {
|
||||
write(http_msg::escape_html(v.as_text()));
|
||||
} else {
|
||||
write(v.as_text());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (v.is_array() || v.is_object()) {
|
||||
std::string text = validate::to_json(v);
|
||||
if (autoescape) {
|
||||
write(http_msg::escape_html(text));
|
||||
} else {
|
||||
write(text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
write(value_to_text(v));
|
||||
}
|
||||
|
||||
void collect_blocks(const std::vector<NodePtr>& nodes,
|
||||
std::map<std::string, std::vector<NodePtr>>& blocks) {
|
||||
for (const NodePtr& node : nodes) {
|
||||
if (node->kind == Node::Kind::Block) {
|
||||
// First definition wins at each level; nested blocks inside bodies
|
||||
// are collected too so deep overrides resolve.
|
||||
if (!blocks.count(node->text)) blocks[node->text] = node->body;
|
||||
collect_blocks(node->body, blocks);
|
||||
} else if (node->kind == Node::Kind::If) {
|
||||
for (const auto& b : node->branches) collect_blocks(b.body, blocks);
|
||||
} else if (node->kind == Node::Kind::For) {
|
||||
collect_blocks(node->body, blocks);
|
||||
collect_blocks(node->else_body, blocks);
|
||||
} else if (node->kind == Node::Kind::Autoescape) {
|
||||
collect_blocks(node->body, blocks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Node* find_extends(const std::vector<NodePtr>& nodes) {
|
||||
for (const NodePtr& node : nodes) {
|
||||
if (node->kind == Node::Kind::Extends) return node.get();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void render_with_inheritance(std::shared_ptr<CompiledTemplate> compiled, Context& ctx,
|
||||
const std::map<std::string, std::vector<NodePtr>>& overrides,
|
||||
std::size_t chain) {
|
||||
if (chain > caps::kMaxExtendsChain) {
|
||||
throw TemplateError("template extends chain exceeds cap");
|
||||
}
|
||||
const Node* ext = find_extends(compiled->nodes);
|
||||
if (ext == nullptr) {
|
||||
// Render macro definitions first so they exist before use.
|
||||
for (const NodePtr& node : compiled->nodes) {
|
||||
if (node->kind == Node::Kind::Macro) define_macro(node, ctx);
|
||||
}
|
||||
render_nodes(compiled->nodes, ctx, compiled->autoescape, overrides);
|
||||
return;
|
||||
}
|
||||
std::map<std::string, std::vector<NodePtr>> blocks = overrides;
|
||||
std::map<std::string, std::vector<NodePtr>> child_blocks;
|
||||
collect_blocks(compiled->nodes, child_blocks);
|
||||
for (const auto& kv : child_blocks) blocks[kv.first] = kv.second;
|
||||
for (const NodePtr& node : compiled->nodes) {
|
||||
if (node->kind == Node::Kind::Macro) define_macro(node, ctx);
|
||||
}
|
||||
validate::Value parent_name = eval(ext->expr, ctx);
|
||||
if (parent_name.is_undefined() || parent_name.is_null()) {
|
||||
throw TemplateError("extends needs a template name");
|
||||
}
|
||||
std::shared_ptr<CompiledTemplate> parent = env_->get_compiled(value_to_text(parent_name));
|
||||
render_with_inheritance(parent, ctx, blocks, chain + 1);
|
||||
}
|
||||
|
||||
void define_macro(const NodePtr& node, Context& ctx) {
|
||||
auto macro = std::make_shared<MacroDef>();
|
||||
macro->name = node->text;
|
||||
macro->params = node->params;
|
||||
macro->defaults = node->defaults;
|
||||
macro->body = node->body;
|
||||
ctx.define_macro(macro);
|
||||
}
|
||||
|
||||
void render_node(const NodePtr& node, Context& ctx, bool autoescape,
|
||||
const std::map<std::string, std::vector<NodePtr>>& overrides) {
|
||||
switch (node->kind) {
|
||||
case Node::Kind::Text:
|
||||
write(node->text);
|
||||
return;
|
||||
case Node::Kind::Output:
|
||||
write_value(eval(node->expr, ctx), autoescape);
|
||||
return;
|
||||
case Node::Kind::Extends:
|
||||
return; // Handled by render_with_inheritance.
|
||||
case Node::Kind::Macro:
|
||||
define_macro(node, ctx);
|
||||
return;
|
||||
case Node::Kind::Set:
|
||||
ctx.set(node->text, eval(node->expr, ctx));
|
||||
return;
|
||||
case Node::Kind::Autoescape:
|
||||
render_nodes(node->body, ctx, node->flag, overrides);
|
||||
return;
|
||||
case Node::Kind::Block: {
|
||||
auto it = overrides.find(node->text);
|
||||
if (it != overrides.end()) {
|
||||
render_nodes(it->second, ctx, autoescape, overrides);
|
||||
} else {
|
||||
render_nodes(node->body, ctx, autoescape, overrides);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case Node::Kind::Include: {
|
||||
if (include_depth_ >= caps::kMaxIncludeDepth) {
|
||||
throw TemplateError("template include depth exceeds cap");
|
||||
}
|
||||
validate::Value name = eval(node->expr, ctx);
|
||||
if (name.is_undefined() || name.is_null()) {
|
||||
throw TemplateError("include needs a template name");
|
||||
}
|
||||
std::shared_ptr<CompiledTemplate> compiled =
|
||||
env_->get_compiled(value_to_text(name));
|
||||
++include_depth_;
|
||||
ctx.push();
|
||||
render_nodes(compiled->nodes, ctx, compiled->autoescape, overrides);
|
||||
ctx.pop();
|
||||
--include_depth_;
|
||||
return;
|
||||
}
|
||||
case Node::Kind::If: {
|
||||
for (const IfBranch& branch : node->branches) {
|
||||
if (!branch.cond || eval(branch.cond, ctx).truthy()) {
|
||||
render_nodes(branch.body, ctx, autoescape, overrides);
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case Node::Kind::For:
|
||||
render_for(node, ctx, autoescape, overrides);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void render_for(const NodePtr& node, Context& ctx, bool autoescape,
|
||||
const std::map<std::string, std::vector<NodePtr>>& overrides) {
|
||||
validate::Value seq = eval(node->seq, ctx);
|
||||
if (seq.is_undefined() || seq.is_null()) {
|
||||
if (seq.is_undefined() && env_->undefined_policy() == UndefinedPolicy::Strict) {
|
||||
throw UndefinedError("for loop over undefined");
|
||||
}
|
||||
render_nodes(node->else_body, ctx, autoescape, overrides);
|
||||
return;
|
||||
}
|
||||
// Normalize to rows of (key, value); single target binds value (or key
|
||||
// for mappings, char for strings).
|
||||
std::vector<std::pair<validate::Value, validate::Value>> rows;
|
||||
if (const auto* arr = std::get_if<validate::Array>(&seq.storage())) {
|
||||
for (const auto& item : *arr) rows.emplace_back(validate::Value::null(), item);
|
||||
} else if (const auto* obj = std::get_if<validate::Object>(&seq.storage())) {
|
||||
for (const auto& kv : *obj) {
|
||||
rows.emplace_back(validate::Value(kv.first), kv.second);
|
||||
}
|
||||
} else if (seq.is_string() || seq.is_safe()) {
|
||||
for (char c : seq.as_text()) {
|
||||
rows.emplace_back(validate::Value::null(), validate::Value(std::string(1, c)));
|
||||
}
|
||||
} else {
|
||||
throw TemplateError("for loop needs a sequence or mapping");
|
||||
}
|
||||
if (rows.empty()) {
|
||||
render_nodes(node->else_body, ctx, autoescape, overrides);
|
||||
return;
|
||||
}
|
||||
long long length = (long long)rows.size();
|
||||
for (long long i = 0; i < length; ++i) {
|
||||
++loop_iterations_;
|
||||
if (loop_iterations_ > caps::kMaxLoopIterations) {
|
||||
throw TemplateError("loop iteration cap exceeded");
|
||||
}
|
||||
ctx.push();
|
||||
if (node->targets.size() == 1) {
|
||||
bool is_map = seq.is_object();
|
||||
ctx.set(node->targets[0], is_map ? rows[(std::size_t)i].first
|
||||
: rows[(std::size_t)i].second);
|
||||
} else {
|
||||
if (seq.is_object()) {
|
||||
ctx.set(node->targets[0], rows[(std::size_t)i].first);
|
||||
ctx.set(node->targets[1], rows[(std::size_t)i].second);
|
||||
} else {
|
||||
const validate::Value& item = rows[(std::size_t)i].second;
|
||||
const auto* pair = std::get_if<validate::Array>(&item.storage());
|
||||
if (pair == nullptr || pair->size() != 2) {
|
||||
ctx.pop();
|
||||
throw TemplateError("cannot unpack loop item into two targets");
|
||||
}
|
||||
ctx.set(node->targets[0], (*pair)[0]);
|
||||
ctx.set(node->targets[1], (*pair)[1]);
|
||||
}
|
||||
}
|
||||
validate::Object loop;
|
||||
loop["index"] = validate::Value(i + 1);
|
||||
loop["index0"] = validate::Value(i);
|
||||
loop["first"] = validate::Value(i == 0);
|
||||
loop["last"] = validate::Value(i == length - 1);
|
||||
loop["length"] = validate::Value(length);
|
||||
loop["revindex"] = validate::Value(length - i);
|
||||
loop["revindex0"] = validate::Value(length - i - 1);
|
||||
ctx.set("loop", validate::Value(std::move(loop)));
|
||||
render_nodes(node->body, ctx, autoescape, overrides);
|
||||
ctx.pop();
|
||||
}
|
||||
}
|
||||
|
||||
validate::Value eval_attr(const ExprPtr& expr, Context& ctx) {
|
||||
validate::Value base = eval(expr->operand, ctx);
|
||||
if (base.is_undefined() || base.is_null()) return validate::Value::undefined();
|
||||
if (const auto* obj = std::get_if<validate::Object>(&base.storage())) {
|
||||
auto it = obj->find(expr->name);
|
||||
if (it == obj->end()) return validate::Value::undefined();
|
||||
return it->second;
|
||||
}
|
||||
return validate::Value::undefined();
|
||||
}
|
||||
|
||||
validate::Value eval_index(const ExprPtr& expr, Context& ctx) {
|
||||
validate::Value base = eval(expr->operand, ctx);
|
||||
validate::Value idx = eval(expr->right, ctx);
|
||||
if (base.is_undefined() || base.is_null()) return validate::Value::undefined();
|
||||
if (const auto* arr = std::get_if<validate::Array>(&base.storage())) {
|
||||
if (!idx.is_int()) throw TemplateError("sequence index must be int");
|
||||
long long i = *std::get_if<long long>(&idx.storage());
|
||||
long long n = (long long)arr->size();
|
||||
if (i < 0) i += n;
|
||||
if (i < 0 || i >= n) return validate::Value::undefined();
|
||||
return (*arr)[(std::size_t)i];
|
||||
}
|
||||
if (const auto* obj = std::get_if<validate::Object>(&base.storage())) {
|
||||
if (!idx.is_string() && !idx.is_safe()) {
|
||||
throw TemplateError("mapping index must be string");
|
||||
}
|
||||
auto it = obj->find(idx.as_text());
|
||||
if (it == obj->end()) return validate::Value::undefined();
|
||||
return it->second;
|
||||
}
|
||||
if (base.is_string() || base.is_safe()) {
|
||||
if (!idx.is_int()) throw TemplateError("string index must be int");
|
||||
const std::string& s = base.as_text();
|
||||
long long i = *std::get_if<long long>(&idx.storage());
|
||||
long long n = (long long)s.size();
|
||||
if (i < 0) i += n;
|
||||
if (i < 0 || i >= n) return validate::Value::undefined();
|
||||
return validate::Value(s.substr((std::size_t)i, 1));
|
||||
}
|
||||
return validate::Value::undefined();
|
||||
}
|
||||
|
||||
validate::Value eval_call(const ExprPtr& expr, Context& ctx) {
|
||||
std::string callee;
|
||||
if (expr->operand->kind == Expr::Kind::Name) callee = expr->operand->name;
|
||||
std::shared_ptr<MacroDef> macro =
|
||||
callee.empty() ? nullptr : ctx.lookup_macro(callee);
|
||||
if (macro) {
|
||||
if (expr->args.size() > macro->params.size()) {
|
||||
throw TemplateError("too many args for macro '" + callee + "'");
|
||||
}
|
||||
std::vector<validate::Value> bound(macro->params.size(), validate::Value::undefined());
|
||||
for (std::size_t i = 0; i < expr->args.size(); ++i) bound[i] = eval(expr->args[i], ctx);
|
||||
for (const auto& kw : expr->kwargs) {
|
||||
bool found = false;
|
||||
for (std::size_t i = 0; i < macro->params.size(); ++i) {
|
||||
if (macro->params[i] == kw.first) {
|
||||
bound[i] = eval(kw.second, ctx);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) throw TemplateError("unknown macro kwarg '" + kw.first + "'");
|
||||
}
|
||||
for (std::size_t i = 0; i < macro->params.size(); ++i) {
|
||||
if (bound[i].is_undefined()) {
|
||||
if (i < macro->defaults.size() && macro->defaults[i].has_value()) {
|
||||
bound[i] = *macro->defaults[i];
|
||||
} else {
|
||||
throw TemplateError("macro '" + callee + "' missing arg '" + macro->params[i] + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
Context inner(env_->globals());
|
||||
for (const auto& scope : ctx.scopes()) {
|
||||
for (const auto& kv : scope.macros) {
|
||||
if (inner.lookup_macro(kv.first) == nullptr) inner.define_macro(kv.second);
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < macro->params.size(); ++i) {
|
||||
inner.set(macro->params[i], bound[i]);
|
||||
}
|
||||
std::string saved = std::move(output_);
|
||||
output_.clear();
|
||||
std::map<std::string, std::vector<NodePtr>> no_overrides;
|
||||
render_nodes(macro->body, inner, false, no_overrides);
|
||||
std::string result = std::move(output_);
|
||||
output_ = std::move(saved);
|
||||
return validate::Value::safe(result);
|
||||
}
|
||||
validate::Value base =
|
||||
callee.empty() ? eval(expr->operand, ctx) : ctx.lookup(callee);
|
||||
if (base.is_undefined()) {
|
||||
if (env_->undefined_policy() == UndefinedPolicy::Strict) {
|
||||
throw UndefinedError("call of undefined '" + callee + "'");
|
||||
}
|
||||
++env_->stats().undefined_hits;
|
||||
return validate::Value::undefined();
|
||||
}
|
||||
throw TemplateError("value is not callable");
|
||||
}
|
||||
|
||||
validate::Value eval_unary(const ExprPtr& expr, Context& ctx) {
|
||||
validate::Value v = eval(expr->operand, ctx);
|
||||
if (expr->op == "+") {
|
||||
if (!v.is_number()) throw TemplateError("unary plus needs a number");
|
||||
return v;
|
||||
}
|
||||
if (const auto* i = std::get_if<long long>(&v.storage())) return validate::Value(-*i);
|
||||
if (const auto* d = std::get_if<double>(&v.storage())) return validate::Value(-*d);
|
||||
throw TemplateError("unary minus needs a number");
|
||||
}
|
||||
|
||||
validate::Value eval_binary(const ExprPtr& expr, Context& ctx) {
|
||||
if (expr->op == "~") {
|
||||
return validate::Value(value_to_text(eval(expr->left, ctx)) +
|
||||
value_to_text(eval(expr->right, ctx)));
|
||||
}
|
||||
validate::Value a = eval(expr->left, ctx);
|
||||
validate::Value b = eval(expr->right, ctx);
|
||||
const std::string& op = expr->op;
|
||||
if (op == "+") {
|
||||
if (a.is_number() && b.is_number()) {
|
||||
if (a.is_float() || b.is_float()) return validate::Value(a.as_number() + b.as_number());
|
||||
return validate::Value(*std::get_if<long long>(&a.storage()) +
|
||||
*std::get_if<long long>(&b.storage()));
|
||||
}
|
||||
if ((a.is_string() || a.is_safe()) && (b.is_string() || b.is_safe())) {
|
||||
return validate::Value(a.as_text() + b.as_text());
|
||||
}
|
||||
if (a.is_array() && b.is_array()) {
|
||||
validate::Array out = *std::get_if<validate::Array>(&a.storage());
|
||||
const auto* tail = std::get_if<validate::Array>(&b.storage());
|
||||
for (const auto& item : *tail) out.push_back(item);
|
||||
return validate::Value(std::move(out));
|
||||
}
|
||||
throw TemplateError("unsupported operands for +");
|
||||
}
|
||||
if (op == "*") {
|
||||
if (a.is_number() && b.is_number()) {
|
||||
if (a.is_float() || b.is_float()) return validate::Value(a.as_number() * b.as_number());
|
||||
return validate::Value(*std::get_if<long long>(&a.storage()) *
|
||||
*std::get_if<long long>(&b.storage()));
|
||||
}
|
||||
if ((a.is_string() || a.is_safe()) && b.is_int()) {
|
||||
std::string out;
|
||||
long long n = *std::get_if<long long>(&b.storage());
|
||||
if (n < 0 || n > 100000) throw TemplateError("string repeat out of range");
|
||||
for (long long i = 0; i < n; ++i) out += a.as_text();
|
||||
return validate::Value(out);
|
||||
}
|
||||
throw TemplateError("unsupported operands for *");
|
||||
}
|
||||
if (!a.is_number() || !b.is_number()) throw TemplateError("arithmetic needs numbers");
|
||||
double x = a.as_number();
|
||||
double y = b.as_number();
|
||||
bool both_int = a.is_int() && b.is_int();
|
||||
if (op == "-") {
|
||||
if (both_int) {
|
||||
return validate::Value(*std::get_if<long long>(&a.storage()) -
|
||||
*std::get_if<long long>(&b.storage()));
|
||||
}
|
||||
return validate::Value(x - y);
|
||||
}
|
||||
if (op == "/") {
|
||||
if (y == 0.0) throw TemplateError("division by zero");
|
||||
return validate::Value(x / y);
|
||||
}
|
||||
if (op == "//") {
|
||||
if (y == 0.0) throw TemplateError("division by zero");
|
||||
return validate::Value((long long)std::floor(x / y));
|
||||
}
|
||||
if (op == "%") {
|
||||
if (both_int) {
|
||||
long long d = *std::get_if<long long>(&b.storage());
|
||||
if (d == 0) throw TemplateError("division by zero");
|
||||
return validate::Value(*std::get_if<long long>(&a.storage()) % d);
|
||||
}
|
||||
if (y == 0.0) throw TemplateError("division by zero");
|
||||
return validate::Value(std::fmod(x, y));
|
||||
}
|
||||
throw TemplateError("unknown operator '" + op + "'");
|
||||
}
|
||||
|
||||
static bool values_equal(const validate::Value& a, const validate::Value& b) {
|
||||
if (a.is_number() && b.is_number()) return a.as_number() == b.as_number();
|
||||
if ((a.is_string() || a.is_safe()) && (b.is_string() || b.is_safe())) {
|
||||
return a.as_text() == b.as_text();
|
||||
}
|
||||
return a == b;
|
||||
}
|
||||
|
||||
validate::Value eval_compare(const ExprPtr& expr, Context& ctx) {
|
||||
validate::Value a = eval(expr->left, ctx);
|
||||
validate::Value b = eval(expr->right, ctx);
|
||||
const std::string& op = expr->op;
|
||||
if (op == "==") return validate::Value(values_equal(a, b));
|
||||
if (op == "!=") return validate::Value(!values_equal(a, b));
|
||||
if (a.is_number() && b.is_number()) {
|
||||
double x = a.as_number();
|
||||
double y = b.as_number();
|
||||
if (op == "<") return validate::Value(x < y);
|
||||
if (op == ">") return validate::Value(x > y);
|
||||
if (op == "<=") return validate::Value(x <= y);
|
||||
return validate::Value(x >= y);
|
||||
}
|
||||
if ((a.is_string() || a.is_safe()) && (b.is_string() || b.is_safe())) {
|
||||
const std::string& x = a.as_text();
|
||||
const std::string& y = b.as_text();
|
||||
if (op == "<") return validate::Value(x < y);
|
||||
if (op == ">") return validate::Value(x > y);
|
||||
if (op == "<=") return validate::Value(x <= y);
|
||||
return validate::Value(x >= y);
|
||||
}
|
||||
throw TemplateError("cannot compare these values");
|
||||
}
|
||||
|
||||
validate::Value eval_in(const ExprPtr& expr, Context& ctx) {
|
||||
validate::Value left = eval(expr->left, ctx);
|
||||
validate::Value seq = eval(expr->seq, ctx);
|
||||
if (seq.is_undefined() || seq.is_null()) {
|
||||
if (seq.is_undefined() && env_->undefined_policy() == UndefinedPolicy::Strict) {
|
||||
throw UndefinedError("'in' over undefined");
|
||||
}
|
||||
return validate::Value(expr->negated);
|
||||
}
|
||||
bool found = false;
|
||||
if ((seq.is_string() || seq.is_safe()) && (left.is_string() || left.is_safe())) {
|
||||
found = seq.as_text().find(left.as_text()) != std::string::npos;
|
||||
} else if (const auto* arr = std::get_if<validate::Array>(&seq.storage())) {
|
||||
for (const auto& item : *arr) {
|
||||
if (values_equal(item, left)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (const auto* obj = std::get_if<validate::Object>(&seq.storage())) {
|
||||
if (left.is_string() || left.is_safe()) found = obj->count(left.as_text()) > 0;
|
||||
} else {
|
||||
throw TemplateError("'in' needs a string, sequence or mapping");
|
||||
}
|
||||
return validate::Value(expr->negated ? !found : found);
|
||||
}
|
||||
|
||||
Environment* env_;
|
||||
std::string output_;
|
||||
std::size_t include_depth_ = 0;
|
||||
std::size_t loop_iterations_ = 0;
|
||||
};
|
||||
|
||||
inline std::string Environment::render(const std::string& name, validate::Object context) {
|
||||
Renderer renderer(this);
|
||||
return renderer.render_template(name, std::move(context));
|
||||
}
|
||||
|
||||
inline std::string Environment::render_source(const std::string& source, const std::string& name,
|
||||
validate::Object context) {
|
||||
Renderer renderer(this);
|
||||
return renderer.render_nodes_source(source, name, std::move(context));
|
||||
}
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::templates::TemplateResponse. Response subclass rendering
|
||||
// a named template with a context through an Environment (plan 05, E11).
|
||||
// Renders eagerly; TemplateError propagates and maps to 500 upstream.
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "../http_msg/response.h"
|
||||
#include "../validate/value.h"
|
||||
#include "environment.h"
|
||||
|
||||
namespace molo::app::templates {
|
||||
|
||||
class TemplateResponse : public http_msg::Response {
|
||||
public:
|
||||
explicit TemplateResponse(Environment& env, std::string name, validate::Object context = {},
|
||||
int status = 200,
|
||||
std::string content_type = "text/html; charset=utf-8")
|
||||
: Response(status, env.render(name, std::move(context)), std::move(content_type)) {}
|
||||
};
|
||||
|
||||
} // namespace molo::app::templates
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::validate::ValidationError. Raised when data cannot be
|
||||
// parsed into a Model. Lists ALL field failures (plan 05, R3), never
|
||||
// fail-fast. JSON shape: {"detail":[{"loc":[...],"msg":"...","type":"..."}]}
|
||||
// with status 422.
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "json.h"
|
||||
#include "value.h"
|
||||
|
||||
namespace molo::app::validate {
|
||||
|
||||
struct FieldFailure {
|
||||
std::vector<std::string> loc;
|
||||
std::string msg;
|
||||
std::string type;
|
||||
};
|
||||
|
||||
class ValidationError : public std::runtime_error {
|
||||
public:
|
||||
explicit ValidationError(std::vector<FieldFailure> failures)
|
||||
: std::runtime_error("validation failed"), failures_(std::move(failures)) {}
|
||||
|
||||
const std::vector<FieldFailure>& failures() const { return failures_; }
|
||||
|
||||
Value to_value() const {
|
||||
Array detail;
|
||||
for (const auto& f : failures_) {
|
||||
Object item;
|
||||
Array loc;
|
||||
for (const auto& part : f.loc) loc.emplace_back(part);
|
||||
item["loc"] = Value(std::move(loc));
|
||||
item["msg"] = Value(f.msg);
|
||||
item["type"] = Value(f.type);
|
||||
detail.emplace_back(std::move(item));
|
||||
}
|
||||
Object root;
|
||||
root["detail"] = Value(std::move(detail));
|
||||
return Value(std::move(root));
|
||||
}
|
||||
|
||||
std::string to_json_string() const { return to_json(to_value()); }
|
||||
|
||||
private:
|
||||
std::vector<FieldFailure> failures_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::validate
|
||||
@@ -0,0 +1,271 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::validate::Field. One declared field: type, constraints,
|
||||
// default, required, nullable (plan 05, section 6 Validation).
|
||||
// Coercion table (Q1 answer, strict booleans, empty string never null):
|
||||
// - string source: int needs ^[+-]?[0-9]+$ after trim; float needs a full
|
||||
// number after trim; bool accepts true/false/1/0 case-insensitive after
|
||||
// trim; string is as-is (no trim).
|
||||
// - int source: to float ok; to string decimal; to bool rejected.
|
||||
// - float source: to int only when integral; to string shortest form.
|
||||
// - bool source: to int/float 1/0; to string "true"/"false".
|
||||
// - null source: ok only when nullable, else type error.
|
||||
// - path params use the same strict table; query/form identical (lenient
|
||||
// part is trim-before-parse only, documented here).
|
||||
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "errors.h"
|
||||
#include "value.h"
|
||||
|
||||
namespace molo::app::validate {
|
||||
|
||||
enum class FieldType { Any, Int, Float, Bool, String, List, Dict };
|
||||
|
||||
inline std::string trim_copy(const std::string& s) {
|
||||
std::size_t a = 0;
|
||||
while (a < s.size() && std::isspace((unsigned char)s[a])) ++a;
|
||||
std::size_t b = s.size();
|
||||
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
|
||||
return s.substr(a, b - a);
|
||||
}
|
||||
|
||||
struct Constraints {
|
||||
std::optional<double> min_value;
|
||||
std::optional<double> max_value;
|
||||
std::optional<double> gt;
|
||||
std::optional<double> ge;
|
||||
std::optional<double> lt;
|
||||
std::optional<double> le;
|
||||
std::optional<std::size_t> min_len;
|
||||
std::optional<std::size_t> max_len;
|
||||
std::optional<std::string> pattern;
|
||||
std::vector<Value> choices;
|
||||
};
|
||||
|
||||
class Field {
|
||||
public:
|
||||
Field() = default;
|
||||
Field(std::string name, FieldType type) : name_(std::move(name)), type_(type) {}
|
||||
|
||||
const std::string& name() const { return name_; }
|
||||
FieldType type() const { return type_; }
|
||||
Constraints& constraints() { return constraints_; }
|
||||
const Constraints& constraints() const { return constraints_; }
|
||||
|
||||
Field& required(bool r = true) {
|
||||
required_ = r;
|
||||
return *this;
|
||||
}
|
||||
Field& nullable(bool n = true) {
|
||||
nullable_ = n;
|
||||
return *this;
|
||||
}
|
||||
Field& with_default(Value v) {
|
||||
default_ = std::move(v);
|
||||
has_default_ = true;
|
||||
return *this;
|
||||
}
|
||||
bool required() const { return required_; }
|
||||
bool nullable() const { return nullable_; }
|
||||
bool has_default() const { return has_default_; }
|
||||
const Value& default_value() const { return default_; }
|
||||
|
||||
Field& min_value(double v) { constraints_.min_value = v; return *this; }
|
||||
Field& max_value(double v) { constraints_.max_value = v; return *this; }
|
||||
Field& gt(double v) { constraints_.gt = v; return *this; }
|
||||
Field& ge(double v) { constraints_.ge = v; return *this; }
|
||||
Field& lt(double v) { constraints_.lt = v; return *this; }
|
||||
Field& le(double v) { constraints_.le = v; return *this; }
|
||||
Field& min_len(std::size_t v) { constraints_.min_len = v; return *this; }
|
||||
Field& max_len(std::size_t v) { constraints_.max_len = v; return *this; }
|
||||
Field& pattern(std::string p) { constraints_.pattern = std::move(p); return *this; }
|
||||
Field& choices(std::vector<Value> c) { constraints_.choices = std::move(c); return *this; }
|
||||
|
||||
// Coerce and check one value. Throws FieldFailure-as-ValidationError with
|
||||
// a single entry; Model::validate aggregates across fields (R3).
|
||||
Value parse(const Value& input, const std::vector<std::string>& loc) const {
|
||||
if (input.is_undefined() || input.is_null()) {
|
||||
if (input.is_null() && nullable_) return Value::null();
|
||||
if (has_default_) return default_;
|
||||
if (required_) {
|
||||
throw ValidationError({{loc, "field required", "missing"}});
|
||||
}
|
||||
return Value::null();
|
||||
}
|
||||
Value coerced = coerce(input, loc);
|
||||
check_constraints(coerced, loc);
|
||||
return coerced;
|
||||
}
|
||||
|
||||
private:
|
||||
Value coerce(const Value& input, const std::vector<std::string>& loc) const {
|
||||
switch (type_) {
|
||||
case FieldType::Any:
|
||||
return input;
|
||||
case FieldType::String:
|
||||
return coerce_string(input, loc);
|
||||
case FieldType::Int:
|
||||
return coerce_int(input, loc);
|
||||
case FieldType::Float:
|
||||
return coerce_float(input, loc);
|
||||
case FieldType::Bool:
|
||||
return coerce_bool(input, loc);
|
||||
case FieldType::List:
|
||||
if (!input.is_array()) fail(loc, "expected array", "type_error");
|
||||
return input;
|
||||
case FieldType::Dict:
|
||||
if (!input.is_object()) fail(loc, "expected object", "type_error");
|
||||
return input;
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
[[noreturn]] static void fail(const std::vector<std::string>& loc, const std::string& msg,
|
||||
const std::string& type) {
|
||||
throw ValidationError({{loc, msg, type}});
|
||||
}
|
||||
|
||||
Value coerce_string(const Value& input, const std::vector<std::string>& loc) const {
|
||||
if (input.is_string() || input.is_safe()) return Value(input.as_text());
|
||||
if (const auto* i = std::get_if<long long>(&input.storage())) {
|
||||
return Value(std::to_string(*i));
|
||||
}
|
||||
if (const auto* d = std::get_if<double>(&input.storage())) {
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "%.17g", *d);
|
||||
return Value(std::string(buf));
|
||||
}
|
||||
if (const auto* b = std::get_if<bool>(&input.storage())) {
|
||||
return Value(*b ? "true" : "false");
|
||||
}
|
||||
fail(loc, "expected string", "string_type");
|
||||
}
|
||||
|
||||
static bool full_int(const std::string& t, long long& out) {
|
||||
if (t.empty()) return false;
|
||||
std::size_t i = 0;
|
||||
if (t[0] == '+' || t[0] == '-') i = 1;
|
||||
if (i == t.size()) return false;
|
||||
for (std::size_t j = i; j < t.size(); ++j) {
|
||||
if (!std::isdigit((unsigned char)t[j])) return false;
|
||||
}
|
||||
try {
|
||||
out = std::stoll(t);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool full_float(const std::string& t, double& out) {
|
||||
if (t.empty()) return false;
|
||||
try {
|
||||
std::size_t used = 0;
|
||||
out = std::stod(t, &used);
|
||||
return used == t.size();
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Value coerce_int(const Value& input, const std::vector<std::string>& loc) const {
|
||||
if (const auto* i = std::get_if<long long>(&input.storage())) return Value(*i);
|
||||
if (input.is_bool()) {
|
||||
fail(loc, "bool is not int", "int_type");
|
||||
}
|
||||
if (const auto* d = std::get_if<double>(&input.storage())) {
|
||||
if (std::trunc(*d) != *d) fail(loc, "float is not integral", "int_from_float");
|
||||
return Value((long long)*d);
|
||||
}
|
||||
if (input.is_string()) {
|
||||
long long v = 0;
|
||||
if (full_int(trim_copy(input.as_text()), v)) return Value(v);
|
||||
fail(loc, "invalid integer", "int_parsing");
|
||||
}
|
||||
fail(loc, "expected int", "int_type");
|
||||
}
|
||||
|
||||
Value coerce_float(const Value& input, const std::vector<std::string>& loc) const {
|
||||
if (const auto* d = std::get_if<double>(&input.storage())) return Value(*d);
|
||||
if (const auto* i = std::get_if<long long>(&input.storage())) return Value((double)*i);
|
||||
if (const auto* b = std::get_if<bool>(&input.storage())) return Value(*b ? 1.0 : 0.0);
|
||||
if (input.is_string()) {
|
||||
double v = 0;
|
||||
if (full_float(trim_copy(input.as_text()), v)) return Value(v);
|
||||
fail(loc, "invalid number", "float_parsing");
|
||||
}
|
||||
fail(loc, "expected number", "float_type");
|
||||
}
|
||||
|
||||
Value coerce_bool(const Value& input, const std::vector<std::string>& loc) const {
|
||||
if (const auto* b = std::get_if<bool>(&input.storage())) return Value(*b);
|
||||
if (input.is_string()) {
|
||||
std::string t = trim_copy(input.as_text());
|
||||
std::string low;
|
||||
for (char c : t) low += (char)std::tolower((unsigned char)c);
|
||||
if (low == "true" || low == "1") return Value(true);
|
||||
if (low == "false" || low == "0") return Value(false);
|
||||
fail(loc, "invalid boolean, use true/false/1/0", "bool_parsing");
|
||||
}
|
||||
fail(loc, "expected bool", "bool_type");
|
||||
}
|
||||
|
||||
void check_constraints(const Value& v, const std::vector<std::string>& loc) const {
|
||||
const Constraints& c = constraints_;
|
||||
if (v.is_number()) {
|
||||
double n = v.as_number();
|
||||
if (c.min_value && n < *c.min_value) fail(loc, "less than minimum", "greater_than_equal");
|
||||
if (c.max_value && n > *c.max_value) fail(loc, "greater than maximum", "less_than_equal");
|
||||
if (c.gt && !(n > *c.gt)) fail(loc, "must be greater than bound", "greater_than");
|
||||
if (c.ge && !(n >= *c.ge)) fail(loc, "must be at least bound", "greater_than_equal");
|
||||
if (c.lt && !(n < *c.lt)) fail(loc, "must be less than bound", "less_than");
|
||||
if (c.le && !(n <= *c.le)) fail(loc, "must be at most bound", "less_than_equal");
|
||||
}
|
||||
std::size_t len = 0;
|
||||
bool has_len = false;
|
||||
if (v.is_string()) {
|
||||
len = v.as_text().size();
|
||||
has_len = true;
|
||||
} else if (const auto* a = std::get_if<Array>(&v.storage())) {
|
||||
len = a->size();
|
||||
has_len = true;
|
||||
} else if (const auto* o = std::get_if<Object>(&v.storage())) {
|
||||
len = o->size();
|
||||
has_len = true;
|
||||
}
|
||||
if (has_len) {
|
||||
if (c.min_len && len < *c.min_len) fail(loc, "too short", "too_short");
|
||||
if (c.max_len && len > *c.max_len) fail(loc, "too long", "too_long");
|
||||
}
|
||||
if (c.pattern && v.is_string()) {
|
||||
std::regex re(*c.pattern);
|
||||
if (!std::regex_match(v.as_text(), re)) fail(loc, "pattern mismatch", "string_pattern");
|
||||
}
|
||||
if (!c.choices.empty()) {
|
||||
bool ok = false;
|
||||
for (const auto& choice : c.choices) {
|
||||
if (choice == v) {
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!ok) fail(loc, "not one of the allowed choices", "literal_error");
|
||||
}
|
||||
}
|
||||
|
||||
std::string name_;
|
||||
FieldType type_ = FieldType::Any;
|
||||
Constraints constraints_;
|
||||
bool required_ = false;
|
||||
bool nullable_ = false;
|
||||
bool has_default_ = false;
|
||||
Value default_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::validate
|
||||
@@ -0,0 +1,298 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::validate JSON codec. Minimal recursive descent parser
|
||||
// and serializer for form binding, error bodies and template tojson.
|
||||
// Depth cap kMaxJsonDepth; document size capped by the caller
|
||||
// (kMaxJsonDocument default, overridable per route down to 0).
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "../caps.h"
|
||||
#include "value.h"
|
||||
|
||||
namespace molo::app::validate {
|
||||
|
||||
class JsonError : public std::runtime_error {
|
||||
public:
|
||||
explicit JsonError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class JsonParser {
|
||||
public:
|
||||
explicit JsonParser(std::string_view text, std::size_t max_depth = caps::kMaxJsonDepth)
|
||||
: text_(text), max_depth_(max_depth) {}
|
||||
|
||||
Value parse() {
|
||||
skip_ws();
|
||||
if (pos_ >= text_.size()) throw JsonError("empty JSON document");
|
||||
Value v = parse_value(0);
|
||||
skip_ws();
|
||||
if (pos_ != text_.size()) throw JsonError("trailing bytes after JSON document");
|
||||
return v;
|
||||
}
|
||||
|
||||
private:
|
||||
void skip_ws() {
|
||||
while (pos_ < text_.size()) {
|
||||
char c = text_[pos_];
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
|
||||
++pos_;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char peek() const {
|
||||
if (pos_ >= text_.size()) throw JsonError("unexpected end of JSON");
|
||||
return text_[pos_];
|
||||
}
|
||||
|
||||
Value parse_value(std::size_t depth) {
|
||||
if (depth > max_depth_) throw JsonError("JSON nesting exceeds depth cap");
|
||||
char c = peek();
|
||||
if (c == '{') return parse_object(depth);
|
||||
if (c == '[') return parse_array(depth);
|
||||
if (c == '"') return Value(parse_string());
|
||||
if (c == 't') return parse_literal("true", Value(true));
|
||||
if (c == 'f') return parse_literal("false", Value(false));
|
||||
if (c == 'n') return parse_literal("null", Value::null());
|
||||
if (c == '-' || (c >= '0' && c <= '9')) return parse_number();
|
||||
throw JsonError(std::string("unexpected character in JSON: ") + c);
|
||||
}
|
||||
|
||||
Value parse_literal(const char* word, Value v) {
|
||||
for (const char* p = word; *p; ++p) {
|
||||
if (pos_ >= text_.size() || text_[pos_] != *p) throw JsonError("bad JSON literal");
|
||||
++pos_;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
Value parse_object(std::size_t depth) {
|
||||
++pos_; // {
|
||||
Object obj;
|
||||
skip_ws();
|
||||
if (peek() == '}') {
|
||||
++pos_;
|
||||
return Value(std::move(obj));
|
||||
}
|
||||
while (true) {
|
||||
skip_ws();
|
||||
if (peek() != '"') throw JsonError("expected string key in JSON object");
|
||||
std::string key = parse_string();
|
||||
skip_ws();
|
||||
if (peek() != ':') throw JsonError("expected colon in JSON object");
|
||||
++pos_;
|
||||
skip_ws();
|
||||
obj[std::move(key)] = parse_value(depth + 1);
|
||||
skip_ws();
|
||||
char c = peek();
|
||||
if (c == ',') {
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
if (c == '}') {
|
||||
++pos_;
|
||||
return Value(std::move(obj));
|
||||
}
|
||||
throw JsonError("expected comma or brace in JSON object");
|
||||
}
|
||||
}
|
||||
|
||||
Value parse_array(std::size_t depth) {
|
||||
++pos_; // [
|
||||
Array arr;
|
||||
skip_ws();
|
||||
if (peek() == ']') {
|
||||
++pos_;
|
||||
return Value(std::move(arr));
|
||||
}
|
||||
while (true) {
|
||||
skip_ws();
|
||||
arr.push_back(parse_value(depth + 1));
|
||||
skip_ws();
|
||||
char c = peek();
|
||||
if (c == ',') {
|
||||
++pos_;
|
||||
continue;
|
||||
}
|
||||
if (c == ']') {
|
||||
++pos_;
|
||||
return Value(std::move(arr));
|
||||
}
|
||||
throw JsonError("expected comma or bracket in JSON array");
|
||||
}
|
||||
}
|
||||
|
||||
std::string parse_string() {
|
||||
++pos_; // opening quote
|
||||
std::string out;
|
||||
while (true) {
|
||||
if (pos_ >= text_.size()) throw JsonError("unterminated JSON string");
|
||||
char c = text_[pos_++];
|
||||
if (c == '"') return out;
|
||||
if (c == '\\') {
|
||||
if (pos_ >= text_.size()) throw JsonError("bad JSON escape");
|
||||
char e = text_[pos_++];
|
||||
switch (e) {
|
||||
case '"': out += '"'; break;
|
||||
case '\\': out += '\\'; break;
|
||||
case '/': out += '/'; break;
|
||||
case 'b': out += '\b'; break;
|
||||
case 'f': out += '\f'; break;
|
||||
case 'n': out += '\n'; break;
|
||||
case 'r': out += '\r'; break;
|
||||
case 't': out += '\t'; break;
|
||||
case 'u': {
|
||||
if (pos_ + 4 > text_.size()) throw JsonError("bad unicode escape");
|
||||
unsigned code = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
char h = text_[pos_++];
|
||||
code <<= 4;
|
||||
if (h >= '0' && h <= '9') code |= (unsigned)(h - '0');
|
||||
else if (h >= 'a' && h <= 'f') code |= (unsigned)(h - 'a' + 10);
|
||||
else if (h >= 'A' && h <= 'F') code |= (unsigned)(h - 'A' + 10);
|
||||
else throw JsonError("bad unicode escape");
|
||||
}
|
||||
if (code < 0x80) {
|
||||
out += (char)code;
|
||||
} else if (code < 0x800) {
|
||||
out += (char)(0xC0 | (code >> 6));
|
||||
out += (char)(0x80 | (code & 0x3F));
|
||||
} else {
|
||||
out += (char)(0xE0 | (code >> 12));
|
||||
out += (char)(0x80 | ((code >> 6) & 0x3F));
|
||||
out += (char)(0x80 | (code & 0x3F));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: throw JsonError("bad JSON escape");
|
||||
}
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Value parse_number() {
|
||||
std::size_t start = pos_;
|
||||
if (peek() == '-') ++pos_;
|
||||
while (pos_ < text_.size() && std::isdigit((unsigned char)text_[pos_])) ++pos_;
|
||||
bool is_float = false;
|
||||
if (pos_ < text_.size() && text_[pos_] == '.') {
|
||||
is_float = true;
|
||||
++pos_;
|
||||
while (pos_ < text_.size() && std::isdigit((unsigned char)text_[pos_])) ++pos_;
|
||||
}
|
||||
if (pos_ < text_.size() && (text_[pos_] == 'e' || text_[pos_] == 'E')) {
|
||||
is_float = true;
|
||||
++pos_;
|
||||
if (pos_ < text_.size() && (text_[pos_] == '+' || text_[pos_] == '-')) ++pos_;
|
||||
while (pos_ < text_.size() && std::isdigit((unsigned char)text_[pos_])) ++pos_;
|
||||
}
|
||||
std::string tok(text_.substr(start, pos_ - start));
|
||||
try {
|
||||
if (is_float) return Value(std::stod(tok));
|
||||
return Value((long long)std::stoll(tok));
|
||||
} catch (...) {
|
||||
throw JsonError("bad JSON number: " + tok);
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view text_;
|
||||
std::size_t pos_ = 0;
|
||||
std::size_t max_depth_;
|
||||
};
|
||||
|
||||
inline Value parse_json(std::string_view text, std::size_t max_depth = caps::kMaxJsonDepth) {
|
||||
JsonParser parser(text, max_depth);
|
||||
return parser.parse();
|
||||
}
|
||||
|
||||
inline void escape_json_string(const std::string& s, std::string& out) {
|
||||
out += '"';
|
||||
for (unsigned char c : s) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char buf[8];
|
||||
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
|
||||
out += buf;
|
||||
} else {
|
||||
out += (char)c;
|
||||
}
|
||||
}
|
||||
}
|
||||
out += '"';
|
||||
}
|
||||
|
||||
inline void write_json_value(const Value& v, std::string& out, std::size_t depth) {
|
||||
if (depth > caps::kMaxJsonDepth) throw JsonError("value exceeds JSON depth cap");
|
||||
if (v.is_null() || v.is_undefined()) {
|
||||
out += "null";
|
||||
return;
|
||||
}
|
||||
if (const auto* b = std::get_if<bool>(&v.storage())) {
|
||||
out += *b ? "true" : "false";
|
||||
return;
|
||||
}
|
||||
if (const auto* i = std::get_if<long long>(&v.storage())) {
|
||||
out += std::to_string(*i);
|
||||
return;
|
||||
}
|
||||
if (const auto* d = std::get_if<double>(&v.storage())) {
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "%.17g", *d);
|
||||
out += buf;
|
||||
return;
|
||||
}
|
||||
if (v.is_string() || v.is_safe()) {
|
||||
escape_json_string(v.as_text(), out);
|
||||
return;
|
||||
}
|
||||
if (const auto* a = std::get_if<Array>(&v.storage())) {
|
||||
out += '[';
|
||||
bool first = true;
|
||||
for (const auto& item : *a) {
|
||||
if (!first) out += ',';
|
||||
first = false;
|
||||
write_json_value(item, out, depth + 1);
|
||||
}
|
||||
out += ']';
|
||||
return;
|
||||
}
|
||||
if (const auto* o = std::get_if<Object>(&v.storage())) {
|
||||
out += '{';
|
||||
bool first = true;
|
||||
for (const auto& kv : *o) {
|
||||
if (!first) out += ',';
|
||||
first = false;
|
||||
escape_json_string(kv.first, out);
|
||||
out += ':';
|
||||
write_json_value(kv.second, out, depth + 1);
|
||||
}
|
||||
out += '}';
|
||||
return;
|
||||
}
|
||||
out += "null";
|
||||
}
|
||||
|
||||
inline std::string to_json(const Value& v) {
|
||||
std::string out;
|
||||
write_json_value(v, out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::app::validate
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::validate::Model. Runtime-declared validation model
|
||||
// (Pydantic-style without reflection): fields are added in code, validate()
|
||||
// coerces an input object into a clean object or throws one ValidationError
|
||||
// listing every failure (plan 05, R2, R3, E4). Feeds path, query, header,
|
||||
// cookie and body binding plus OpenAPI schema generation (08-clients-openapi).
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "errors.h"
|
||||
#include "field.h"
|
||||
#include "value.h"
|
||||
|
||||
namespace molo::app::validate {
|
||||
|
||||
class Model {
|
||||
public:
|
||||
explicit Model(std::string name = "") : name_(std::move(name)) {}
|
||||
|
||||
Model& field(Field f) {
|
||||
fields_.push_back(std::move(f));
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Reject unknown keys when true; default keeps and passes them through.
|
||||
Model& strict(bool s = true) {
|
||||
strict_ = s;
|
||||
return *this;
|
||||
}
|
||||
|
||||
const std::string& name() const { return name_; }
|
||||
const std::vector<Field>& fields() const { return fields_; }
|
||||
|
||||
Object validate(const Object& input, const std::string& source) const {
|
||||
Object out;
|
||||
std::vector<FieldFailure> failures;
|
||||
for (const Field& f : fields_) {
|
||||
std::vector<std::string> loc{source, f.name()};
|
||||
auto it = input.find(f.name());
|
||||
Value raw = (it == input.end()) ? Value::null() : it->second;
|
||||
bool missing = (it == input.end());
|
||||
try {
|
||||
if (missing && !f.required() && !f.has_default()) {
|
||||
continue;
|
||||
}
|
||||
out[f.name()] = f.parse(raw, loc);
|
||||
} catch (const ValidationError& e) {
|
||||
for (const auto& item : e.failures()) failures.push_back(item);
|
||||
}
|
||||
}
|
||||
if (strict_) {
|
||||
for (const auto& kv : input) {
|
||||
bool known = false;
|
||||
for (const Field& f : fields_) {
|
||||
if (f.name() == kv.first) {
|
||||
known = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!known) {
|
||||
failures.push_back({{source, kv.first}, "unknown field", "extra_forbidden"});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const auto& kv : input) {
|
||||
bool known = false;
|
||||
for (const Field& f : fields_) {
|
||||
if (f.name() == kv.first) {
|
||||
known = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!known) out[kv.first] = kv.second;
|
||||
}
|
||||
}
|
||||
if (!failures.empty()) throw ValidationError(std::move(failures));
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
std::vector<Field> fields_;
|
||||
bool strict_ = false;
|
||||
};
|
||||
|
||||
} // namespace molo::app::validate
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::validate::Value. Single dynamic value type shared by
|
||||
// validation, forms, negotiation variants and template contexts (DRY: one
|
||||
// model, plan 05 section 9). JSON-compatible plus SafeString (template
|
||||
// markup exempt from escaping) and Undefined (missing template variable).
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::app::validate {
|
||||
|
||||
struct Null {
|
||||
bool operator==(const Null&) const = default;
|
||||
};
|
||||
struct Undefined {
|
||||
bool operator==(const Undefined&) const = default;
|
||||
};
|
||||
struct SafeString {
|
||||
std::string text;
|
||||
bool operator==(const SafeString&) const = default;
|
||||
};
|
||||
|
||||
class Value;
|
||||
using Array = std::vector<Value>;
|
||||
using Object = std::map<std::string, Value>;
|
||||
|
||||
class Value {
|
||||
public:
|
||||
using Storage = std::variant<Null, Undefined, bool, long long, double, std::string,
|
||||
SafeString, Array, Object>;
|
||||
|
||||
Value() : data_(Null{}) {}
|
||||
Value(Null v) : data_(v) {}
|
||||
Value(Undefined v) : data_(v) {}
|
||||
Value(bool v) : data_(v) {}
|
||||
Value(int v) : data_((long long)v) {}
|
||||
Value(long v) : data_((long long)v) {}
|
||||
Value(long long v) : data_(v) {}
|
||||
Value(unsigned v) : data_((long long)v) {}
|
||||
Value(unsigned long v) : data_((long long)v) {}
|
||||
Value(double v) : data_(v) {}
|
||||
Value(const char* v) : data_(std::string(v)) {}
|
||||
Value(std::string v) : data_(std::move(v)) {}
|
||||
Value(SafeString v) : data_(std::move(v)) {}
|
||||
Value(Array v) : data_(std::move(v)) {}
|
||||
Value(Object v) : data_(std::move(v)) {}
|
||||
|
||||
static Value null() { return Value(Null{}); }
|
||||
static Value undefined() { return Value(Undefined{}); }
|
||||
static Value safe(std::string s) { return Value(SafeString{std::move(s)}); }
|
||||
|
||||
bool is_null() const { return std::holds_alternative<Null>(data_); }
|
||||
bool is_undefined() const { return std::holds_alternative<Undefined>(data_); }
|
||||
bool is_bool() const { return std::holds_alternative<bool>(data_); }
|
||||
bool is_int() const { return std::holds_alternative<long long>(data_); }
|
||||
bool is_float() const { return std::holds_alternative<double>(data_); }
|
||||
bool is_number() const { return is_int() || is_float(); }
|
||||
bool is_string() const { return std::holds_alternative<std::string>(data_); }
|
||||
bool is_safe() const { return std::holds_alternative<SafeString>(data_); }
|
||||
bool is_array() const { return std::holds_alternative<Array>(data_); }
|
||||
bool is_object() const { return std::holds_alternative<Object>(data_); }
|
||||
|
||||
// String content for string or safe values, else "".
|
||||
std::string as_text() const {
|
||||
if (const auto* s = std::get_if<std::string>(&data_)) return *s;
|
||||
if (const auto* s = std::get_if<SafeString>(&data_)) return s->text;
|
||||
return "";
|
||||
}
|
||||
|
||||
double as_number(double fallback = 0.0) const {
|
||||
if (const auto* i = std::get_if<long long>(&data_)) return (double)*i;
|
||||
if (const auto* d = std::get_if<double>(&data_)) return *d;
|
||||
if (const auto* b = std::get_if<bool>(&data_)) return *b ? 1.0 : 0.0;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// Jinja truthiness: null/undefined/false/0/""/empty containers are false.
|
||||
bool truthy() const {
|
||||
if (is_null() || is_undefined()) return false;
|
||||
if (const auto* b = std::get_if<bool>(&data_)) return *b;
|
||||
if (const auto* i = std::get_if<long long>(&data_)) return *i != 0;
|
||||
if (const auto* d = std::get_if<double>(&data_)) return *d != 0.0;
|
||||
if (const auto* s = std::get_if<std::string>(&data_)) return !s->empty();
|
||||
if (const auto* s = std::get_if<SafeString>(&data_)) return !s->text.empty();
|
||||
if (const auto* a = std::get_if<Array>(&data_)) return !a->empty();
|
||||
if (const auto* o = std::get_if<Object>(&data_)) return !o->empty();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string type_name() const {
|
||||
if (is_null()) return "null";
|
||||
if (is_undefined()) return "undefined";
|
||||
if (is_bool()) return "bool";
|
||||
if (is_int()) return "int";
|
||||
if (is_float()) return "float";
|
||||
if (is_string() || is_safe()) return "string";
|
||||
if (is_array()) return "array";
|
||||
if (is_object()) return "object";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const Storage& storage() const { return data_; }
|
||||
Storage& storage() { return data_; }
|
||||
|
||||
bool operator==(const Value& other) const = default;
|
||||
|
||||
private:
|
||||
Storage data_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::validate
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::views handler adapters. Function handlers (sync or
|
||||
// coroutine) and View subclasses adapt to the single routing::Handler type
|
||||
// (plan 05, section 3). Raw string returns stay rejected: adapters accept
|
||||
// Response-returning callables only (R4).
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../routing/route.h"
|
||||
#include "view.h"
|
||||
|
||||
namespace molo::app::views {
|
||||
|
||||
inline routing::Handler adapt(std::function<http_msg::Response(http_msg::Request&)> fn) {
|
||||
return [fn = std::move(fn)](http_msg::Request& req)
|
||||
-> async::Task<http_msg::Response> { co_return fn(req); };
|
||||
}
|
||||
|
||||
inline routing::Handler adapt_task(routing::Handler fn) { return fn; }
|
||||
|
||||
template <typename V>
|
||||
routing::Handler view_handler() {
|
||||
static_assert(std::is_base_of<View, V>::value, "V must derive from molo::app::views::View");
|
||||
return [](http_msg::Request& req) -> async::Task<http_msg::Response> {
|
||||
V view(req);
|
||||
co_return co_await view.dispatch();
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace molo::app::views
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::views flash helpers. flash() stores a one-time message in
|
||||
// the session store (seam owned by 03-security, default in-memory store held
|
||||
// by Application); take() returns pending messages and clears them so each
|
||||
// message renders exactly once (plan 05, section 6 Errors).
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/cookies.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
#include "../seams/session.h"
|
||||
|
||||
namespace molo::app::app {
|
||||
class Application;
|
||||
}
|
||||
|
||||
namespace molo::app::views {
|
||||
|
||||
inline std::string generate_session_id() {
|
||||
static std::atomic<std::uint64_t> counter{1};
|
||||
std::uint64_t n = counter.fetch_add(1, std::memory_order_relaxed);
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "sess-%016llx", (unsigned long long)n);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
inline constexpr const char* kSessionCookie = "molo_session";
|
||||
|
||||
class Flash {
|
||||
public:
|
||||
static void flash(http_msg::Request& req, http_msg::Response& res, std::string level,
|
||||
std::string text);
|
||||
static std::vector<seams::FlashMessage> take(http_msg::Request& req);
|
||||
};
|
||||
|
||||
} // namespace molo::app::views
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
// Spec: molo::app::views::View. aiohttp-style class-based view: constructed
|
||||
// with the Request, one virtual coroutine per HTTP method, dispatch()
|
||||
// selects by method (plan 05, E7). Unimplemented methods throw 405 with the
|
||||
// view's Allow list; override allowed_methods() to list implemented ones.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../async/task.h"
|
||||
#include "../errors/http_error.h"
|
||||
#include "../http_msg/method.h"
|
||||
#include "../http_msg/request.h"
|
||||
#include "../http_msg/response.h"
|
||||
|
||||
namespace molo::app::views {
|
||||
|
||||
class View {
|
||||
public:
|
||||
explicit View(http_msg::Request& request) : request_(request) {}
|
||||
virtual ~View() = default;
|
||||
|
||||
virtual async::Task<http_msg::Response> get() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> post() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> put() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> patch() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> del() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> head() { return method_not_allowed(); }
|
||||
virtual async::Task<http_msg::Response> options() { return method_not_allowed(); }
|
||||
|
||||
virtual std::vector<std::string> allowed_methods() const {
|
||||
return {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};
|
||||
}
|
||||
|
||||
async::Task<http_msg::Response> dispatch() {
|
||||
switch (request_.method()) {
|
||||
case http_msg::Method::GET: co_return co_await get();
|
||||
case http_msg::Method::POST: co_return co_await post();
|
||||
case http_msg::Method::PUT: co_return co_await put();
|
||||
case http_msg::Method::PATCH: co_return co_await patch();
|
||||
case http_msg::Method::DELETE: co_return co_await del();
|
||||
case http_msg::Method::HEAD: co_return co_await head();
|
||||
case http_msg::Method::OPTIONS: co_return co_await options();
|
||||
}
|
||||
co_return co_await method_not_allowed();
|
||||
}
|
||||
|
||||
protected:
|
||||
http_msg::Request& request() { return request_; }
|
||||
|
||||
private:
|
||||
async::Task<http_msg::Response> method_not_allowed() {
|
||||
throw errors::MethodNotAllowed(allowed_methods());
|
||||
co_return http_msg::TextResponse("unreachable");
|
||||
}
|
||||
|
||||
http_msg::Request& request_;
|
||||
};
|
||||
|
||||
} // namespace molo::app::views
|
||||
Reference in New Issue
Block a user