Aegon

Middleware Pipeline

Coroutine-native onion execution model, multi-level scoping, short-circuiting, and per-request typed data bags.

Aegon features a coroutine-native, onion-model middleware architecture designed for zero per-request heap allocation. Middlewares can execute pre-handler logic, delegate down the chain via co_await next(ctx), inspect or mutate the response during the post-handler phase, or terminate the pipeline early (short-circuit).


The Onion Execution Model

In Aegon, middleware functions wrap downstream handlers like concentric layers of an onion:

Inbound Request
  │
  ▼
[Global Middleware (Pre-handler)]
  │
  ▼
[RouteGroup Middleware (Pre-handler)]
  │
  ▼
[Per-Route Middleware (Pre-handler)]
  │
  ▼
[Target Route Handler (ctx)]
  │
  ▲
[Per-Route Middleware (Post-handler)]
  │
  ▲
[RouteGroup Middleware (Post-handler)]
  │
  ▲
[Global Middleware (Post-handler)]
  │
  ▼
Outbound Response

When an incoming request arrives:

  1. Pre-handler phase: Middlewares execute in registration order from global to route-level until reaching the route handler.
  2. Handler execution: The target endpoint handler executes (co_await handler(ctx)).
  3. Post-handler phase: Execution resumes after co_await next(ctx), unwinding in reverse order back up to global middlewares before the final response is flushed.

Core Signatures & Adapters

Middleware types are defined in #include <aegon/http/Middleware.h>. The fundamental types are:

namespace aegon::http {
    using Next = std::function<core::Task<void>(Context&)>;
    using MiddlewareFn = std::function<core::Task<void>(Context&, Next)>;
    using Handler = Next;
}

Through make_middleware(), Aegon automatically adapts four callable signatures into standard MiddlewareFn wrappers without requiring boilerplate:

// Full coroutine onion: runs code before and after next(ctx)
[](http::Context& ctx, http::Next next) -> core::Task<void> {
    // 1. Pre-handler
    ctx.res().header("X-Custom", "1");
    
    // 2. Delegate downstream
    co_await next(ctx);
    
    // 3. Post-handler
    ctx.res().header("X-Elapsed", "12ms");
}

Writing Custom Middlewares

1. Timing & Metrics Middleware (Onion)

This example measures total request execution time using std::chrono::steady_clock:

#include <aegon/http/Server.h>
#include <aegon/http/Middleware.h>
#include <chrono>

using namespace aegon::http;

auto timing_middleware() -> MiddlewareFn {
    return [](Context& ctx, Next next) -> core::Task<void> {
        auto start = std::chrono::steady_clock::now();

        // 1. Pre-handler: attach identification headers
        ctx.res().header("X-Framework", "Aegon");

        // 2. Delegate downstream to route handler
        co_await next(ctx);

        // 3. Post-handler: calculate elapsed microseconds
        auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now() - start
        );
        ctx.res().header("X-Response-Time", std::to_string(elapsed.count()) + "us");
    };
}

2. Short-Circuiting (Authentication Guard)

To abort request execution and prevent downstream handlers from running, write the error status code/body and return without calling co_await next(ctx):

auto require_api_key() -> MiddlewareFn {
    return [](Context& ctx, Next next) -> core::Task<void> {
        auto key = ctx.req().header("X-API-Key");
        if (key != "secret-production-token") {
            // Short-circuit: do NOT call next(ctx)!
            ctx.problem(
                StatusCode::Unauthorized, 
                "Unauthorized", 
                "Missing or invalid X-API-Key header"
            );
            co_return;
        }

        // Token is valid -> continue down pipeline
        co_await next(ctx);
    };
}

Attachment Scopes

Middlewares can be attached at three distinct granularities:

               [ Global Middleware ]  ── router.use(...)
                         │
             [ RouteGroup Middleware ]  ── group.use(...)
                         │
             [ Per-Route Middleware ]  ── router.get(..., { mw1, mw2 }, ...)
                         │
                     [ Handler ]

1. Global Scope (router.use)

Global middlewares apply to every incoming request routed through the server:

http::Server server;

server.router()
    .use(timing_middleware())
    .use([](http::Context& ctx) {
        ctx.res().header("X-App-Cluster", "us-east-1");
    });

2. RouteGroup Scope & Inheritance (group.use)

Group-scoped middlewares execute only for routes registered within that group. Nested sub-groups automatically inherit the parent group's middleware chain:

auto api = server.router().group("/api");
api.use(require_api_key()); // Applies to all /api/* routes

auto v1 = api.group("/v1"); // Automatically inherits require_api_key()!
v1.use(rate_limiter());      // Applies only to /api/v1/* routes

v1.get("/users", [](http::Context& ctx) {
    // Chain executed: Global -> api -> v1 -> handler
    ctx.res().text("Users List");
});

api.get("/ping", [](http::Context& ctx) {
    // Chain executed: Global -> api -> handler (v1 middleware does NOT run)
    ctx.res().text("pong");
});

3. Per-Route Scope

Individual endpoints can specify an explicit std::vector<MiddlewareFn> list:

std::vector<http::MiddlewareFn> admin_guards = {
    require_api_key(),
    require_admin_role()
};

// Route-level middleware executes after group middleware, immediately before the handler
api.get("/admin/metrics", std::move(admin_guards), [](http::Context& ctx) {
    ctx.res().json(R"({"cpu_usage": 0.12})");
});

Per-Request Typed Data Bag

Middlewares frequently need to pass state (such as decoded JWT claims, authenticated user profiles, or tracing IDs) to downstream handlers. Aegon provides a type-safe per-request store on Context.

The per-request store is isolated strictly to the lifetime of the active request Context and has zero interaction with the global singleton ServiceRegistry.

Methods on Context

MethodReturn TypeDescription
ctx.set<T>(value)voidStores a typed value of type T in the request context.
ctx.get<T>()T*Non-throwing lookup. Returns pointer to T, or nullptr if not set.
ctx.local<T>()T&Throwing lookup. Returns reference to T; throws std::runtime_error if missing.
ctx.has<T>()boolReturns true if type T is present in this request context.

Example: Setting & Consuming Typed State

struct UserClaims {
    std::string user_id;
    std::string role;
};

// 1. Auth middleware sets typed user state
auto auth_middleware() -> http::MiddlewareFn {
    return [](http::Context& ctx, http::Next next) -> core::Task<void> {
        // Authenticate request token...
        ctx.set<UserClaims>(UserClaims{
            .user_id = "usr_9981",
            .role = "admin"
        });

        co_await next(ctx);
    };
}

// 2. Downstream route handler accesses typed state
server.router().get("/profile", { auth_middleware() }, [](http::Context& ctx) {
    // Safe non-throwing lookup:
    if (auto* claims = ctx.get<UserClaims>()) {
        ctx.res().text("User ID: " + claims->user_id + ", Role: " + claims->role);
        return;
    }

    // Direct throwing access (useful when guard middleware guarantees presence):
    // UserClaims& claims = ctx.local<UserClaims>();

    ctx.res().status(http::StatusCode::Unauthorized).text("Missing credentials");
});

Exception Propagation

Exceptions thrown inside a middleware or route handler propagate naturally through standard C++ coroutine unwinding:

  1. Local Catching: Any middleware wrapping next(ctx) can catch exceptions thrown downstream:
    [](http::Context& ctx, http::Next next) -> core::Task<void> {
        try {
            co_await next(ctx);
        } catch (const std::exception& e) {
            ctx.res().status(http::StatusCode::InternalServerError)
                     .body("Caught error in middleware: " + std::string(e.what()));
        }
    }
  2. Global Exception Boundary: If an exception escapes all middlewares, it bubbles directly into Router::dispatch(), triggering your custom set_error_handler or producing an RFC 7807 500 JSON response.

Performance Guarantees

  1. Zero-Allocation Chain Execution: In run_chain(), execution traverses contiguous std::span<const MiddlewareFn> views of pre-registered vectors, eliminating per-hop dynamic memory allocations.
  2. Zero-Overhead Fast Path: When a route has no group or route-level middleware and no global middleware is registered, Aegon's fast path dispatches directly to the raw handler without wrapping lambdas.
  3. Pre-composed Route Chains: Group and per-route middleware are composed into a unified local chain at route registration time, ensuring SIMD exact-match radix tree lookups are never degraded during runtime dispatch.

Built-in Middlewares

Aegon ships with an optimized suite of production-ready middlewares:

MiddlewareHeaderDescription
Access Logger#include <aegon/http/middleware/AccessLog.h>High-speed structured logging (Combined, Common, Json, Custom) with slow request detection.
Compression#include <aegon/http/middleware/Compress.h>SIMD-accelerated dynamic HTTP response compression (gzip, deflate) using libdeflate.
CORS#include <aegon/http/middleware/Cors.h>W3C Fetch specification CORS handling with origin validation, subdomain wildcards, and preflight caching.
Security Headers#include <aegon/http/middleware/SecurityHeaders.h>Defense-in-depth security headers (CSP, HSTS, X-Content-Type-Options, Frame-Options, Referrer-Policy).
Authentication & RBAC#include <aegon/http/middleware/Auth.h>Bearer, Cookie, API Key, and Basic auth extractors with compile-time type-safe RBAC role guards.