Skip to content

Latest commit

 

History

History
304 lines (258 loc) · 23.1 KB

HTTP_ASSETS.md

File metadata and controls

304 lines (258 loc) · 23.1 KB

HTTP asset encoding

HTTP asset negotiation and fallback apply to every frontend and to custom filesystem providers.

The server handles one HTTP request per connection and announces Connection: close on ordinary responses, as required by RFC 9112 §9.3; it does not implement HTTP keep-alive. WebSocket upgrades retain Connection: Upgrade and their ongoing read/write loops. Each response owns its status line until its asynchronous send completes, independently of other pending responses.

Application providers generated by wf embed and custom filesystem providers can serve gzip resources. The core assets are identity representations; see the current inventory in Embedded assets. If a client does not accept gzip, the HTTP server decodes the asset and serves identity with the decoded Content-Length and no Content-Encoding. Encoded responses carry Vary: Accept-Encoding; explicit q=0 exclusions are respected. Duplicate mentions accept a coding if any valid mention accepts it, regardless of their order or which field contains them: gzip;q=0, gzip and gzip, gzip;q=0 both accept gzip. Coding names use locale-independent ASCII case folding. x-gzip is an alias of gzip in preferences and stored assets, as specified by RFC 9110 §8.4.1.3. Alias mentions share the same explicit preference, including exclusions and duplicate merging; pass-through retains the stored coding label. Explicit coding mentions still override *. Unknown parameters are ignored; malformed qvalues, including q=.5 (use q=0.5), reject only that mention.

Decoding validates gzip headers, DEFLATE blocks, CRC32 and uncompressed sizes, including concatenated members, with a 4 MiB default total output limit. Any trailing bytes after the final member, including zero padding, are rejected. Fallback decoding failures or an exceeded limit return HTTP 500. If neither the stored coding nor identity is acceptable, or a custom provider uses an unsupported coding (such as Brotli) the client does not accept, the server returns HTTP 406. Custom codings can still be served directly to accepting clients.

Streaming and dynamic routes (#454)

An unencoded file whose size is known (fs::File::knownSize(): embedded data, or a native file on a seekable stream) is announced with its Content-Length and sent in chunks of emissionBufferSize bytes, each read on the server's worker thread and sent before the next is read: memory does not depend on the file's size, and HEAD reads nothing. Encoded files are still read whole, since the coding negotiation and the gzip fallback need them. A failure after the status line (a read error, a closing connection) cannot change the status: the connection is closed, which the client sees as a truncated body.

app.addRoute(prefix, handler) answers GET and HEAD under an absolute prefix ending with / with an http::RouteReply produced at run time: status, headers, an exact contentLength (unset: the body ends when the connection closes) and a body callback filling the next chunk (0 ends it). The handler and the callback run on the worker thread, so a slow disk does not delay other connections. Route work runs on its own pool of 4 threads and the files of the providers on another of 2: a handler that blocks for seconds delays at most the routes queued behind four such handlers, never WebFront.js or a page. A route precedes the file providers, never masks the embedded WebFront.js, and overlapping prefixes are refused when registered. Other methods get 405; a handler that throws, or sets a header that could split the response or that the server owns (Content-Length, Connection, Transfer-Encoding), gets 500. The registration handle removes the route when destroyed; a request already running keeps its handler. The binding of a request to a connection (#469) is not part of this mechanism yet.

app.addRoute(prefix, handler, http::RouteOptions{.postBodyLimit = n}) also answers POST (#619), for a small request such as a JSON-RPC call: the body, announced by Content-Length and at most n bytes, is read whole before the handler runs and reaches it as RouteRequest::body. Expect: 100-continue gets 100 Continue first. The server refuses, without calling the handler, a POST without Content-Length (411), with a Transfer-Encoding (501: no chunked bodies), with a malformed or contradictory length (400; spaces around the value and a list of equal lengths such as 5, 5 are accepted) or a longer body (413); a connection that ends before the announced length is closed without an answer. 100 Continue goes only to an HTTP/1.1 client whose Expect lists 100-continue (alone or among other comma-separated tokens, compared without case), and not when the body is already there or the request is refused. Such a route lists POST in the Allow header of its 405. There is still one request per connection, and no check of the origin of the request: a route that changes state verifies it, with a token or the Origin header.

Limits: the server has no timeout on reading the headers or the body, so a slow client holds its connection and the bytes received so far (at most n); size n for the smallest request the route needs. A refusal sent while the client is still sending its body can reach it as a connection reset instead of the status, since the unread body is not drained.

Secret path segments (#673)

The server logs every request with its path (never its query). An application whose URLs carry a capability, such as a session identifier that is enough to drive the session (/s/<id>/), declares the prefix that precedes it with app.addSecretPrefix("/s/"): the segment that follows the prefix is then never written to WebFront's logs, for a file, a route, a WebSocket upgrade and the warnings of a failure alike. The request is logged as /s/*/index.html, and the error message of a handler, a body or a file provider serving such a path, which may quote it, is not logged. The path is judged as the server reads it (percent-decoded, empty and . segments dropped, in any letter case); prefixes may overlap (/s/ and /s/<id>/files/ mask both segments), and a declaration lasts as long as the application. The prefix is not a route: it changes nothing in what is served. A family of spaces (app.spaces, docs/SPACES.md) always masks its segment in this way, and a secret prefix also covers the prefix of a family and the paths within a space as it reads them; http::RouteOptions::secretPath masks the whole rest of a path, under /webfront/services/ only. The application's own logs are its business.

Byte ranges (#455)

An unencoded file of known size, from any provider, is served by ranges (RFC 9110 §14) and says so with Accept-Ranges: bytes. A single Range: bytes=a-b, a- or -n answers 206 Partial Content with Content-Range and the length of that part; only those bytes are read, on the worker, in chunks of emissionBufferSize (the file positions itself with fs::File::seek). A range that starts at or past the end, an empty suffix (-0), or any range of an empty file answers 416 with Content-Range: bytes */size; a last byte past the end is clamped, and a suffix longer than the file selects all of it. Range is defined for GET only (RFC 9110 §14.2): a HEAD ignores it and describes the whole file, without a body.

What the server may ignore, it ignores, and the answer is a normal 200 with the whole file: several ranges (in one field or several), a unit other than bytes, a malformed or inverted range (5-2), and a Range on a response that cannot be ranged. Multipart answers (multipart/byteranges) are not produced. The responses of encoded files (served as stored with Content-Encoding, or decoded by the gzip fallback) carry Accept-Ranges: none and are never partial, like files whose size is unknown.

If-Range conditions a range on a validator, and only a strong entity tag is compared. WebFront derives none itself: a pathname, a size or a modification time can describe another version than the stream that was opened (a replacement between the open and the lookup, a rewrite that keeps the time), and a tag that is wrong would let a client join bytes of two versions. A provider whose storage is versioned (a content hash, a revision) gives its tag with fs::File::setEntityTag, which must change whenever the bytes change; it is sent as ETag on the 200 and 206 responses. Native files of NativeDebugFS and the development root, and embedded data, have no tag: a conditioned range is answered in full, while an unconditioned Range is still served. The server sends no Last-Modified, so a date in If-Range never matches (and a browser applies no heuristic freshness to development files).

A dynamic route that serves a file, such as the services built on #454, calls http::fileReply(request, file, contentType): it applies the same rules to the route's RouteRequest::request and returns the RouteReply (200, 206 or 416) that the handler completes with its own headers (Cache-Control, Content-Disposition...); the Referrer-Policy and X-Content-Type-Options of the content policy are added to a reply that does not set them. A handler with its own storage can use http::range::select(request, size, entityTag) directly. A file with a stored coding is sent as stored, with Content-Encoding and Vary: Accept-Encoding, in full and with Accept-Ranges: none; a client that does not accept the coding gets a 406, because fileReply does not decode. The read-only reply is repeatable: successive range requests on one URL each open the file again.

Validated representation cache

Each server owns a bounded LRU cache through its RequestHandler. It is destroyed after server tasks have drained, with no global state, background work or extra shutdown join. A copied handler starts with an empty cache; applications never implicitly share entries. The server context serializes filesystem access and cache access; worker threads receive owned compressed bytes and never call a provider or touch an I/O object.

Keys contain the complete compressed bytes, rather than a pathname, borrowed pointer, modification time, checksum alone or unvalidated ISIZE trailer. Every request still opens and reads the provider. Changed bytes at the same path cause a new validation; identical bytes at different paths or with the x-gzip alias share an entry. A custom provider needs no revision API, but must keep its backing storage valid and stable throughout each read. Older revisions remain eligible for LRU eviction; returning to exactly those bytes is safe.

Only successful full gzip validation creates an entry. It stores decoded content and thus its validated length. GET reuses the content; HEAD reuses its length without copying decoded content into the response. Each hit checks the current decoded output budget. Corrupt streams and over-budget failures are never cached as successful representations. Pass-through and 406 negotiation do not access the cache.

The default retention budget is 8 MiB per server, allocated lazily. LRU eviction accounts for both compressed and decoded string capacities plus their terminators, entry metadata and two list links. Allocator bookkeeping is implementation-dependent and excluded. The fixed cache object and counters, provider storage, request/response buffers and temporary cold decoding allocations are outside this retention budget. Admission may temporarily construct one additional entry before eviction, bounded by the same budget; the output limit separately bounds cold decoded bytes. A representation too large to retain is still validated and served under the output budget, without evicting useful entries; repeated requests decode it again. There is no separate length-only cache for oversized HEAD responses.

Set maxDecodedAssetCacheSize on the buffer policy (or the sixth CustomBuffersPolicy argument) to change retention. The retention budget is captured at handler construction; the decoded output budget is read for every fallback request. Zero retention disables caching, including HEAD metadata. Policies without this member inherit 8 MiB. For the synchronous API, RequestHandler::fallbackCacheStatistics() exposes decode attempts, hits (including budget-rejected hits), entries and accounted retained bytes; read it on the server context. The LRU lookup compares compressed bytes linearly across retained entries; gzip pass-through remains independent of this cost. Cold decoding uses bounded buffered bit reads and a 256-entry short-code Huffman lookup, with the canonical decoder for longer codes. Validation, budgets and strict member/trailer boundaries are unchanged. Optional manual benchmarks measure codec/cache costs.

Cold decoding, admission and shutdown (#283)

http::Server sends cache misses to a single CPU worker, created lazily on the first admitted miss. Plain files, gzip/x-gzip pass-through and warm cache hits create no worker. A server which never needs cold fallback pays for the small executor state, with no thread or reserved payload buffers. The explicit low-level RequestHandler::handleRequest API remains synchronous; server connections use prepareRequest, the executor sender and finish instead.

Filesystem opens/reads, negotiation, cache lookup/publication and response construction run on the server I/O context. The worker only validates/decodes owned bytes. The sender explicitly resumes through the connection's network scheduler. Identical in-flight compressed bytes with the same captured output limit share one job, including GET/HEAD consumers and oversized cache entries. Different output limits use separate jobs, so a failed smaller decode cannot poison a larger one. The output budget is checked again on completion. Completed worker data can serve followers until its last response lease is released. Work skipped after cancellation or interrupted by a decoder exception is excluded from coalescing; a later request retries validation. Failures never become valid cache entries.

Defaults, captured at server construction, are optional buffer-policy members:

Member Default Meaning
maxGzipDecodeJobs 4 distinct active, queued or completed revisions whose responses still hold a lease
maxGzipDecodeWaiters 16 accepted identity responses, including coalesced requests and cache hits, until send completion
maxGzipDecodeBytes 64 MiB reserved compressed, decoded and response string capacities including terminators
maxGzipEncodedAssetSize 4 MiB compressed bytes read for a gzip identity fallback request

A new job reserves a decoded string up to its captured output limit; every GET also reserves a response buffer up to that limit, regardless of the actual asset size. With the default 4 MiB output limit, one cold GET reserves at least 8 MiB plus its compressed key and terminators; each coalesced GET reserves another 4 MiB. Raising the output limit to 32 MiB prevents a cold GET from fitting the default 64 MiB budget even for a tiny asset. Tune the output and worker byte limits together. HEAD reserves no decoded response body. Reservation happens on the I/O thread before submission, so the worker fills preallocated storage without growing it. Actual string capacities are charged, including compressed revision keys. Cache hits reserve the actual response capacity. Completed jobs and slow sends keep their reservations; completing CPU work does not free budget that a response still owns. Cache retention has its separate 8 MiB budget. Fixed executor state, bounded queue/waiter metadata, decoder stack and allocator bookkeeping are outside the payload budget. One serial I/O preparation/admission buffer is also outside it; the compressed-input limit and decoded/cache limits bound that temporary buffer. Provider-owned storage and ordinary HTTP/pass-through connection buffers retain their existing contracts; these settings do not impose a global HTTP connection limit.

Exceeding the jobs, waiters or byte admission limits, or an allocation failure during request preparation/admission, returns 503 Service Unavailable, with Vary: Accept-Encoding; there is no unbounded waiting queue or silent synchronous fallback. Rejected or cancelled compressed input is released before posting its I/O completion. Zero jobs disables cold admission; zero waiters/bytes disables gzip identity-fallback admission. Gzip pass-through is unchanged. The compressed-input cap is deterministic: exceeding maxGzipEncodedAssetSize returns 500 Internal Server Error, including HEAD and assets previously validated through the synchronous handler. The cap is enforced while reading, before cache lookup, so retention cannot bypass it. This introduces a default 4 MiB compressed-input ceiling for server identity fallback; raise the policy limit for larger assets. Gzip pass-through remains unrestricted by this cap. For admitted work, malformed streams and exceeded decoded output budgets return 500; incompatible negotiation still returns 406. Limits are also checked for HEAD. The worker count is fixed at one per server; applications tune queued work and memory through the policy, without creating detached threads or a process-global pool.

Cancellation is local and observed before starting a queued job and at completion. Cancelling one consumer does not cancel other consumers. A queued job whose consumers have all requested local cancellation is skipped. Queued cancellation completes when that job is serviced; an active decode ahead of it can delay cancellation delivery and slot release. An active decode is not interruptible and must finish; the byte limit is not a wall-clock deadline. A disconnected peer is detected by the eventual send, rather than a parallel socket read while decoding; its work remains owned and bounded until completion. Slow peers can exhaust the bounded response slots and cause 503 responses to later identity requests.

stop() closes admission and requests task cancellation from any thread. After external run() callers return, drain()/destruction joins the worker first, then pumps the I/O context and joins the task scope, retaining all connection/response dependencies until then. The executor never closes a socket from its thread. An active non-interruptible decode can delay this join; queued jobs are stopped without decoding. fallbackDecodeStatistics() exposes atomic counters for jobs, response leases, charged bytes, decode attempts and whether a worker has been created. Server::fallbackCacheStatistics() combines I/O-context cache counters with worker decode attempts; read cache statistics on the I/O context. Buffered decoding reduces cold CPU work; see manual benchmarks.

Fallback budget

The limit applies to the sum of decoded bytes across all gzip members, for GET and HEAD. Gzip pass-through to an accepting client does not use this budget. A smaller budget reduces the work and memory a fallback request can consume, but it is not a wall-clock deadline. Applications can override decoding and retention through their buffer policy:

#include <webfront/WebFront.hpp>
#include <cstddef>

struct AppBuffers : webfront::http::DefaultBuffersPolicy {
    static constexpr std::size_t maxDecodedAssetSize = 1024 * 1024;
    static constexpr std::size_t maxDecodedAssetCacheSize = 2 * 1024 * 1024;
};
using App = webfront::BasicWF<webfront::NetProvider, webfront::fs::DefaultFS, AppBuffers>;

CustomBuffersPolicy also accepts the limit as its fifth template argument. Policies without maxDecodedAssetSize inherit the default. Zero permits only empty decoded assets. An asset exceeding a smaller custom budget returns 500 when identity is needed; gzip pass-through is unchanged. Caching avoids repeated decoding; the worker keeps cold decoding off the I/O context. Filesystem reads remain synchronous on that context.

Manual benchmarks and differential validation

With a CEF-off Release test build configured, build the optional tools explicitly. gzip_decoder_benchmark is unavailable when WEBFRONT_ENABLE_SANITIZER_THREAD=ON; use a build with ThreadSanitizer disabled for the commands below:

cmake --build build --target gzip_cache_benchmark gzip_decoder_benchmark --parallel 2
build/test/unit/gzip_cache_benchmark
python3 test/fuzz/GenerateGzipCorpus.py build/gzip-corpus
build/test/unit/gzip_decoder_benchmark build/gzip-corpus/*.gz

The corpus directory must be new. The generator accepts an optional second argument naming an application bundle to compress, and prints sizes and SHA-256 checksums. Compression depends on the local Python/zlib version; generated test inputs do not change the core's identity assets.

The cache benchmark exercises the synchronous RequestHandler with in-memory compressed providers, including negotiation, decoding and cache lookup. CSV reports cold/repeated GET/HEAD costs, decode counts and retained bytes with retention enabled and disabled. An optional argument supplies a complete gzip asset below the default 4 MiB decoded limit. Network I/O, browser work and filesystem latency are excluded; this does not measure worker scheduling.

The decoder benchmark checks decoded bytes and reports time, throughput and allocation totals for fresh and pre-reserved output. It always includes the three neutral fixtures. It excludes HTTP, cache lookup and worker admission. Generated near-budget codec inputs can exceed the server's separate compressed-input cap. Allocated-byte totals are cumulative requests, not peak RSS; cache retention also excludes transient response/decoder storage and allocator bookkeeping.

These targets are excluded from normal builds and CTest and impose no timing threshold. For comparisons, use the same harness, compiler, hardening and corpus on both revisions; alternate run order and record host/cache conditions. Earlier cache measurements (#281) and decoder measurements (#282) remain available at cce1927, the last revision containing those reports.

-DWEBFRONT_GZIP_DIFFERENTIAL=ON enables test-only zlib linkage; production stays header-only without a zlib dependency:

cmake -S . -B build -DWEBFRONT_GZIP_DIFFERENTIAL=ON
cmake --build build --target gzip_differential --parallel 2
build/test/unit/gzip_differential build/gzip-corpus
ctest --test-dir build -R GzipZlibDifferential --output-on-failure

The oracle handles concatenated members and requires full consumption. Generated supported streams compare acceptance and exact content in both directions, including budgets, truncation, mutation, optional headers, CRC and trailing bytes. Arbitrary-input fuzzing checks every stream WebFront accepts against zlib. WebFront intentionally rejects trailing padding (even zeros) and dynamic declarations of 31/32 distance symbols; malformed-input unit fixtures cover these rules. See fuzzing for sanitizer and bounded differential-fuzzer commands.