wooga-kafka-rb 0.0.7

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # kafka-rb
2
+ kafka-rb allows you to produce messages to the Kafka distributed publish/subscribe messaging service.
3
+
4
+ ## Requirements
5
+ You need to have access to your Kafka instance and be able to connect through TCP. You can obtain a copy and instructions on how to setup kafka at https://github.com/kafka-dev/kafka
6
+
7
+ ## Installation
8
+ sudo gem install kafka-rb
9
+
10
+ (the code works fine with JRuby, Ruby 1.8x and Ruby 1.9.x)
11
+
12
+ ## Usage
13
+
14
+ ### Sending a simple message
15
+
16
+ require 'kafka'
17
+ producer = Kafka::Producer.new
18
+ message = Kafka::Message.new("some random message content")
19
+ producer.send(message)
20
+
21
+ ### Sending a sequence of messages
22
+
23
+ require 'kafka'
24
+ producer = Kafka::Producer.new
25
+ message1 = Kafka::Message.new("some random message content")
26
+ message2 = Kafka::Message.new("some more content")
27
+ producer.send([message1, message2])
28
+
29
+ ### Batching a bunch of messages using the block syntax
30
+
31
+ require 'kafka'
32
+ producer = Kafka::Producer.new
33
+ producer.batch do |messages|
34
+ puts "Batching a send of multiple messages.."
35
+ messages << Kafka::Message.new("first message to send")
36
+ messages << Kafka::Message.new("second message to send")
37
+ end
38
+
39
+ * they will be sent all at once, after the block execution
40
+
41
+ ### Consuming messages one by one
42
+
43
+ require 'kafka'
44
+ consumer = Kafka::Consumer.new
45
+ messages = consumer.consume
46
+
47
+
48
+ ### Consuming messages using a block loop
49
+
50
+ require 'kafka'
51
+ consumer = Kafka::Consumer.new
52
+ consumer.loop do |messages|
53
+ puts "Received"
54
+ puts messages
55
+ end
56
+
57
+
58
+ Contact for questions
59
+
60
+ alejandrocrosa at(@) gmail.com
61
+
62
+ http://twitter.com/alejandrocrosa
data/Rakefile ADDED
@@ -0,0 +1,74 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ require 'rubygems'
17
+ require 'rake/gempackagetask'
18
+ require 'rubygems/specification'
19
+ require 'date'
20
+ require 'rspec/core/rake_task'
21
+
22
+ spec = Gem::Specification.new do |s|
23
+ s.name = %q{wooga-kafka-rb}
24
+ s.version = "0.0.7"
25
+
26
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
27
+ s.authors = ["Alejandro Crosa", "Stefan Mees", "Tim Lossen"]
28
+ s.autorequire = %q{kafka-rb}
29
+ s.date = %q{2011-01-13}
30
+ s.description = %q{kafka-rb allows you to produce and consume messages using the Kafka distributed publish/subscribe messaging service.}
31
+ s.email = %q{alejandrocrosa@gmail.com}
32
+ s.extra_rdoc_files = ["LICENSE"]
33
+ s.files = ["LICENSE", "README.md", "Rakefile", "lib/kafka", "lib/kafka/batch.rb", "lib/kafka/consumer.rb", "lib/kafka/io.rb", "lib/kafka/message.rb", "lib/kafka/producer.rb", "lib/kafka/request_type.rb", "lib/kafka/error_codes.rb", "lib/kafka.rb", "spec/batch_spec.rb", "spec/consumer_spec.rb", "spec/io_spec.rb", "spec/kafka_spec.rb", "spec/message_spec.rb", "spec/producer_spec.rb", "spec/spec_helper.rb"]
34
+ s.homepage = %q{http://github.com/wooga/kafka-rb}
35
+ s.require_paths = ["lib"]
36
+ s.rubygems_version = %q{1.3.7}
37
+ s.summary = %q{A Ruby client for the Kafka distributed publish/subscribe messaging service}
38
+
39
+ if s.respond_to? :specification_version then
40
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
41
+ s.specification_version = 3
42
+
43
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
44
+ s.add_development_dependency(%q<rspec>, [">= 0"])
45
+ else
46
+ s.add_dependency(%q<rspec>, [">= 0"])
47
+ end
48
+ else
49
+ s.add_dependency(%q<rspec>, [">= 0"])
50
+ end
51
+ end
52
+
53
+ Rake::GemPackageTask.new(spec) do |pkg|
54
+ pkg.gem_spec = spec
55
+ end
56
+
57
+ task :default => :rspec
58
+
59
+ desc "Run specs"
60
+ RSpec::Core::RakeTask.new do |t|
61
+ t.pattern = FileList['spec/**/*_spec.rb']
62
+ t.rspec_opts = %w(-fs --color)
63
+ end
64
+
65
+ desc "install the gem locally"
66
+ task :install => [:package] do
67
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
68
+ end
69
+
70
+ desc "Run all examples with RCov"
71
+ RSpec::Core::RakeTask.new(:rcov) do |t|
72
+ t.pattern = FileList['spec/**/*_spec.rb']
73
+ t.rcov = true
74
+ end
@@ -0,0 +1,28 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ module Kafka
17
+ class Batch
18
+ attr_accessor :messages
19
+
20
+ def initialize
21
+ self.messages = []
22
+ end
23
+
24
+ def << (message)
25
+ self.messages << message
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,113 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ module Kafka
17
+ class Consumer
18
+
19
+ include Kafka::IO
20
+
21
+ MAX_SIZE = 1024 * 1024 # 1 megabyte
22
+ DEFAULT_POLLING_INTERVAL = 2 # 2 seconds
23
+ MAX_OFFSETS = 1
24
+ EARLIEST_OFFSET = -2
25
+
26
+ attr_accessor :topic, :partition, :offset, :max_size, :request_type, :polling
27
+
28
+ def initialize(options = {})
29
+ self.topic = options[:topic] || "test"
30
+ self.partition = options[:partition] || 0
31
+ self.host = options[:host] || "localhost"
32
+ self.port = options[:port] || 9092
33
+ self.offset = options[:offset]
34
+ self.max_size = options[:max_size] || MAX_SIZE
35
+ self.polling = options[:polling] || DEFAULT_POLLING_INTERVAL
36
+ connect(host, port)
37
+ end
38
+
39
+ def loop(&block)
40
+ messages = []
41
+ while (true) do
42
+ messages = consume
43
+ block.call(messages) if messages && !messages.empty?
44
+ sleep(polling)
45
+ end
46
+ end
47
+
48
+ def consume
49
+ self.offset ||= fetch_earliest_offset
50
+ send_consume_request
51
+ data = read_data_response
52
+ parse_message_set_from(data)
53
+ rescue SocketError
54
+ nil
55
+ end
56
+
57
+ def fetch_earliest_offset
58
+ send_offsets_request
59
+ read_offsets_response
60
+ end
61
+
62
+ def send_offsets_request
63
+ write(encoded_request_size)
64
+ write(encode_request(Kafka::RequestType::OFFSETS, topic, partition, EARLIEST_OFFSET, MAX_OFFSETS))
65
+ end
66
+
67
+ def read_offsets_response
68
+ read_data_response[4,8].reverse.unpack('q')[0]
69
+ end
70
+
71
+ def send_consume_request
72
+ write(encoded_request_size)
73
+ write(encode_request(Kafka::RequestType::FETCH, topic, partition, offset, max_size))
74
+ end
75
+
76
+ def read_data_response
77
+ data_length = read(4).unpack("N").shift
78
+ data = read(data_length)
79
+ # TODO: inspect error code instead of skipping it
80
+ data[2, data.length]
81
+ end
82
+
83
+ def encoded_request_size
84
+ size = 2 + 2 + topic.length + 4 + 8 + 4
85
+ [size].pack("N")
86
+ end
87
+
88
+ def encode_request(request_type, topic, partition, offset, max_size)
89
+ request_type = [request_type].pack("n")
90
+ topic = [topic.length].pack('n') + topic
91
+ partition = [partition].pack("N")
92
+ offset = [offset].pack("q").reverse # DIY 64bit big endian integer
93
+ max_size = [max_size].pack("N")
94
+ request_type + topic + partition + offset + max_size
95
+ end
96
+
97
+ def parse_message_set_from(data)
98
+ messages = []
99
+ processed = 0
100
+ length = data.length - 4
101
+ while (processed <= length) do
102
+ message_size = data[processed, 4].unpack("N").shift + 4
103
+ message_data = data[processed, message_size]
104
+ break unless message_data.size == message_size
105
+ messages << Kafka::Message.parse_from(message_data)
106
+ processed += message_size
107
+ end
108
+ self.offset += processed
109
+ messages
110
+ end
111
+
112
+ end
113
+ end
@@ -0,0 +1,35 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ module Kafka
16
+ module ErrorCodes
17
+ NO_ERROR = 0
18
+ OFFSET_OUT_OF_RANGE = 1
19
+ INVALID_MESSAGE_CODE = 2
20
+ WRONG_PARTITION_CODE = 3
21
+ INVALID_RETCH_SIZE_CODE = 4
22
+
23
+ STRINGS = {
24
+ 0 => 'No error',
25
+ 1 => 'Offset out of range',
26
+ 2 => 'Invalid message code',
27
+ 3 => 'Wrong partition code',
28
+ 4 => 'Invalid retch size code',
29
+ }
30
+
31
+ def self.to_s(code)
32
+ STRINGS[code] || 'Unknown error'
33
+ end
34
+ end
35
+ end
data/lib/kafka/io.rb ADDED
@@ -0,0 +1,54 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ module Kafka
16
+ module IO
17
+ attr_accessor :socket, :host, :port
18
+
19
+ def connect(host, port)
20
+ raise ArgumentError, "No host or port specified" unless host && port
21
+ self.host = host
22
+ self.port = port
23
+ self.socket = TCPSocket.new(host, port)
24
+ end
25
+
26
+ def reconnect
27
+ self.socket = TCPSocket.new(self.host, self.port)
28
+ rescue
29
+ self.disconnect
30
+ raise
31
+ end
32
+
33
+ def disconnect
34
+ self.socket.close rescue nil
35
+ self.socket = nil
36
+ end
37
+
38
+ def read(length)
39
+ self.socket.read(length) || raise(SocketError, "no data")
40
+ rescue
41
+ self.disconnect
42
+ raise SocketError, "cannot read: #{$!.message}"
43
+ end
44
+
45
+ def write(data)
46
+ self.reconnect unless self.socket
47
+ self.socket.write(data)
48
+ rescue
49
+ self.disconnect
50
+ raise SocketError, "cannot write: #{$!.message}"
51
+ end
52
+
53
+ end
54
+ end
@@ -0,0 +1,49 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ module Kafka
16
+
17
+ # A message. The format of an N byte message is the following:
18
+ # 1 byte "magic" identifier to allow format changes
19
+ # 4 byte CRC32 of the payload
20
+ # N - 5 byte payload
21
+ class Message
22
+
23
+ MAGIC_IDENTIFIER_DEFAULT = 0
24
+
25
+ attr_accessor :magic, :checksum, :payload
26
+
27
+ def initialize(payload = nil, magic = MAGIC_IDENTIFIER_DEFAULT, checksum = nil)
28
+ self.magic = magic
29
+ self.payload = payload
30
+ self.checksum = checksum || self.calculate_checksum
31
+ end
32
+
33
+ def calculate_checksum
34
+ Zlib.crc32(self.payload)
35
+ end
36
+
37
+ def valid?
38
+ self.checksum == Zlib.crc32(self.payload)
39
+ end
40
+
41
+ def self.parse_from(binary)
42
+ size = binary[0, 4].unpack("N").shift.to_i
43
+ magic = binary[4, 1].unpack("C").shift
44
+ checksum = binary[5, 4].unpack("N").shift
45
+ payload = binary[9, size] # 5 = 1 + 4 is Magic + Checksum
46
+ return Kafka::Message.new(payload, magic, checksum)
47
+ end
48
+ end
49
+ end