Module: MCPClient::HttpTransportBase::BoundedInflate

Defined in:
lib/mcp_client/http_transport_base/bounded_inflate.rb

Overview

Inflation of peer-supplied gzip bytes under an expansion bound. The peer controls the compression ratio, so the bound is applied to the pieces zlib produces as it produces them: a body that expands far past the ceiling is stopped at the first piece that crosses it, never allocated in full and then measured.

Class Method Summary collapse

Class Method Details

.inflate(inflater, bytes, limit, inflated_so_far = 0) ⇒ String?

Returns the text these bytes expand to; nil once the expansion would cross the limit.

Parameters:

  • inflater (Zlib::Inflate) —

    the stream the bytes belong to

  • bytes (String) —

    gzip bytes as they arrived

  • limit (Integer, nil) —

    ceiling on the inflated size, nil for none

  • inflated_so_far (Integer) (defaults to: 0) —

    bytes this stream already produced

Returns:

  • (String, nil) —

    the text these bytes expand to; nil once the expansion would cross the limit



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mcp_client/http_transport_base/bounded_inflate.rb', line 21

def inflate(inflater, bytes, limit, inflated_so_far = 0)
  text = +''.b
  over = ->(piece) { limit && inflated_so_far + text.bytesize + piece.bytesize > limit }
  catch(:over_the_bound) do
    inflater.inflate(bytes) do |piece|
      throw :over_the_bound if over.call(piece)

      text << piece
    end
    # zlib hands over full pieces as it fills them; what is left of a
    # stream that has not ended stays in its buffer until asked for.
    tail = inflater.flush_next_out
    throw :over_the_bound if over.call(tail)

    return text << tail
  end
  nil
end