Class: Elastomer::Middleware::Compress

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/elastomer/middleware/compress.rb

Overview

Request middleware that compresses request bodies with GZip for supported versions of Elasticsearch.

It will only compress when there is a request body that is a String. This middleware should be inserted after JSON serialization.

Constant Summary collapse

CONTENT_ENCODING =
"Content-Encoding"
GZIP =
"gzip"
MIN_BYTES_FOR_COMPRESSION =

An Ethernet packet can hold 1500 bytes. No point in compressing anything smaller than that (plus some wiggle room).

1400

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Compress

options - The Hash of “keyword” arguments.

:compression - the compression level (0-9, default Zlib::DEFAULT_COMPRESSION)


21
22
23
24
# File 'lib/elastomer/middleware/compress.rb', line 21

def initialize(app, options = {})
  super(app)
  @compression = options[:compression] || Zlib::DEFAULT_COMPRESSION
end

Instance Attribute Details

#compressionObject (readonly)

Returns the value of attribute compression.



17
18
19
# File 'lib/elastomer/middleware/compress.rb', line 17

def compression
  @compression
end

Instance Method Details

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/elastomer/middleware/compress.rb', line 26

def call(env)
  if body = env[:body]
    if body.is_a?(String) && body.bytesize > MIN_BYTES_FOR_COMPRESSION
      output = StringIO.new
      output.set_encoding("BINARY")
      gz = Zlib::GzipWriter.new(output, compression, Zlib::DEFAULT_STRATEGY)
      gz.write(env[:body])
      gz.close
      env[:body] = output.string
      env[:request_headers][CONTENT_ENCODING] = GZIP
    end
  end

  @app.call(env)
end