diff --git a/lib/ex_aws/bedrock/event_stream.ex b/lib/ex_aws/bedrock/event_stream.ex index 15b973e..d52f47a 100644 --- a/lib/ex_aws/bedrock/event_stream.ex +++ b/lib/ex_aws/bedrock/event_stream.ex @@ -119,7 +119,7 @@ defmodule ExAws.Bedrock.EventStream do &Function.identity/1 ) - Stream.flat_map(stream, &decode_chunk/1) + decode_stream(stream) end @doc """ @@ -164,88 +164,132 @@ defmodule ExAws.Bedrock.EventStream do end end + @uint32_size 4 + @checksum_size 4 + # prelude_length = message_total_length + headers_length + prelude_checksum + @prelude_length @uint32_size * 3 + # message_overhead = prelude + message_checksum + @message_overhead @prelude_length + @checksum_size + # The limits the AWS SDKs enforce on a message. A prelude declaring more is + # rejected up front, so no more than one message is ever buffered. + @max_headers_length 128 * 1024 + @max_payload_length 24 * 1024 * 1024 + + @typep decoded :: {:chunk, map()} | {:bad_chunk, binary(), term()} + @doc false - @spec decode_chunk(binary()) :: list({:chunk, map()} | {:bad_chunk, binary(), term()}) - def decode_chunk(data) do - decode_chunks(data, []) + # Decodes a stream of binaries into event stream messages. + # + # The transport gives no guarantee that a binary holds a whole number of + # messages: a message may be split across any number of binaries. Bytes are + # buffered until the message length declared in the prelude has arrived. + # + # Bytes left over when the stream ends are reported as a bad or incomplete + # chunk. + @spec decode_stream(Enumerable.t()) :: Enumerable.t() + def decode_stream(stream) do + # Runs once, before the first binary: nothing is buffered yet. + empty_buffer = fn -> <<>> end + + # Runs for every binary: emit the whole messages, keep the rest buffered. + decode_binary = fn data, buffer -> decode_messages(buffer <> data, []) end + + # Runs once, after the last binary: report bytes that never made a message. + report_leftover = fn buffer -> {leftover(buffer), <<>>} end + + # Runs last, also when the consumer stops early: nothing to clean up. + no_cleanup = fn _buffer -> :ok end + + Stream.transform(stream, empty_buffer, decode_binary, report_leftover, no_cleanup) end - defp decode_chunks(<<>>, acc), do: Enum.reverse(acc) + # Bytes that do not make up a whole message once there is no more data. + defp leftover(<<>>), do: [] - defp decode_chunks(data, acc) do - case parse_chunk(data) do - {:ok, chunk, rest} -> - decode_chunks(rest, [{:chunk, chunk} | acc]) + defp leftover(rest) when byte_size(rest) < @prelude_length, + do: [{:incomplete_chunk, rest}] - {:error, reason, rest} -> - decode_chunks(rest, [{:bad_chunk, data, reason} | acc]) + defp leftover(rest), do: [{:bad_chunk, rest, :invalid_chunk}] + + # Decodes every complete message in the buffer, returning the bytes of a + # trailing partial message so they can be prepended to the next binary. + @spec decode_messages(binary(), list(decoded())) :: {list(decoded()), binary()} + defp decode_messages(buffer, acc) do + case split_message(buffer) do + {:ok, message, rest} -> + decode_messages(rest, [decode_message(message) | acc]) :incomplete -> - # May wish to buffer incomplete data - [{:incomplete_chunk, data} | acc] + {Enum.reverse(acc), buffer} + + {:error, reason} -> + # The declared length cannot be used so the start of the next message + # is unknown: discard the buffer and resume decoding at the next + # binary, which is assumed to start on a message boundary. + {Enum.reverse([{:bad_chunk, buffer, reason} | acc]), <<>>} end end - @uint32_size 4 - @checksum_size 4 - # prelude_length = message_total_length + headers_length + prelude_checksum - @prelude_length @uint32_size * 3 - # message_overhead = prelude + message_checksum - @message_overhead @prelude_length + @checksum_size - defp parse_chunk( + defp split_message( << message_total_length::unsigned-32, headers_length::unsigned-32, prelude_checksum::unsigned-32, - headers::binary-size(headers_length), - rest::binary - >> = data - ) - when byte_size(data) >= message_total_length do - message_length = message_total_length - @message_overhead - body_length = message_length - headers_length - - if byte_size(rest) >= body_length + @checksum_size do - << - body::binary-size(^body_length), - message_checksum::unsigned-32, - next_data::binary - >> = rest - - prelude = <> - - with :ok <- verify_prelude_checksum(prelude, prelude_checksum), - :ok <- - verify_message_checksum(prelude, prelude_checksum, headers, body, message_checksum), - {:ok, chunk} <- process_chunk(body) do - {:ok, chunk, next_data} - else - {:error, reason} -> {:error, reason, next_data} - end - else - :incomplete + _::binary + >> = buffer + ) do + prelude = <> + + cond do + crc32(prelude) != prelude_checksum -> + {:error, :invalid_prelude_checksum} + + message_total_length < @message_overhead + headers_length -> + {:error, :invalid_chunk} + + headers_length > @max_headers_length -> + {:error, :headers_too_large} + + message_total_length - @message_overhead - headers_length > @max_payload_length -> + {:error, :payload_too_large} + + byte_size(buffer) < message_total_length -> + :incomplete + + true -> + <> = buffer + {:ok, message, rest} end end - defp parse_chunk(data) when byte_size(data) < @prelude_length do - :incomplete - end + defp split_message(_buffer), do: :incomplete - defp parse_chunk(_data) do - {:error, :invalid_chunk, <<>>} - end + defp decode_message( + <<_message_total_length::unsigned-32, headers_length::unsigned-32, _::binary>> = message + ) do + checked_length = byte_size(message) - @checksum_size + body_length = checked_length - @prelude_length - headers_length - defp verify_prelude_checksum(prelude, checksum) do - if crc32(prelude) == checksum do - :ok + << + checked::binary-size(^checked_length), + message_checksum::unsigned-32 + >> = message + + << + _prelude::binary-size(@prelude_length), + _headers::binary-size(^headers_length), + body::binary-size(^body_length) + >> = checked + + with :ok <- verify_message_checksum(checked, message_checksum), + {:ok, chunk} <- process_chunk(body) do + {:chunk, chunk} else - {:error, :invalid_prelude_checksum} + {:error, reason} -> {:bad_chunk, message, reason} end end - defp verify_message_checksum(prelude, prelude_checksum, headers, body, checksum) do - message = prelude <> <> <> headers <> body - + defp verify_message_checksum(message, checksum) do if crc32(message) == checksum do :ok else diff --git a/test/ex_aws/bedrock/event_stream_test.exs b/test/ex_aws/bedrock/event_stream_test.exs index 30c890e..a6e6a16 100644 --- a/test/ex_aws/bedrock/event_stream_test.exs +++ b/test/ex_aws/bedrock/event_stream_test.exs @@ -7,30 +7,118 @@ defmodule ExAws.Bedrock.EventStreamTest do @checksum_size 4 @prelude_length @uint32_size * 3 @message_overhead @prelude_length + @checksum_size + @max_headers_length 128 * 1024 + @max_payload_length 24 * 1024 * 1024 - describe "decode_chunk/1" do + describe "decode_stream/1 with a single binary" do test "should decode single chunk response", %{chunk: chunk} do - assert [{:chunk, %{"outputText" => output_text}}] = EventStream.decode_chunk(chunk) + assert [{:chunk, %{"outputText" => output_text}}] = decode_stream([chunk]) assert String.contains?(output_text, "Elixir") end test "should decode multiple chunks in single response", %{multipart_chunk: multipart_chunk} do assert [{:chunk, %{"type" => _}}, {:chunk, %{"type" => _}}] = - EventStream.decode_chunk(multipart_chunk) + decode_stream([multipart_chunk]) end test "should handle invalid prelude checksum", %{chunk_with_invalid_prelude_checksum: chunk} do assert [{:bad_chunk, ^chunk, :invalid_prelude_checksum}] = - EventStream.decode_chunk(chunk) + decode_stream([chunk]) end test "should handle invalid message checksum", %{chunk_with_invalid_message_checksum: chunk} do assert [{:bad_chunk, ^chunk, :invalid_message_checksum}] = - EventStream.decode_chunk(chunk) + decode_stream([chunk]) end test "should handle incomplete chunk", %{incomplete_chunk: chunk} do - assert [{:bad_chunk, ^chunk, :invalid_chunk}] = EventStream.decode_chunk(chunk) + assert [{:bad_chunk, ^chunk, :invalid_chunk}] = decode_stream([chunk]) + end + end + + describe "decode_stream/1" do + test "should decode a message split at any byte offset", %{chunk: chunk} do + expected = decode_stream([chunk]) + assert [{:chunk, _}] = expected + + for offset <- 0..byte_size(chunk) do + <> = chunk + + assert expected == decode_stream([head, tail]), "split at byte #{offset}" + end + end + + test "should decode multiple messages split at any byte offset", %{ + multipart_chunk: multipart_chunk + } do + expected = decode_stream([multipart_chunk]) + assert [{:chunk, _}, {:chunk, _}] = expected + + for offset <- 0..byte_size(multipart_chunk) do + <> = multipart_chunk + + assert expected == decode_stream([head, tail]), "split at byte #{offset}" + end + end + + test "should decode messages delivered one byte at a time", %{ + multipart_chunk: multipart_chunk + } do + bytes = for <>, do: <> + + assert decode_stream([multipart_chunk]) == decode_stream(bytes) + end + + test "should emit each message as soon as it is complete", %{chunk: chunk} do + <> = chunk + + assert [{:chunk, _}] = + [head, tail] + |> Stream.concat(Stream.repeatedly(fn -> flunk("stream read too far") end)) + |> EventStream.decode_stream() + |> Enum.take(1) + end + + test "should continue after a message with an invalid checksum", %{ + chunk: chunk, + chunk_with_invalid_message_checksum: bad_chunk + } do + <> = bad_chunk <> chunk + + assert [{:bad_chunk, ^bad_chunk, :invalid_message_checksum}, {:chunk, _}] = + decode_stream([head, tail]) + end + + test "should report a stream that ends inside a message", %{ + chunk: chunk, + incomplete_chunk: incomplete_chunk + } do + assert [{:chunk, _}, {:bad_chunk, ^incomplete_chunk, :invalid_chunk}] = + decode_stream([chunk, incomplete_chunk]) + end + + test "should report a stream that ends inside a prelude", %{chunk: chunk} do + <> = chunk + + assert [{:chunk, _}, {:incomplete_chunk, ^head}] = decode_stream([chunk, head]) + end + + test "should reject a message over the payload limit without buffering it" do + prelude = prelude(@max_payload_length + 1, 0) + + assert [{:bad_chunk, ^prelude, :payload_too_large}] = decode_stream([prelude]) + end + + test "should reject a message over the headers limit without buffering it" do + prelude = prelude(0, @max_headers_length + 1) + + assert [{:bad_chunk, ^prelude, :headers_too_large}] = decode_stream([prelude]) + end + + test "should wait for a message at the payload and headers limits" do + prelude = prelude(@max_payload_length, @max_headers_length) + + assert [{:bad_chunk, ^prelude, :invalid_chunk}] = decode_stream([prelude]) end end @@ -158,6 +246,20 @@ defmodule ExAws.Bedrock.EventStreamTest do } end + defp decode_stream(binaries) do + binaries + |> EventStream.decode_stream() + |> Enum.to_list() + end + + # The prelude of a message with the given payload and headers lengths. + defp prelude(payload_length, headers_length) do + message_total_length = @message_overhead + headers_length + payload_length + lengths = <> + + lengths <> <<:erlang.crc32(lengths)::unsigned-32>> + end + defp alter_prelude_checksum(chunk) do # Modify the prelude checksum to be invalid <