HTTP transport
- Comparing
- v1 to v2
- Current
- Read the document
Abstract
We I will build the engine's HTTP layer from immutable request and response objects, a middleware
pipeline wrapping wrapped around a terminal handler, and a route table the engine owns, which requests are matched against and links
and
links are generated from. The layer will hydrate a request from the superglobals, run it through the pipeline, resolve a handler
a
handler and emit the response. It stops will stop at the handler seam.
Motivation
The engine has no HTTP layer. nikic/fast-route, filp/whoops and monolog/monolog have been
required since the start and are unused.
The panel is server-rendered, as
as ADR-0001
decides, so the engine has to accept
accept a request, decide what answers it, and produce HTML. Server rendering also means means
every anchor and every form action is
is generated on the server, so routes have to run backwards as well as forwards.
Proposal
The messages will be Request and Response, bespoke rather than PSR-7, as
ADR-0018 decides. They will carry their collections and values as
Headers, Cookies, Cookie, Uri, UploadedFiles and UploadedFile, and the request method and response status as
the enums Method and Status. BodyWriter will write a streamed body, and Emitter will emit a response. Handler
and Middleware will be the contracts for handling a request, and Pipeline will compose them. Routes will be
collected by RouteRegistry and sealed into RouteCatalogue, and Router will be a handler that matches a request to
a Route and delegates to it.
Messages
A Request will be constructed once per cycle and never changed.
| Member | Type | Taken from |
|---|---|---|
method |
Method |
The request method. |
uri |
Uri |
The server values, with the scheme resolved through the proxy headers. |
headers |
Headers |
The HTTP_* server values, plus the content type and length. |
cookies |
Cookies |
The request cookies. |
query |
array |
The query string values. |
form |
array |
The decoded form body. |
files |
UploadedFiles |
The uploaded files, with the nested shape normalised. |
body |
Stream | The raw body. |
ip |
IpAddress |
The client address, resolved through trusted proxies. |
will Request::fromGlobals()Headershydrate from the superglobals, which FrankenPHPbe immutable, the runtime chosen in
ADRwith case-0009, repopulates insensitive lookup and any number of values for each request inside
the worker callbackname. A general constructor It will take be normalised
from the same server values explicitlyrather than from getallheaders(), so its source is the same under a test can build a request without
touching global stateas under the worker.
PHP has already parsed the form body, decoded the encoding, folded the headers and populated the uploaded files before any engine code runs, so the request will hydrate rather than parse. The body will be the raw stream, read once and held, and not decoded here: it will stay a stream because uploads are measured in gigabytes. When the request was multipart, PHP has already consumed it.
Headers will be normalised from the server values rather than from getallheadersRequest::fromGlobals(), so will build a request from the source is superglobals, which FrankenPHP, the same under a
test as under runtime
ADR-0009 chooses, repopulates for each
request inside the workerworker callback. Lookup A general constructor will be case insensitive, and take the same values will be multi-valuedexplicitly, so a test can build a
request without touching global state.
MethodBy the time any engine will cover GET, HEAD, POST, PUTcode runs, PATCHPHP has already parsed the form body, DELETE decoded its encoding,
folded the headers and OPTIONSpopulated the uploaded files. A method outside that set The request will therefore hydrate rather than parse. The one thing
left raw is the body, which will not be decoded here. It will be read once and held, and it will stay a routing
outcomestream, not because
a hydration failurebackup upload can run to gigabytes. When the request was multipart, PHP has already consumed the body into the form
values and the uploaded files, and it cannot be read again.
The client address will come from the forwarded-for header, since the reverse proxy in front of the worker is always the
immediate peer. Loopback will be trusted by default, and the trusted set will be configurable. IpAddress will
normalise and validate both address families. It will belong with the engine's shared values rather than here, because
tokens and audit records use it too.
No attribute bag
A request IpAddress will carry no general-purpose property bag, normalise and nothing will copy a request to attach something to it.
Middleware that resolves something, such as the authenticated user or the matched route, validate both IPv4 and IPv6 addresses. It will bind it into the open
cycle from RFC-0007live with the
engine's shared values rather than in the HTTP layer, because tokens and whatever needs it will resolve it from the
container. A request will stay a description of what arrivedaudit records use it
too.
Responses
Response A request will carry a status, headersno general-purpose bag of properties, cookies and nothing will copy a bodyrequest in order to attach something
to it. Middleware that works something out, and take no position on content type: such as the content type will
be a headerauthenticated user or the matched route, set by will bind it into the
open cycle from RFC-0007, and whatever produced needs it will resolve it
from the bodycontainer. A request will stay a description of what arrived.
| Factory | Produces |
|---|---|
make(string $body, Status $status = Status::Ok) |
A response with a body, whatever its type. |
redirect(string $location, Status $status = Status::Found) |
A redirect, setting the location header. |
noContent() |
A 204 with no body. |
stream(Closure $writer, Status $status = Status::Ok) |
A streamed body, written by the closure. |
A will carry a status, headers, cookies and a body. It will take no position on content type: that will be StatusResponsean integer-backed enum over the registered status codesa
header, carrying set by whatever produced the reason phrasebody. As an enum, it
Each cookie it sets will not be able to express a code outside the registryCookie, carrying its name, value, expiry,
path, domain, and the non-standard codes will be left out. The reason phrase
is not transmitted over HTTP/2 or HTTP/3its secure, which is what the proxy negotiates for most traffic; it will exist for logs
HTTP-only and error pagessame-site attributes.
A body will be a string, or a closure taking a BodyWriter for a streamed one. The closure Responses will be given a writer
rather than writing directly, so streaming can be tested against a fake writer instead of output buffering. BodyWriter
will write a string, write a file and flush.built through static factories:
The request
The messages will be bespoke rather than PSR-7, as ADR-0018
decides. A Request will describe what arrived. It will be constructed once per cycle and never
changed, and it will carry:
- the method, as the
Methodenum; - the URI, as a
Uriholding the scheme, host, port, path and query string, with the scheme resolved through the proxy headers; - the headers, as
Headers, taken from theHTTP_*server values plus the content type and length; - the cookies, as
Cookies; - the query string values and the decoded form body, each as an array;
- the uploaded files, as
UploadedFiles, which normalises PHP's nested shape intoUploadedFilevalues; - the raw body, as a stream;
- the client address, as an
IpAddress.
Method will cover GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS. A method outside that set will be a routing
outcome, not a failure to hydrate the request.
Reading the request from the worker
The client address
The reverse proxy in front of the worker is always the immediate peer, so the connection's own address is the proxy's. The client address will come from the forwarded-for header instead, trusting loopback by default, with the set of trusted proxies configurable.
No attribute bag
Responses
Response::make(string $body, Status $status = Status::Ok): Response;
Response::redirect(string $location, Status $status = Status::Found): Response;
Response::noContent(): Response;
Response::stream(Closure $writer, Status $status = Status::Ok): Response;
make() will cover a body of any type. Each of the other three will exist because it sets something beyond the body: a
redirect sets the location header, noContent() produces a 204 with no body, and stream() takes a closure in place of
a string.
Status will be an integer-backed enum over the registered status codes, carrying each code's reason phrase. As an
enum, it will not be able to express a code outside the registry, and non-standard codes will be left out. The reason
phrase is not sent over HTTP/2 or HTTP/3, which is what the proxy negotiates for most traffic, so it will exist for logs
and error pages.
Streaming a body
A body will be a string, or a closure that is given a BodyWriter for a streamed one. File and backup downloads need
it, as will server-sent events for the console.
Response::stream(static function (BodyWriter $out) use ($path): void {
$out->file($path);
});
The closure will be handed a writer rather than echoing, so streaming can be tested against a fake writer instead of
through output buffering. will write a EmitterBodyWriterresponse: the status line, the headers, the cookies, then the bodystring, whether that body is a
string or write a closurefile, and flush.
The pipeline
Emitter will send a response: the status line, then the headers, the cookies and the body. A string body will be
written in one call, and a closure body will be invoked with a real writer.
Handlers and middleware
interface Handler
{
public function handle(Request $request): Response;
}
interface Middleware
{
public function process(Request $request, Handler $next): Response;
}
Handler will be the seam this design stops at. Everything that turns a request into a response will implement it,
including a composed pipeline, so a pipeline will be substitutable for the handler it wraps.
Middleware will receive be handed the next handler rather than a closure, so a test can hand give a middleware the terminal handler
directly. Returning A middleware that returns without calling it will short-circuitcircuit everything inside it: an authentication authentication
middleware returning a redirect will never
never reach what it wrappedwraps.
$handler = Pipeline::through($middleware)->then($terminal);
Middleware will be given as class names and resolved through the container, as
RFC-0001 describes, when the pipeline is composed rather than on every
request. They will have the Process lifetime from RFC-0007, so
a one instance will serve every request the worker handles. A middleware will hold no state belonging to a request and request, and
will reach anything that does through a
a provider.
The pipeline will be composed at two moments. The outer pipeline will wrap the router and be composed once at boot, since every request passes through it whatever it matches. A route's pipeline cannot be composed at boot, because which middleware apply depends on the route matched. It will be composed on first use instead, and kept for the life of the worker, keyed by route. A runtime that boots per request forces composition on every request; a worker does not.
Middleware Pipelines will run outward to inward and unwind in reversebe composed at two moments. Three sources will apply in order: global, then group, then
routeThe outer pipeline, with declaration order within each. A holding the middleware named by more than one source will run onceevery request passes through
whatever it matches, at its earliest
position. There will be no priority numbers: order will wrap the router and be positionalcomposed once at boot.
Routing
FastRoute matches a path against patterns and answers found, not found or method not allowed; it neither holds routes in a form anything else can read nor runs backwards. Since every anchor and form action is generated, the engine will own the route table and compile FastRoute from it.
RouteRegistry Middleware will collect routes run outward to inward and seal into RouteCatalogue, following
ADR-0003unwind in reverse. The
catalogue They will be indexed by name and hold the dispatch data compiled come from the tablethree sources, along
with each pattern parsed into its variantsapplied in order:
global, which is what generation needsthen group, then route, each in the order it was declared. Both A middleware named by more than one source will be built once at boot and held for
the life of the workerrun
once, so no compiled form will be cached to a fileat its earliest position.
A Route There will carry the methods it answers, its path pattern, its name, the handler behind it, its middleware and its
panel contextbe no priority numbers. Routes Order will be a projection of the action registrypositional, so a route's name
will come from the action behind middleware that must run before another says so by
where it and nothing will declare a name by handappears in the list.
The router will be a Handler. It will match, then delegate:
| Outcome | Result |
|---|---|
| Found | The route's pipeline runs, wrapping the handler behind the route. |
| Not found | A 404 status, with presentation left to whatever renders errors. |
| Method not allowed | A 405 status carrying the permitted methods in an allow header. |
Routes will be collected in a HEADRouteRegistrywill be served by the matching and sealed into a , following
ADR-0003. The
catalogue GETRouteCatalogueroutewill be indexed by name, with the body suppressed when and will hold the response dispatch data along with each pattern
parsed into its variants, which is emitted. Paths will be
case sensitivewhat generation needs. A path differing from its canonical form only by a trailing slash Both will redirect to be built once at boot and held for the canonical form.
Parameters life of the
worker, so no compiled form will be extracted as strings; turning one into an entity belongs cached to whatever consumes the routea file.
Each route A Route will belong to a panel contextcarry the methods it answers, its path pattern, its name, the handler behind it, its middleware and each context its
panel context. Routes will map to be a URL prefix taken from configuration rather
than fixed in code, since projection of the panel decides action registry, so every route will
have an action behind it, its own URL shapename will come from that action, and nothing will declare a route name by hand.
Generation will not be a service. The catalogue will look a route up by name. The route will substitute parameters into its own pattern and validate them against its own constraints, so a missing or invalid parameter will throw rather than produce a broken link.
When pipelines are composed
A route's own pipeline cannot be composed at boot, because which middleware apply depends on the route matched. It will be composed the first time its route is used instead, and kept for the life of the worker, keyed by route, so the cost is paid once for each route in each worker. Composing on every request is what a runtime that boots for each request forces, and a worker does not.
Middleware order
The route table
FastRoute matches a path against patterns and answers found, not found or method not allowed. It does not hold routes in a form anything else can read, and it cannot run backwards. Since every anchor and form action is generated, the engine will own the route table, and compile FastRoute's dispatch data from it.
Matching a request
The router will be a Handler. It will match the request, then delegate:
| Outcome | Result |
|---|---|
| Found | The route's pipeline runs, wrapping the handler behind the route. |
| Not found | A 404 status, with its presentation left to whatever renders errors. |
| Method not allowed | A 405 status, with an allow header listing the methods the path accepts. |
HEAD will be served by the matching GET route, with the body suppressed when the response is emitted. Paths will be
case sensitive, and a path that differs from its canonical form only by a trailing slash will redirect to the canonical
form rather than match. Parameters will be extracted as strings; turning one into an entity belongs to whatever
consumes the route.
Each route will belong to a panel context, and each context will map to a URL prefix. The prefixes will come from configuration rather than code, since the panel decides its own URL shape.
Generating links
Generation will not be a service. The catalogue will look a route up by name, and the route will substitute parameters into its own pattern, validating them against its own constraints. A missing or invalid parameter will throw rather than produce a broken link.
$catalogue->get('server.show')->path(['server' => $id]);
An absolute URL Absolute URLs will not be built here. The scheme and host will come from configuration rather than from the current
request, so a link generated in a queued job will match one generated in a request, and whatever needs an absolute URL
will combine the two.
Errors
A middleware may catch what it wraps, but the pipeline will catch nothing, and neither will the router. Turning an
exception into a response belongs to whatever handles errors, and containing one belongs to whatever drives the
the worker.
Out of scope
- The worker loop. Booting the framework and running it, with drivers for HTTP, the command line and the queue, belongs to bootstrapping. Anything serving every driver is not an HTTP concern.
- Errors and diagnostics. Turning exceptions into responses, logging and error pages serve every driver too.
- Views. Templates, layouts and fragment rendering produce the body this layer emits.
- Actions. The module-facing layer sits on the other side of the handler seam, and owns how HTTP methods are used, how parameters become entities, and what a result maps to.
- Sessions. They own a table, a store and an expiry policy. Their cookies are transported here.
- Route authoring. Routes arrive from the action registry; this design defines the shape they arrive in.
- Body decoding and content types. Decoding a body and deciding a content type belong to what consumes and produces it.
- Cross-origin handling, method override, and built-in middleware. There is no cross-origin consumer, how methods are used is decided where actions are defined, and the middleware that exist arrive with what needs them.
- Modules contributing middleware or routes, which is a collector in the module system.
Alternatives considered
The decisions this This design rests on are recorded separatelyfour decisions, each recorded with the alternatives each one it rejected:
Using FastRoute's route collection as the route table. We I rejected this because it cannot can neither be read back or nor run
backwards, and generation needs both.
FastRoute's file-backed cached dispatcher. We I rejected this because the worker already holds the compiled form in
memory, so a file would add a staleness problem for no gain.
Composing every pipeline at boot. We I rejected this because which middleware apply to a route depends on the route
matched.
No other alternatives were weighed.
Backwards compatibility
Nothing will break. The engine has no HTTP layer today.
Open questions
Resolved questions
Where the panel context is defined
Routing needs it, and it is currently defined inside the module system's collector work. It has to be promoted somewhere shared before routing can consume it.
Changelog
- : Where the panel context is defined is resolved by RFC-0015.
- : Reworded in the readable house style, and the project's own vocabulary linked to the glossary. The design is unchanged.
- : Rewrote the document in full, with no change to the design.
- : Moved where the panel context is defined to Resolved questions, answered by RFC-0015.
Sources
- Issue #62, Engine - HTTP, , edited through and with four comments: the scope stopping at the handler seam, the runtime it assumes, bespoke messages, the server-rendered frontend, the route table being owned rather than borrowed from FastRoute, what each excluded epic is, and the panel context remaining unsettled. Its edits narrow the scope, moving the worker loop and error handling to bootstrapping and sessions to their own component, and replace citations of closed issues with the content stated directly.
- Issue #64, Engine - HTTP - Messages, , edited on to state content directly: every member of a request and where it comes from, hydration from the superglobals and an explicit constructor, the raw body, the absence of an attribute bag, client address resolution, the response factories, the status enum, streamed bodies through a writer, the collections, and emission.
- Issue #65, Engine - HTTP - Middleware pipeline, , edited on , with a comment removing module
contribution: the handler and middleware contracts, composition, short-circuiting, the two composition points and
the route pipeline kept for the life of the worker, ordering across the three sources with earliest-position
deduplication and no priorities, and
Processlifetime. - Issue #66, Engine - HTTP - Routing, , edited on to state content directly: the owned route
table, the registry sealed into a catalogue indexed by name, what a route carries, routes as a projection of the
action registry, the three matching outcomes,
HEAD, case sensitivity, trailing-slash redirection, parameters as strings, contexts and their configured prefixes, generation from the route itself, absolute URLs left to their consumer, and compilation once at boot.
Source rfc/0010-http-transport.md · commit 9444a99 · published