Class BedrockEventStreamEncoder

java.lang.Object
org.mockserver.llm.codec.BedrockEventStreamEncoder

public final class BedrockEventStreamEncoder extends Object
Encoder and decoder for the AWS event-stream binary message format (application/vnd.amazon.eventstream).

Each message has the following layout:

   4 bytes  — total byte length (big-endian)
   4 bytes  — headers byte length (big-endian)
   4 bytes  — prelude CRC32 (of the first 8 bytes)
   N bytes  — headers
   M bytes  — payload
   4 bytes  — message CRC32 (of everything up to this point)
 

For Bedrock InvokeModelWithResponseStream, each "chunk" event carries headers :event-type=chunk, :content-type=application/json, :message-type=event, and the payload is {"bytes":"<base64(chunkJson)>"}.

This class uses only JDK APIs (CRC32, Base64) and introduces no new Maven dependencies.

  • Field Details

  • Method Details

    • encodeChunk

      public static byte[] encodeChunk(String chunkJson)
      Encode a single model chunk (JSON string) into one AWS event-stream binary message. The chunk JSON is base64-encoded and wrapped in a {"bytes":"<base64>"} payload, matching Bedrock's InvokeModelWithResponseStream wire format.
      Parameters:
      chunkJson - the model's streaming chunk JSON (e.g. an Anthropic SSE data payload)
      Returns:
      the complete binary event-stream message
    • encodeMessage

      public static byte[] encodeMessage(Map<String,String> headers, byte[] payload)
      Encode a full event-stream binary message with the given headers and payload.
      Parameters:
      headers - string-typed headers (name to value)
      payload - the raw payload bytes
      Returns:
      the complete binary message
    • encodeStream

      public static byte[] encodeStream(List<String> chunks)
      Concatenate multiple chunk JSON strings into a single event-stream byte array (one binary message per chunk, concatenated).
      Parameters:
      chunks - the ordered list of model chunk JSON strings
      Returns:
      concatenated event-stream messages
    • decode

      public static List<BedrockEventStreamEncoder.DecodedMessage> decode(byte[] data)
      Decode a concatenated event-stream byte array into individual messages.
      Parameters:
      data - the raw event-stream bytes
      Returns:
      ordered list of decoded messages
      Throws:
      IllegalArgumentException - if any CRC32 check fails or data is malformed