Skip to content

Commit 6f336df

Browse files
committed
Avoid runtime work when looking up codecs
1 parent d0f1caf commit 6f336df

File tree

3 files changed

+28
-13
lines changed

3 files changed

+28
-13
lines changed

lib/kafka/compression.rb

+19-12
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,34 @@
44

55
module Kafka
66
module Compression
7+
CODEC_NAMES = {
8+
1 => :gzip,
9+
2 => :snappy,
10+
3 => :lz4,
11+
}.freeze
12+
13+
CODECS = {
14+
:gzip => GzipCodec.new,
15+
:snappy => SnappyCodec.new,
16+
:lz4 => LZ4Codec.new,
17+
}.freeze
18+
719
def self.codecs
8-
[:snappy, :gzip, :lz4]
20+
CODECS.keys
921
end
1022

1123
def self.find_codec(name)
12-
case name
13-
when nil then nil
14-
when :snappy then SnappyCodec.new
15-
when :gzip then GzipCodec.new
16-
when :lz4 then LZ4Codec.new
17-
else raise "Unknown compression codec #{name}"
24+
CODECS.fetch(name) do
25+
raise "Unknown compression codec #{name}"
1826
end
1927
end
2028

2129
def self.find_codec_by_id(codec_id)
22-
case codec_id
23-
when 1 then GzipCodec.new
24-
when 2 then SnappyCodec.new
25-
when 3 then LZ4Codec.new
26-
else raise "Unknown codec id #{codec_id}"
30+
codec_name = CODEC_NAMES.fetch(codec_id) do
31+
raise "Unknown codec id #{codec_id}"
2732
end
33+
34+
find_codec(codec_name)
2835
end
2936
end
3037
end

lib/kafka/compressor.rb

+3-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ class Compressor
2121
# @param threshold [Integer] the minimum number of messages in a message set
2222
# that will trigger compression.
2323
def initialize(codec_name: nil, threshold: 1, instrumenter:)
24-
@codec = Compression.find_codec(codec_name)
24+
# Codec may be nil, in which case we won't compress.
25+
@codec = codec_name && Compression.find_codec(codec_name)
26+
2527
@threshold = threshold
2628
@instrumenter = instrumenter
2729
end

spec/compression_spec.rb

+6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@
77

88
expect(codec.decompress(codec.compress(data))).to eq data
99
end
10+
11+
it "has a consistent codec id" do
12+
codec = Kafka::Compression.find_codec(codec_name)
13+
14+
expect(Kafka::Compression.find_codec_by_id(codec.codec_id)).to eq codec
15+
end
1016
end
1117
end
1218
end

0 commit comments

Comments
 (0)