Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor compression codec lookup #509

Merged
merged 2 commits into from
Dec 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions lib/kafka/compression.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,34 @@

module Kafka
module Compression
CODEC_NAMES = {
1 => :gzip,
2 => :snappy,
3 => :lz4,
}.freeze

CODECS = {
:gzip => GzipCodec.new,
:snappy => SnappyCodec.new,
:lz4 => LZ4Codec.new,
}.freeze

def self.codecs
CODECS.keys
end

def self.find_codec(name)
case name
when nil then nil
when :snappy then SnappyCodec.new
when :gzip then GzipCodec.new
when :lz4 then LZ4Codec.new
else raise "Unknown compression codec #{name}"
CODECS.fetch(name) do
raise "Unknown compression codec #{name}"
end
end

def self.find_codec_by_id(codec_id)
case codec_id
when 1 then GzipCodec.new
when 2 then SnappyCodec.new
when 3 then LZ4Codec.new
else raise "Unknown codec id #{codec_id}"
codec_name = CODEC_NAMES.fetch(codec_id) do
raise "Unknown codec id #{codec_id}"
end

find_codec(codec_name)
end
end
end
4 changes: 3 additions & 1 deletion lib/kafka/compressor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ class Compressor
# @param threshold [Integer] the minimum number of messages in a message set
# that will trigger compression.
def initialize(codec_name: nil, threshold: 1, instrumenter:)
@codec = Compression.find_codec(codec_name)
# Codec may be nil, in which case we won't compress.
@codec = codec_name && Compression.find_codec(codec_name)

@threshold = threshold
@instrumenter = instrumenter
end
Expand Down
18 changes: 18 additions & 0 deletions spec/compression_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
describe Kafka::Compression do
Kafka::Compression.codecs.each do |codec_name|
describe codec_name.to_s do
it "encodes and decodes data" do
data = "yolo"
codec = Kafka::Compression.find_codec(codec_name)

expect(codec.decompress(codec.compress(data))).to eq data
end

it "has a consistent codec id" do
codec = Kafka::Compression.find_codec(codec_name)

expect(Kafka::Compression.find_codec_by_id(codec.codec_id)).to eq codec
end
end
end
end