Skip to content

Commit 4d7d661

Browse files
authored
feat: Support streaming request bodies (#131)
* feat: Support streaming request bodies Handlers implementing StreamingRequestHandler receive the request body unread as an InputStream, decoded lazily under the existing size cap, or raw via StreamingRequestHandler.raw(...). Parameters, security and body presence are still checked before the handler runs. Also: Content-Type media ranges (type/*, */*) and a missing Content-Type are matched against requestBody.content; Request.headers() lists all headers; Builder.maxConcurrentStreamingRequests(...) caps concurrent streaming requests with a 503 + Retry-After. * feat: Separate decompression cap for streamed bodies Builder.maxDecompressedStreamingRequestBytes(long) caps the decoded size of a body read by a StreamingRequestHandler with any positive long, so decoded streams are no longer held to the 2 GiB that bounds a buffered body. Unset, it defaults to maxDecompressedRequestBytes. * docs: Point streaming cap references at the new setting Javadoc and README now name maxDecompressedStreamingRequestBytes where streamed bodies are concerned. Adds an IT holding a streaming extra route to the streaming cap, with the setters in reverse order. * refactor: Use a stream in validateStreamingWiring
1 parent ea5df84 commit 4d7d661

25 files changed

Lines changed: 3141 additions & 76 deletions

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Key abstractions:
4141
- `com.retailsvc.http.validate.DefaultValidator` — single class using `switch` pattern-match over `Schema` subtypes. Validation failures produce RFC 9457 `application/problem+json` 400 responses.
4242
- `com.retailsvc.http.internal.Router` — two indexes: exact path map and templated path list. Resolves `operationId` + extracted path variables for each request.
4343
- `TypeMapper` — per-media-type request parsing and response writing; registered via `Builder.bodyMapper(...)`, with `GsonTypeMapper` auto-registered when Gson is on the classpath.
44-
- `com.retailsvc.http.Request` — an immutable record-like carrier built from primitives (body bytes, path parameters, raw query string, a header lookup function), never the `HttpExchange`. `bytes()` returns the decoded body, `parsed()` the object produced by the `TypeMapper`.
44+
- `com.retailsvc.http.Request` — an immutable record-like carrier built from primitives (body bytes, path parameters, raw query string, a header lookup function), never the `HttpExchange`. `bytes()` returns the decoded body, `parsed()` the object produced by the `TypeMapper`. A handler that implements `StreamingRequestHandler` instead gets the body unread: `RequestPreparationFilter` routes first, validates parameters, peeks one byte, and binds `Request.streaming(...)`, whose `bodyStream()` decodes lazily (`internal/DecodingInputStream`) under its own `long` size cap (`maxDecompressedStreamingRequestBytes`, defaulting to the buffered one), or not at all when the handler's `decodeContent()` is false; `bytes()` / `parsed()` throw. `internal/StreamingLimit` optionally caps concurrent streaming requests server-wide (503 + `Retry-After`). `internal/RequestContentType` matches `Content-Type` against `requestBody.content` for both paths.
4545
- `com.retailsvc.http.ContentCoding` — a pluggable HTTP content coding. gzip is built in (`internal/GzipCoding`); callers register others on the builder, held per direction in `internal/ContentCodings`. `RequestBodyReader` decodes requests under the size cap and `ResponseRenderer` codes responses. See the README's "Content encoding" section for the policy.
4646

4747
## Conventions

‎README.md‎

Lines changed: 160 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ endpoints declared in an OpenAPI 3.1.x specification. Handlers are pure function
2828
- [After-response hooks](#after-response-hooks)
2929
- [Security](#security)
3030
- [Request body content types](#request-body-content-types)
31+
- [Streaming request bodies](#streaming-request-bodies)
3132
- [Error responses (RFC 9457)](#error-responses-rfc-9457)
3233
- [Extra (non-OpenAPI) handlers](#extra-non-openapi-handlers)
3334
- [Health endpoint](#health-endpoint)
@@ -49,6 +50,8 @@ endpoints declared in an OpenAPI 3.1.x specification. Handlers are pure function
4950
- OpenAPI `securitySchemes` and `security` enforcement (`apiKey`, `http bearer`, `http basic`),
5051
with an opt-out for sidecar / gateway authentication
5152
- RFC 9457 `application/problem+json` validation errors with an `errors[]` array of JSON-Pointers to the failing locations
53+
- Streaming request bodies for uploads of any size, opted into per handler, with an optional cap on
54+
concurrent uploads
5255
- Transparent gzip: request bodies are inflated under a zip-bomb ceiling, responses are compressed
5356
when the client accepts it and the payload is worth it
5457
- Built on the JDK's native `HttpServer` with thread-per-request behaviour using virtual threads
@@ -494,7 +497,9 @@ OpenApiServer.builder()
494497
```
495498

496499
Note this bounds the *inflated* size of a coded body, whatever the coding. It is not a request size
497-
limit — a body that arrives uncompressed is read in full, as it always has been.
500+
limit — a body that arrives uncompressed is read in full, as it always has been. For a
501+
[streaming handler](#streaming-request-bodies), the cap is enforced as the handler reads, and
502+
[can be set separately](#a-separate-cap-for-streamed-bodies), past 2 GiB.
498503

499504
**Responses.** A body is gzipped when the client sends `Accept-Encoding: gzip`, the media type is
500505
text-shaped (`text/*`, `application/json`, `application/xml`, `application/yaml`, and the `+json` /
@@ -537,7 +542,8 @@ OpenApiServer.builder()
537542

538543
The client's weights pick the coding; on a tie, registered codings win over gzip, in registration
539544
order. `decode` and `encode` wrap streams rather than whole bodies, so a decoder that reads lazily
540-
is held to `maxDecompressedRequestBytes` without doing anything itself. `requestContentCoding` and
545+
is held to `maxDecompressedRequestBytes` (or, for a streaming handler,
546+
`maxDecompressedStreamingRequestBytes`) without doing anything itself. `requestContentCoding` and
541547
`responseContentCoding` register one direction only; a request coded with a response-only coding
542548
gets 415. Tokens must be lower-case, and `gzip`, `x-gzip`, `identity` and `*` are reserved.
543549

@@ -964,6 +970,156 @@ Coercion failures surface as RFC-9457 `400` responses with a JSON-pointer to the
964970
Both built-in parsers honour the `charset=` parameter on the `Content-Type` header (default
965971
UTF-8). Unknown charsets fall back to UTF-8.
966972

973+
### Matching the declared media types
974+
975+
The request's media type is matched against the keys under `requestBody.content`, ignoring case.
976+
The most specific declaration wins: the exact type, then a `type/*` range, then `*/*`. The matched
977+
key decides the schema; the parser is still picked by the request's own media type (falling back
978+
to one registered for the range itself), so `text/*` with a `text/plain` request uses the built-in
979+
text parser.
980+
981+
A request without a `Content-Type` is read as `application/json` when the operation declares
982+
`application/json`. Otherwise it is read as `application/octet-stream`, which RFC 9110 lets a
983+
recipient assume, so it is accepted by an operation that declares `application/octet-stream`,
984+
`application/*` or `*/*`.
985+
986+
A body whose media type matches no declaration is answered 400.
987+
988+
## Streaming request bodies
989+
990+
The server reads a request body in full before the handler runs, so the handler gets it as
991+
`bytes()` and `parsed()`. For uploads that should not be held in memory — large files, archives,
992+
anything passed straight on to storage — register a `StreamingRequestHandler` instead. The handler
993+
then reads the body as it arrives:
994+
995+
```java
996+
StreamingRequestHandler upload =
997+
request -> {
998+
try (InputStream in = request.bodyStream()) {
999+
storage.write(request.pathParam("id"), in);
1000+
} catch (IOException e) {
1001+
throw new UncheckedIOException(e);
1002+
}
1003+
return Response.accepted();
1004+
};
1005+
1006+
OpenApiServer.builder()
1007+
.spec(spec)
1008+
.handlers(Map.of("uploadFile", upload, "getFile", getFile))
1009+
.build();
1010+
```
1011+
1012+
The handler's type is the opt-in, so one operation can stream while the rest of the spec is
1013+
buffered. It works for [extra routes](#extra-non-openapi-handlers) too. Memory per request no
1014+
longer depends on the size of the body.
1015+
1016+
What still runs before the handler:
1017+
1018+
- Routing, and path / query / header parameter validation.
1019+
- A one-byte peek at the body, so that an empty body is told from a present one. As when buffered,
1020+
an empty body fails a `required: true` request body with 400, and a present body must have a
1021+
`Content-Type` declared under the operation's `requestBody.content`. No `TypeMapper` is needed
1022+
for it.
1023+
- [Security](#security). A request that fails any of these checks is answered with one byte of
1024+
its body read — for a coded body, one *decoded* byte, so the coding's header and first buffer.
1025+
- The [concurrency cap](#limiting-concurrent-streaming-requests), if one is set.
1026+
- Interceptors, response decorators and after-response hooks, as for any handler.
1027+
1028+
What changes:
1029+
1030+
- **The body is not validated against its schema**, because it is never parsed. Declare it as
1031+
`type: string, format: binary` (or whatever documents it best) and check the content yourself.
1032+
- **`bytes()`, `parsed()` and `asPojo()` throw** `IllegalStateException`. `request.isStreaming()`
1033+
tells interceptors and hooks that log or inspect bodies to keep away from them.
1034+
- **The stream can be read once, and only inside `handle()`**, on the request thread. Once the
1035+
handler returns, the response is sent and the exchange closed. A body the handler leaves unread
1036+
is drained up to 64 KiB (the JDK's `sun.net.httpserver.drainAmount`); past that, the connection
1037+
is closed rather than reused.
1038+
- **A `Content-Encoding` is decoded as the handler reads**, capped by
1039+
[`maxDecompressedRequestBytes`](#content-encoding) unless a
1040+
[streaming cap](#a-separate-cap-for-streamed-bodies) is set. Going over the cap, or a body that
1041+
fails to decode, surfaces from `read` as a `BadRequestException` (413 or 400). The client
1042+
dropping the connection surfaces as the plain `IOException` it would be for an uncoded body.
1043+
Let it propagate and the `ExceptionHandler` renders it as usual. By then the handler may
1044+
already have passed earlier bytes on, so write to storage in a way you can abandon, such as a
1045+
resumable upload you finalise only after the last read. The handler sees no `Content-Encoding`
1046+
and no `Content-Length` for a decoded body.
1047+
- **An uncoded body has no size limit.** Bound it yourself if you need to, for example by counting
1048+
as you read, and bound how many run at once with
1049+
[`maxConcurrentStreamingRequests`](#limiting-concurrent-streaming-requests).
1050+
1051+
`request.headers()` lists every header with all of its values, for example to store them
1052+
alongside the body. It works for any handler, streaming or not.
1053+
1054+
Tests can build a streaming request directly with `Request.streaming(InputStream, ...)`. For
1055+
buffered requests, `bodyStream()` returns a fresh stream over `bytes()`, so a helper that reads a
1056+
stream works for both.
1057+
1058+
### A separate cap for streamed bodies
1059+
1060+
`maxDecompressedRequestBytes` bounds buffered bodies too, which are held in a `byte[]`, so it
1061+
can't go above 2 GiB. A streamed body is never held in memory, so it can have a cap of its own,
1062+
any positive `long` — higher than the buffered one, or lower:
1063+
1064+
```java
1065+
OpenApiServer.builder()
1066+
.spec(spec)
1067+
.handlers(handlers)
1068+
.maxDecompressedRequestBytes(32 * 1024 * 1024) // buffered: 32 MiB
1069+
.maxDecompressedStreamingRequestBytes(50L * 1024 * 1024 * 1024) // streamed: 50 GiB
1070+
.build();
1071+
```
1072+
1073+
Left unset, streamed bodies share `maxDecompressedRequestBytes`. It covers decoded bodies only;
1074+
uncoded and [raw](#raw-bodies) bodies have no cap either way.
1075+
1076+
### Raw bodies
1077+
1078+
To store or forward a body exactly as the client sent it, wrap the handler in
1079+
`StreamingRequestHandler.raw(...)`, or override `decodeContent()` to return `false`:
1080+
1081+
```java
1082+
.handlers(Map.of("uploadFile", StreamingRequestHandler.raw(upload)))
1083+
```
1084+
1085+
The handler then reads the coded bytes. `Content-Encoding` and `Content-Length` are visible as
1086+
sent. Neither decompression cap applies, and a coding the server doesn't know is passed on
1087+
instead of being answered 415.
1088+
1089+
### Limiting concurrent streaming requests
1090+
1091+
Memory no longer bounds how many uploads a server takes on, so cap them instead:
1092+
1093+
```java
1094+
OpenApiServer.builder()
1095+
.maxConcurrentStreamingRequests(150) // Retry-After: 1
1096+
.maxConcurrentStreamingRequests(150, Duration.ofSeconds(5)) // or choose the Retry-After
1097+
```
1098+
1099+
The cap counts requests to streaming handlers across every spec and extra route. A request takes a
1100+
slot once it has passed validation and security, just before interceptors and the handler run, and
1101+
gives it back once its response is sent — whether the handler returned or threw. So a client that
1102+
is slow to send its body, or isn't authenticated, never holds a slot.
1103+
1104+
A request over the cap is answered `503 Service Unavailable` with `Retry-After` and an
1105+
`application/problem+json` body. Its body is left unread, and interceptors and the handler don't
1106+
run. After-response hooks do see the 503, so one can count shed requests:
1107+
1108+
```java
1109+
.afterResponseHook((request, response) -> {
1110+
if (response.status() == 503 && response.headers().containsKey("Retry-After")) {
1111+
shed.increment();
1112+
}
1113+
})
1114+
```
1115+
1116+
A client that sends `Expect: 100-continue` has already been told to send its body by the JDK server
1117+
before any of this runs, so a rejected upload may still arrive until the server stops draining it
1118+
(see the unread-body note above).
1119+
1120+
Buffered requests aren't counted, so health probes and ordinary API calls keep being answered while
1121+
uploads are shed. The cap is unlimited by default.
1122+
9671123
## Error responses (RFC 9457)
9681124

9691125
Validation failures — missing required fields, type mismatches, unsupported content types,
@@ -1316,4 +1472,5 @@ A few things worth keeping in mind when reading this:
13161472
- **Per-request state uses `ScopedValue`** (Java 25, JEP 506). This matters if a handler
13171473
offloads work to an executor that's not a `StructuredTaskScope`-managed child thread: the
13181474
`ScopedValue` is not visible there, so the handler must capture the values it needs (e.g.
1319-
`byte[] body = request.bytes();`) before submitting.
1475+
`byte[] body = request.bytes();`) before submitting. A streamed body can't be handed off this
1476+
way at all: read it before `handle()` returns.

0 commit comments

Comments
 (0)