diff --git a/apps/albedo/src/albedo/http/albedo_http_api.erl b/apps/albedo/src/albedo/http/albedo_http_api.erl index 4dae00335..997ecda73 100644 --- a/apps/albedo/src/albedo/http/albedo_http_api.erl +++ b/apps/albedo/src/albedo/http/albedo_http_api.erl @@ -11,7 +11,7 @@ zstd_end/1, zstd_decompress/2, stream_socket/1, - chunked_source/1 + body_source/1 ]). %% The window a frame declares is the memory its decoder must hold: a client @@ -37,12 +37,12 @@ stream_socket({connection, _, Socket, Transport, _}) -> %% The bytes mist buffered past the request head, and a reader for more from %% the same socket, for a body mist has not started reading. -chunked_source({connection, {initial, Buffered}, Socket, Transport, _}) -> +body_source({connection, {initial, Buffered}, Socket, Transport, _}) -> Receive = fun(Amount, Timeout) -> 'glisten@transport':receive_timeout(Transport, Socket, Amount, Timeout) end, {ok, {Buffered, Receive}}; -chunked_source(_) -> +body_source(_) -> {error, nil}. zstd_compress(Data) -> zstd:compress(Data, zstd_params()). diff --git a/apps/albedo/src/albedo/http/http_api.gleam b/apps/albedo/src/albedo/http/http_api.gleam index 630daaeed..d1435201d 100644 --- a/apps/albedo/src/albedo/http/http_api.gleam +++ b/apps/albedo/src/albedo/http/http_api.gleam @@ -112,6 +112,29 @@ pub fn bounded_catalog( |> result.map(fn(items) { list.map(items, fn(item) { item.1 }) }) } +/// A request body, and whether the client had already sent bytes past it. +/// Those bytes are pipelined requests, which mist cannot keep for its next +/// read, so the daemon answers this request and closes the connection. +pub type Body { + Body(bytes: BitArray, pipelined: Bool) +} + +/// A body of exactly `length` bytes, which the caller has checked against its +/// limit. Mist reads a body it has buffered whole as everything after the +/// head, so a buffer longer than the body is split here. +pub fn read_fixed( + req: request.Request(mist.Connection), + length: Int, +) -> Result(Body, mist.ReadError) { + case body_source(req.body) { + Ok(#(<>, _)) if rest != <<>> -> + Ok(Body(body, True)) + _ -> + mist.read_body(req, length) + |> result.map(fn(read) { Body(read.body, False) }) + } +} + /// A chunked request body of at most `limit` bytes. Mist 6's whole-body /// chunked reader does not enforce its byte limit, so this decodes the framing /// itself and refuses an oversized chunk before reading its payload. The whole @@ -119,14 +142,14 @@ pub fn bounded_catalog( pub fn read_chunked( connection: mist.Connection, limit: Int, -) -> Result(BitArray, mist.ReadError) { - case chunked_source(connection) { +) -> Result(Body, mist.ReadError) { + case body_source(connection) { Error(Nil) -> Error(mist.MalformedBody) Ok(#(buffered, receive)) -> { let source = Source(receive, albedo_clock.monotonic_ms() + 15_000) case chunks(source, buffered, limit, []) { - Ok(#(body, <<>>)) -> Ok(body) - Ok(_) | Error(Malformed) -> Error(mist.MalformedBody) + Ok(#(body, rest)) -> Ok(Body(body, rest != <<>>)) + Error(Malformed) -> Error(mist.MalformedBody) Error(TooLarge) -> Error(mist.ExcessBody) } } @@ -352,8 +375,8 @@ fn erlang_binary_match(bytes: BitArray, pattern: BitArray) -> Dynamic /// The bytes mist buffered past the request head and a reader for more, for /// a request whose body mist has not started reading. -@external(erlang, "albedo_http_api", "chunked_source") -fn chunked_source( +@external(erlang, "albedo_http_api", "body_source") +fn body_source( connection: mist.Connection, ) -> Result(#(BitArray, fn(Int, Int) -> Result(BitArray, Dynamic)), Nil) diff --git a/apps/albedo/src/albedo/lifecycle/server.gleam b/apps/albedo/src/albedo/lifecycle/server.gleam index c6b16a4ed..6019a70c0 100644 --- a/apps/albedo/src/albedo/lifecycle/server.gleam +++ b/apps/albedo/src/albedo/lifecycle/server.gleam @@ -561,31 +561,39 @@ fn admitted( Error(refusal) -> refusal Ok(length) -> { let read = case length { - Some(_) -> - mist.read_body(req, admission.body_limit) - |> result.map(fn(read) { read.body }) + Some(length) -> http_api.read_fixed(req, length) None -> { use _ <- result.try(mist.stream(req)) http_api.read_chunked(req.body, admission.body_limit) } } case read { - Ok(body) -> { - let size = bit_array.byte_size(body) - case length, compressed { - Some(length), _ if size != length -> - failure(400, "invalid_request", "invalid request body") - _, False -> next(request.set_body(req, body)) - _, True -> - case http_coding.decompress(body, admission.body_limit) { - Ok(body) -> next(request.set_body(req, body)) - Error(_) -> - failure( - 400, - "invalid_request", - "request body does not decode within its limit", - ) - } + Ok(http_api.Body(bytes: body, pipelined:)) -> { + let answer = { + let size = bit_array.byte_size(body) + case length, compressed { + Some(length), _ if size != length -> + failure(400, "invalid_request", "invalid request body") + _, False -> next(request.set_body(req, body)) + _, True -> + case + http_coding.decompress(body, admission.body_limit) + { + Ok(body) -> next(request.set_body(req, body)) + Error(_) -> + failure( + 400, + "invalid_request", + "request body does not decode within its limit", + ) + } + } + } + // The pipelined requests are gone with the bytes read past + // this one, so the client must resend them on a new connection. + case pipelined { + True -> response.set_header(answer, "connection", "close") + False -> answer } } Error(mist.MalformedBody) -> diff --git a/docs/http-api-design.md b/docs/http-api-design.md index a98e9c1ea..dcca34b00 100644 --- a/docs/http-api-design.md +++ b/docs/http-api-design.md @@ -162,6 +162,9 @@ data frames have a 1 MiB limit. The limits on each OpenAPI operation apply as well. HTTP body framing accepts valid fixed-length and chunked requests, enforcing the same byte limit while reading. Ambiguous framing, unsupported content encoding, and incomplete bodies fail without executing the operation. +The daemon does not process pipelined requests. When a request arrives with +bytes behind it, the daemon answers that request with `Connection: close` and +discards the rest unread, so a client resends them on a new connection. zstd is the one content coding. A JSON or text response of at least 1 KiB is compressed when `Accept-Encoding` admits `zstd`, and so is a session or diff --git a/e2e/daemon_test.py b/e2e/daemon_test.py index bd5f9a803..42448edc9 100644 --- a/e2e/daemon_test.py +++ b/e2e/daemon_test.py @@ -527,6 +527,39 @@ class DaemonTest(unittest.TestCase): (status, 200), ) + def test_pipelined_requests_answer_the_first_and_close(self): + # Mist cannot keep bytes read past a request for its next read, so + # a request sent behind another in one write used to become part of + # the first body: 400 for GET and chunked, 500 for a fixed length. + with Albedo() as app: + token = app.connection["token"] + session = app.session() + address = urllib.parse.urlsplit(app.base) + head = f"Host: {address.netloc}\r\nAuthorization: Bearer {token}\r\n" + get = f"GET /server HTTP/1.1\r\n{head}\r\n".encode() + for name, framing, body in ( + ("get", None, b""), + ("fixed", "Content-Length: 2", b"{}"), + ("chunked", "Transfer-Encoding: chunked", b"2\r\n{}\r\n0\r\n\r\n"), + ): + with self.subTest(name): + if framing is None: + first = get + else: + visit = f"/sessions/{session}/visits/{operation_id()}" + first = ( + f"PUT {visit} HTTP/1.1\r\n{head}" + f"Content-Type: application/json\r\n{framing}\r\n\r\n" + ).encode() + body + with socket.create_connection( + (address.hostname, address.port), timeout=5 + ) as connection: + connection.sendall(first + get) + status, headers, _ = read_response_details(connection) + self.assertEqual(status, 200) + self.assertEqual(headers["connection"], "close") + self.assertEqual(connection.recv(1), b"") + def test_empty_and_incomplete_bodies_are_handled_at_ingress(self): with Albedo() as app: token = {"Authorization": "Bearer " + app.connection["token"]}