Fix the frame size decoder for WebSocket frames

Review the AI's codeMedium15 min

Your task

Your Node server decoded each WebSocket frame as if one TCP chunk held exactly one frame with a 2-byte header, so large and split messages came out mangled. The fix buffers incoming bytes and first works out how big the next frame is. That needs the header rules from RFC 6455.

An assistant wrote websocket_frame_length(header). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • header: the first bytes of the frame received so far, as integers from 0 to 255.
  • Return the total size of the frame in bytes (header, masking key and payload), or -1 when more bytes are needed or the header is invalid.

Rules the tests check:

  • With fewer than 2 bytes, return -1.
  • In byte 1, the top bit (value 128) is the MASK flag and the low 7 bits are a length code. When MASK is set, a 4-byte masking key follows the header.
  • Length code 0 to 125: the payload length is the code. The header is 2 bytes.
  • Length code 126: the payload length is the next 2 bytes, big-endian. The header is 4 bytes. With fewer than 4 bytes, return -1.
  • Length code 127: the payload length is the next 8 bytes, big-endian, using all 8. The header is 10 bytes. With fewer than 10 bytes, return -1. If the top bit of the first of those 8 bytes is set, the frame is invalid: return -1.
  • The total is the header size, plus 4 when MASK is set, plus the payload length.

Examples

websocket_frame_length(header: list[int]) -> int
Example 1
Inputwebsocket_frame_length([129, 133])
Output11
Example 2
Inputwebsocket_frame_length([129, 254, 1, 44])
Output308
Example 3
Inputwebsocket_frame_length([129, 126, 1, 44])
Output304