Skip to content

feat(server/app): thin-bin Extensions: HTTP routers and a request observer - #549

Open
LeeroyHannigan wants to merge 10 commits into
feat/request-scopefrom
feat/thin-bin-extensions
Open

LeeroyHannigan wants to merge 10 commits into
feat/request-scopefrom
feat/thin-bin-extensions

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

What

A backend's thin binary installs its storage backend and calls extenddb_app::run. It had no way to add an HTTP route of its own or a hook on the request path. extenddb_app::run_with(build, extensions) takes an Extensions value with two fields. run is the same call with the empty default. Extensions, RequestObserver, RequestRecord and the axum the server is built with are re-exported from extenddb_app, so a thin main needs that one dependency.

Extensions::http is a list of routers with absolute prefixes. start_server nests each after the built-in routes and before the response security layer. So an extension response carries X-Content-Type-Options, X-Frame-Options and Referrer-Policy like a built-in one. The layers that start_server puts in front of every route apply too. They answer ServiceUnavailable while the serving registration is lost, refuse a repeated host or authorization header, and fail a request body that stops sending data. Nothing else of the server's applies: no authentication, no request rate limit, and axum's default 2 MB body limit for the limited extractors. The server refuses a prefix that:

  • is not absolute, is / or ends with /
  • has an empty segment, a parameter or wildcard segment, or a byte no request path carries
  • is at or under /health, /metrics, /management or /console
  • is at, under or above an earlier extension's prefix

The refusal names the colliding route. cmd_serve checks the list before the backend connects or the daemon forks, so the message reaches stderr.

Extensions::request_observer receives one RequestRecord per request that reached authentication. It gets the record after the response is built, on the request's task and outside the request scope. The record holds:

  • the request id the client received, the operation and the request's top-level TableName
  • the account when authentication produced one
  • the status and error __type the client received
  • the handler latency and a hash of the raw body
  • the two SDK correlation headers

A refusal from authentication, the point-in-time recovery check, authorization or the throttle is recorded with its error type. A request the client abandons while it is in flight is recorded with status 0. A request refused before authentication (an oversize body, no X-Amz-Target, an unknown operation, a body that is not JSON) is not recorded. Without an observer the handler hashes no body and builds no record.

The record is built once per observed request, before authentication, and held by a guard while the request runs. If the handler future is dropped, the guard reports it. Otherwise the exit completes it and reports it. Because there is one construction site, every exit for one request carries the same table name. Extensions and RequestRecord are #[non_exhaustive]. A binary builds Extensions through Extensions::default with with_router and with_request_observer, and only the server builds a RequestRecord.

Why

A backend author may want a status page, a control endpoint or a per-request audit record. Before this PR, that took a fork of the server crate or a second listener. The two extension points cover both without the server knowing what the binary does with them. The observer's record is what a retry analysis needs and nothing a wire capture would not show. The body is hashed, not kept, and the SDK headers are what the SDKs send to correlate the attempts of one call.

Stacking

This branch is built on #547 (the request scope), which stacks on #536, #532 and #529. The change under review is the two commits this branch had on top of #547: the code and tests, and the documentation. After them come the merges of #547's current head and the follow-ups below. Once #547 is on main this PR rebases onto main.

Merge of #547's head

06344280d merges #547 at 119d67cc5, which carries #536 and main at 95425f5e8. Five files conflicted. In crates/server/src/lib.rs, the extension routers mount after the built-in routes and inside the layers that main puts in front of every route. From the inside out, the layers are the 503 while the serving registration is lost and the repeated header refusal. Then come the security headers, the request body timeout, and HSTS when TLS is on. The security headers come from one function, apply_security_headers, at main's place in that order. In crates/server/src/handler.rs, the point-in-time recovery refusal (#950) returns Refused, so the observer records it like the other refusals after authentication. The other three files keep both sides.

The follow-up commits:

Testing done

Twelve unit tests cover the extension rules:

  • a mounted router answers under its prefix behind the security headers
  • the empty default mounts nothing
  • a reserved prefix, one at or under a reserved prefix and a duplicate are each refused, with the colliding route or the shape named
  • a prefix at, under or above an earlier prefix is refused the same way
  • a relative prefix, /, a trailing slash, an empty segment, a parameter and a wildcard are each refused the same way
  • a refused prefix stops the mount at that router
  • the list check, the builders and body_hash

Seven tests run through handle_request against an in-memory engine:

  • a served request is recorded once with the response's request id, status, account, body hash and both headers
  • a dispatch error is recorded with its error type and table
  • a throttle refusal is recorded with ProvisionedThroughputExceededException, the table and the account
  • an authentication refusal is recorded with UnrecognizedClientException, the table and no account
  • a request refused before authentication is not recorded, and an abandoned request is recorded with status 0
  • a state without an observer answers as before

Three tests run through start_server on a loopback socket:

  • an extension response carries the three security headers from the server's own wiring. The extension body limit is axum's default, and the request handler's is 16 MB
  • eleven built-in routes answer the same with and without an extension mounted
  • a client that closes its socket mid-request produces one record with status 0

Twelve request shapes went through the handler on the base and on this branch, with and without an observer. Each gave the same status, headers and body on both.

Negative controls, each on a clean committed tree and restored after:

  • applying the security layer before the mount fails the start_server header test
  • the overlap rule reduced to equality fails two prefix tests, and the shape rule removed fails the shape test
  • the guard's record built without the table fails three observer tests
  • the record cloned instead of taken from the guard fails four (each request recorded twice)
  • the exit record removed, the refusal record removed, the guard never disarmed and the guard's Drop emptied each fail the tests named for them
  • the error type not recorded and the reserved-prefix check removed fail the tests named for them too
cargo +1.97.0 fmt --all -- --check
cargo +1.97.0 clippy --all-targets -- -D warnings
cargo +1.97.0 test -p extenddb-server -p extenddb-app --lib   # 551 + 93 passed at b0ae22686

At b0ae22686, 5 more server tests fail on the build host only: the backup_store tests, because another user owns a directory above the spool directory.

Checklist

  • I have read CONTRIBUTING.md
  • All tests pass (cargo test --workspace --lib; the integration suites run in CI)
  • Code is formatted (cargo fmt --check)
  • Clippy is clean (cargo clippy --all-targets -- -D warnings)
  • I have added or updated tests for new functionality
  • I have updated documentation if behavior changed
  • Breaking changes are noted below (if any)
  • If this changes the wire protocol, Storage trait, auth model, on-disk
    format, or public CLI surface, an RFC has been accepted or is linked
    below. Otherwise, an ADR captures the decision (link below).

ADR / RFC: no trait change; extenddb_app and extenddb_server gain a public type and function. RFC-0002 now states that Extensions and RequestRecord may gain fields in a minor release and how a thin binary builds the one and reads the other. The architecture guide gains a Thin binary extensions subsection; the storage extension manual's Step 6 gains a paragraph on run_with, the exposure of extension routes and the observer's calling contract.

Breaking changes

None. extenddb_app::run is unchanged. extenddb_server::start_server gains a parameter; it has one caller in the workspace (serve.rs) and is not called by the thin binaries, which go through extenddb_app. No wire body, header or status changes with or without an observer.


By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.

… observer

Add extenddb_server::extensions with Extensions { http, request_observer },
re-exported from extenddb_app beside RequestObserver, RequestRecord and the
axum the server is built with, and extenddb_app::run_with(build, extensions);
run(build) is the same call with the empty default. Extensions is
non_exhaustive and built from Extensions::default() with with_router and
with_request_observer. The serve subcommand hands it to ServeParams
(with_extensions); every other subcommand ignores it.

Routers. start_server takes the list of (prefix, Router) and nests each after
the built-in management and console routes and before the response security
layer, so an extension response carries X-Content-Type-Options, X-Frame-Options
and Referrer-Policy like a built-in one. Nothing else of the server's applies
to an extension route: no authentication, no request rate limit, and axum's
default 2 MB body limit for the limited extractors. A prefix is refused when
it is not absolute, is /, ends with /, has an empty segment or a parameter or
wildcard segment, is at or under /health, /metrics, /management or /console,
or is at, under or above an earlier extension's prefix; the refusal names the
colliding route. cmd_serve checks the prefixes before the backend connects or
the daemon forks, so the message reaches stderr. The security layer moved into
apply_security_headers so the tests apply the layer the server applies.

Observer. AppState gains request_observer. The handler builds one
RequestRecord per observed request before authentication (request id,
operation, the request's TableName, a hash of the raw body, the two SDK
correlation headers) and holds it in a guard while serve_request runs. On the
normal path the guard hands the record back and the exit completes it with the
account, the status and error __type the client received and the handler
latency, then calls the observer once: a served request, a dispatch error, or
a refusal from authentication, authorization or the throttle (serve_request
returns a Refused value carrying the account it had resolved). If the client
goes away while serve_request is in flight, the guard's Drop reports the record
with status 0; a handler that panics drops the guard during unwinding and the
observer is not called. A request refused before authentication (oversize
body, no X-Amz-Target, unknown operation, a body that is not JSON) is not
recorded. Without an observer the handler hashes no body and builds no
record. RequestRecord is non_exhaustive and built by the server only.

Tests: twelve for the extension rules (reachable behind the security headers;
the empty default mounts nothing; reserved, at-or-under-reserved, duplicate,
at-under-or-above an earlier prefix, relative, root, trailing slash, empty
segment, parameter and wildcard prefixes refused with the colliding route
named; a refused prefix stops the mount at that router; the list check;
the builders; body_hash). Seven through handle_request against an in-memory
engine: a served request recorded once with the response's request id,
status, account, body hash and headers; a dispatch error with its error type
and table; a throttle refusal with ProvisionedThroughputExceededException,
table and account; an authentication refusal with UnrecognizedClientException,
the table and no account; a request refused before authentication not
recorded; an abandoned request recorded with status 0; a state without an
observer serving as before. Three through start_server on a loopback socket:
an extension response carries the three security headers from the server's
own wiring, the extension body limit is axum's default and the request
handler's is 16 MB; eleven built-in routes answer the same with and without an
extension mounted; a client that closes its socket mid-request produces one
record with status 0.
Architecture guide: a Thin binary extensions subsection under Pluggable Architecture (run_with, the prefix rules, what does and does not apply to an extension route, the observer's contract, status 0 for an abandoned request, nothing built without an observer). Storage extension manual: a paragraph under Step 6 naming the types, the exposure of extension routes, the observer's calling contract and the record's table_name rule. RFC-0002: Extensions and RequestRecord may gain fields in a minor release; a thin binary builds Extensions through its builders.
LeeroyHannigan added a commit that referenced this pull request Nov 3, 2026
The first commit sorts the body after authentication. Open pull
requests #587, #549 and #547 edit the lines around the end of the
authentication segment, so there the call conflicts with all three.
This commit moves it to immediately after the parse, where it merges
cleanly with the nine open pull requests that edit handler.rs.

On a preserve_order build an unauthenticated request now pays for the
sort, as it already pays for the parse. Without preserve_order the call
does nothing.

The comment now says which builds have preserve_order: any build that
compiles the MongoDB backend crate, which includes a build of the whole
workspace, not only the MongoDB binary.
crates/app/src/cmd_serve.rs keeps the serve parameters, config path, bounded runtime shutdown and exit codes of feat/request-scope. This branch adds its extensions to those parameters.

crates/server/src/handler.rs keeps the request id argument of serve_request, the point-in-time recovery refusal and the item authorizer from feat/request-scope. The success flag and the account and metric table on error metrics come from there too. From this branch it keeps the observer record, the Refused type and the error type. A point-in-time recovery refusal now returns Refused, so the observer sees it like any other refusal after authentication.

crates/server/src/handler/throttle_wire_tests.rs holds the admission field of feat/request-scope next to the request observer of this branch.

crates/server/src/lib.rs takes the serve exports, admission field, admission layer, repeated header refusal and request body timeout from feat/request-scope. This branch contributes the extension exports, request observer field, extension mount and security header function. Extensions mount after the built-in routes, so every layer above them, security headers included, wraps their responses as well.

crates/server/src/serve.rs carries the config path and catalog label of feat/request-scope together with the extensions of this branch.
feat/request-scope brings three layers from main that start_server puts in front of every route. They are a ServiceUnavailable answer while the serving registration is lost, the refusal of a repeated host or authorization header, and the request body timeout. The extension routers mount after the built-in routes and under those layers, so the layers apply to them too.

The Extensions::http comment, the architecture guide and the storage extension manual said that extension routes get the security headers and nothing else. They now name the three layers. The list of what does not apply stays as it was.
The merge brings two commits of #547: the second subscriber in the dispatch entry test, and the architecture guide sentence on the TTL index backfill. No file conflicted.
…er records

Since the merge 0634428, the point-in-time recovery refusal returns Refused, and the request observer records it. The comment on the refusal arm of handle_request listed only authentication, authorization and the throttle.
… routes

Since the merge 0634428, extension routes sit under the layers that start_server puts in front of every route, and the documentation says so. start_server_mounts_extensions_behind_the_security_layer now sends a second Host header to an extension route and expects the 400 of the repeated header refusal.
LeeroyHannigan added a commit that referenced this pull request Nov 17, 2026
The merge brings the new commits of #549 and #547. #547 adds a second subscriber to the dispatch entry test and a guide sentence on the TTL index backfill. #549 adds the recovery refusal to the observer comment and the repeated Host check on an extension route. No file conflicted.
LeeroyHannigan added a commit that referenced this pull request Nov 17, 2026
The merge brings the new commits of #557 and of the PRs below it. #557 rewrites the admin page text and reads the tab identity from one identity_label call. #547 and #549 change tests, a comment and a guide sentence. No file conflicted.
@demohan demohan self-assigned this Nov 24, 2026

@demohan demohan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With no extensions installed, the default binary answers as the base does on SQLite and on PostgreSQL: 394 console and management requests, 48 data-plane requests run twice (errors, refusals, oversize bodies, wrong methods, non-root paths) and 40 management API requests with good, bad and no Basic auth, apart from the per-process secret key. A thin binary built from the manual's paragraph and the extenddb_app docs needs only extenddb-app and the backend crates. On it:

  • Extension responses carry the security headers, and HSTS over TLS, over HTTP/1.1 and HTTP/2, including 404s and the repeated-header 400.
  • Bytes bodies stop at 2 MB with 413, and / still takes up to 16 MB.
  • Every prefix the check refuses exits 1 with its message on stderr, in daemon mode too, before the port binds or the database is touched.
  • Observer records match the request id, status and __type the client received, 0 mismatches over about 2,400 records, and carry no credentials, item values or bodies. Requests refused before authentication are not recorded.

fmt and clippy are clean, the code builds on the 1.88 MSRV, 556 server and 93 app tests pass (30 of 30 repeated runs), CI is green on 53 checks, and the five controls re-run from the body fail the tests they name.

I will approve once every prefix the check accepts mounts and answers, the observer contract covers the fork and a panic, and the four untested guarantees below have tests.

crates/server/src/handler.rs:1

Optional. The file grows from 547 to 681 lines. A stalled body on an extension route answers 400 Failed to buffer the request body, where / answers 408; the manuals could say which.

if prefix == "/" {
return Err(ExtensionMountError::Root);
}
if prefix.ends_with('/')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A segment that starts with : passes this check. /:id and /_x/:id make axum 0.8.9 panic in Router::nest (path_router.rs:211) after the daemon has forked and 12 catalog migrations have run. In the foreground the process exits 101; in daemon mode the parent prints only daemon process exited during startup, and the panic text is in the journal. /health/x is refused on stderr before the backend connects, as the PR body, the Extensions::http doc, the architecture guide (:233) and the manual (:367) say every bad prefix is. Other accepted prefixes mount and are unreachable, twice each:

  • /a<b, /_t`b and >: every request gets 400 from hyper before routing.
  • /é, and prefixes with |, ", ^, \ or []: only the raw byte answers; the percent-encoded form clients send gets 404.
  • /.. and /.: browsers and curl remove the dot segments, and /%2E%2E/status gets 404.

Refusing a leading :, the bytes hyper refuses, bytes at or above 0x80 and dot segments as BadShape, with test rows, would match the docs.

/// once per request after the response is built, on the request's own task,
/// outside the request scope and holding no lock. The call runs before the
/// response is written to the socket, so a slow observer delays the response;
/// an observer that does more than record should hand the record to its own

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extensions is built before run_with, and the daemon fork keeps only the calling thread. An observer that sends records to a thread spawned in main, as "hand the record to its own task" suggests, wrote 0 records for 6 requests in daemon mode and 3 for 3 in the foreground. A factory that serve calls after the fork, or a sentence in this doc and the manual saying to start the task lazily on the first call, would cover it.

record.status = response.status().as_u16();
record.error_type = Some(refused.error.error_type().to_owned());
record.latency_us = elapsed_us(handler_start);
observer.on_response(record);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A panicking observer runs after the write is applied, so the request does not fail in the sense this doc gives. One boto3 update_item with ADD c :one and max_attempts=3 left the counter at 4, twice: the connection closed, and the SDK retried a write that had committed. The same applies at :333 and :371. Wrapping the observer calls in catch_unwind, and the doc saying the response is still sent, would keep a broken observer from repeating writes.

);

// The observed exit for every request that reached dispatch.
if let (Some(observer), Some(mut record)) = (state.request_observer.as_ref(), record.take()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four documented guarantees have no test that fails without them. Each mutation below leaves the 22 new tests and the 93 app tests passing:

  • the extension mount moved after the ServiceUnavailable layer for a lost registration;
  • extension routes losing only the request body timeout;
  • the authorization and point-in-time recovery refusals recording account_id: None instead of the account;
  • the validate_extension_prefixes call at cmd_serve.rs:57 removed.

At this head each behaves as written where measured: a stalled body on an extension route answers 400 after 30 s, and a point-in-time recovery refusal is recorded with the account.

}

/// Hash of the raw request body for [`RequestRecord::body_hash`].
pub(crate) fn body_hash(bytes: &[u8]) -> u64 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DefaultHasher::new() is unkeyed, so a body hashes to the same value in every process (15028961044028402855 in two). A holder of records can confirm a guessed body offline. A key drawn once per process matches the documented "within one process" scope.

/// The request id the client received in `x-amzn-RequestId`.
pub request_id: String,
/// The operation name from `X-Amz-Target`.
pub operation: String,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ListStreams and ListBackups record the TableName filter they were sent, and a table ARN in TableName is recorded as the ARN, so "None for the stream operations" does not hold. On an unauthenticated refusal the value is unchecked client text of any length (an 8 MiB name was recorded as sent), and the doc names only the two SDK fields as client-supplied.


The `bin` crate will discover your backend at startup and select it by name from the configuration.

A thin binary that needs HTTP routes of its own (a status page, a control endpoint) or a hook on every request passes an `extenddb_app::Extensions` to `extenddb_app::run_with` in place of `run`. `Extensions::http` is a `Vec<(String, axum::Router)>`, built against the `axum` that `extenddb_app` re-exports; `Extensions::request_observer` is an `Option<Arc<dyn RequestObserver>>`, and the trait has one method, `fn on_response(&self, record: RequestRecord)`, on a `Send + Sync` type. Routers mount under absolute prefixes of literal segments, outside `/health`, `/metrics`, `/management` and `/console`, and not at, under or above another extension's prefix; a refused prefix stops the server before it connects to the backend. Their responses carry the server's security headers, and the layers in front of every route apply to them: a `ServiceUnavailable` answer while the serving registration is lost, the refusal of a repeated `host` or `authorization` header, and the request body timeout. Nothing else of the server's applies to them: no authentication, no request rate limit, and axum's default 2 MB body limit for the limited extractors (none for a raw `Body`). A route that changes state or reads data authenticates in its own handler or layer. A `RequestObserver` receives one `RequestRecord` per request that reached authentication, after the response is built, on the request's task, with no lock held and no ordering across requests; keep `on_response` short or hand the record to a task of your own, since the response is written after it returns, and do not let it panic, since a panic there closes the connection. The record's `table_name` is the request's top-level `TableName`, so it is `None` for the batch, transaction, PartiQL and stream operations; its two SDK fields are client-supplied text.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"In place of run" points at a call Step 6 never shows; its example uses inventory::submit! and ServerComponentsRegistration, which no crate defines. The paragraph also promises one record per request that reached authentication, and a request whose handler panics gets none. A blocking observer holds a runtime worker and slows every route: with a 2 s sleep, 4 workers and 8 concurrent requests, /health took up to 3.8 s and DynamoDB requests up to 6.0 s.

# Conflicts:
#	crates/server/src/handler.rs
#	crates/server/src/handler/request_scope_tests.rs
#	crates/server/src/handler/throttle_wire_tests.rs
…name

The merge of feat/request-scope brings main's parse_request into
handle_request. The handler now holds an extenddb_engine::ParsedRequest,
and the parsed body becomes a value only when serve_request calls admit
after authentication. handle_request builds the observer's record before
authentication, with the table name from the parsed body. A request that
authentication refuses gets a record with its table.

ParsedRequest gets a body accessor, which the merge's handle_request
calls to fill in the record's table name. admit runs where it did, after
authentication.
@LeeroyHannigan LeeroyHannigan changed the title feat(server,app): thin-bin Extensions: HTTP routers and a request observer feat(server/app): thin-bin Extensions: HTTP routers and a request observer Dec 2, 2026

@navareamol navareamol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured that the observer record keeps the whole TableName from the body. A request with a 1,000,000 character TableName was answered with a ValidationException and still reached the observer with table_name of 1,000,000 characters. The body limit allows up to 16 MB. I think the record should cut the name at the DynamoDB limit or leave it as None when it is longer. Is there a reason to keep the full value?

The RequestObserver doc says a panic in on_response fails the request and closes its connection. That matches what I saw on the normal path. The abandoned request path calls the observer from the Drop of AbandonGuard, so a panic there happens in a destructor. Could the doc mention that case?

The branch is 41 commits behind main and sits on #547, which is still open. Could you merge main once #547 lands so the checks run on the merged tree?

I will approve once the record limits the table name, the observer doc covers the abandon call, and the checks are green on a branch that has main merged.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants