This repository has been archived by the owner on Jan 10, 2024. It is now read-only.
forked from zendesk/ruby-kafka
-
Notifications
You must be signed in to change notification settings - Fork 1
/
consumer_spec.rb
565 lines (461 loc) · 16.2 KB
/
consumer_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# frozen_string_literal: true
require "timecop"
require "fake_consumer_interceptor"
require "kafka/interceptors"
describe Kafka::Consumer do
let(:cluster) { double(:cluster) }
let(:log) { StringIO.new }
let(:logger) { Logger.new(log) }
let(:instrumenter) { Kafka::Instrumenter.new(client_id: "test", group_id: "test") }
let(:group) { double(:group) }
let(:offset_manager) { double(:offset_manager) }
let(:heartbeat) { double(:heartbeat) }
let(:fetcher) { double(:fetcher, configure: nil, subscribe: nil, seek: nil, start: nil, stop: nil) }
let(:session_timeout) { 30 }
let(:assigned_partitions) { { "greetings" => [0] } }
let(:consumer) {
Kafka::Consumer.new(
cluster: cluster,
logger: logger,
instrumenter: instrumenter,
group: group,
offset_manager: offset_manager,
fetcher: fetcher,
session_timeout: session_timeout,
heartbeat: heartbeat,
)
}
let(:messages) {
[
double(:message, {
value: "hello",
key: nil,
headers: {},
topic: "greetings",
partition: 0,
offset: 13,
create_time: Time.now,
})
]
}
let(:fetched_batches) {
[
Kafka::FetchedBatch.new(
topic: "greetings",
partition: 0,
last_offset: 13,
highwater_mark_offset: 42,
messages: messages,
)
]
}
shared_context 'from unassigned partition' do
let(:unassigned_messages) do
[
double(:message, {
value: "hello",
key: nil,
topic: "greetings",
partition: 1,
offset: 10,
create_time: Time.now,
})
]
end
let(:old_fetched_batches) {
[
Kafka::FetchedBatch.new(
topic: "greetings",
partition: 1,
last_offset: 10,
highwater_mark_offset: 42,
messages: unassigned_messages,
)
]
}
before do
allow(fetcher).to receive(:poll).and_return(
[:batches, old_fetched_batches], # first call
[:batches, fetched_batches] # any time after the first call
)
end
end
shared_context 'with partition reassignment' do
let(:messages_after_partition_reassignment) {
[
double(:message, {
value: "hello",
key: nil,
headers: {},
topic: "greetings",
partition: 1,
offset: 10,
create_time: Time.now,
is_control_record: false
})
]
}
let(:batches_after_partition_reassignment) {
[
Kafka::FetchedBatch.new(
topic: "greetings",
partition: 1,
last_offset: 10,
highwater_mark_offset: 42,
messages: messages_after_partition_reassignment,
)
]
}
before do
allow(fetcher).to receive(:poll).and_return(
[:batches, fetched_batches], # first call
[:batches, batches_after_partition_reassignment] # any time after the first call
)
end
end
before do
allow(cluster).to receive(:add_target_topics)
allow(cluster).to receive(:disconnect)
allow(cluster).to receive(:refresh_metadata_if_necessary!)
allow(cluster).to receive(:mark_as_stale!)
allow(offset_manager).to receive(:commit_offsets)
allow(offset_manager).to receive(:commit_offsets_if_necessary)
allow(offset_manager).to receive(:set_default_offset)
allow(offset_manager).to receive(:mark_as_processed)
allow(offset_manager).to receive(:next_offset_for) { 42 }
allow(offset_manager).to receive(:clear_offsets)
allow(group).to receive(:subscribe)
allow(group).to receive(:group_id)
allow(group).to receive(:leave)
allow(group).to receive(:member?) { true }
allow(group).to receive(:subscribed_partitions) { assigned_partitions }
allow(group).to receive(:assigned_to?) { false }
allow(group).to receive(:assigned_to?).with('greetings', 0) { true }
allow(group).to receive(:generation_id) { 1 }
allow(group).to receive(:join)
allow(group).to receive(:assigned_partitions) { [] }
allow(heartbeat).to receive(:trigger)
allow(fetcher).to receive(:data?) { fetched_batches.any? }
allow(fetcher).to receive(:poll) { [:batches, fetched_batches] }
allow(fetcher).to receive(:reset)
consumer.subscribe("greetings")
end
describe "#each_message" do
let(:messages) {
[
double(:message, {
value: "hello",
key: nil,
headers: {},
topic: "greetings",
partition: 0,
offset: 13,
create_time: Time.now,
is_control_record: false
})
]
}
let(:fetched_batches) {
[
Kafka::FetchedBatch.new(
topic: "greetings",
partition: 0,
last_offset: 13,
highwater_mark_offset: 42,
messages: messages,
)
]
}
it "instruments" do
expect(instrumenter).to receive(:instrument).once.with('start_process_message.consumer', anything)
expect(instrumenter).to receive(:instrument).once.with('process_message.consumer', anything)
allow(instrumenter).to receive(:instrument).and_call_original
consumer.each_message do |message|
consumer.stop
end
end
it "raises ProcessingError if the processing code fails" do
expect {
consumer.each_message do |message|
raise "yolo"
end
}.to raise_exception(Kafka::ProcessingError) {|exception|
expect(exception.topic).to eq "greetings"
expect(exception.partition).to eq 0
expect(exception.offset).to eq 13
cause = exception.cause
expect(cause.class).to eq RuntimeError
expect(cause.message).to eq "yolo"
}
expect(log.string).to include "Exception raised when processing greetings/0 at offset 13 -- RuntimeError: yolo"
end
it "stops if SignalException is encountered" do
allow(fetcher).to receive(:poll) { [:exception, SignalException.new("SIGTERM")] }
consumer.each_message {}
expect(log.string).to include "Received signal SIGTERM, shutting down"
end
it "seeks to the default offset when the checkpoint is invalid " do
done = false
allow(offset_manager).to receive(:seek_to_default) { done = true }
allow(fetcher).to receive(:poll) {
if done
[:batches, fetched_batches]
else
[:exception, Kafka::OffsetOutOfRange.new]
end
}
consumer.each_message do |message|
consumer.stop
end
expect(offset_manager).to have_received(:seek_to_default)
end
it "does not fetch messages from paused partitions" do
allow(group).to receive(:assigned_to?).with('greetings', 42) { true }
assigned_partitions["greetings"] << 42
consumer.pause("greetings", 42)
consumer.each_message do |message|
consumer.stop
end
expect(fetcher).to_not have_received(:seek).with("greetings", 42, anything)
consumer.resume("greetings", 42)
consumer.each_message do |message|
consumer.stop
end
expect(fetcher).to have_received(:seek).with("greetings", 42, anything)
end
it "does not seek (previously) paused partition when not in group" do
allow(group).to receive(:assigned_to?).with('greetings', 42) { false }
assigned_partitions["greetings"] << 42
consumer.pause("greetings", 42)
consumer.resume("greetings", 42)
consumer.each_message do |message|
consumer.stop
end
expect(fetcher).to_not have_received(:seek).with("greetings", 42, anything)
end
it "automatically resumes partitions if a timeout is set" do
time = Time.now
Timecop.freeze time do
consumer.pause("greetings", 0, timeout: 30)
Timecop.travel 29 do
expect(consumer.paused?("greetings", 0)).to eq true
end
Timecop.travel 31 do
expect(consumer.paused?("greetings", 0)).to eq false
end
end
end
it 'retries final offsets commit at the end' do
allow(offset_manager).to receive(:commit_offsets)
.exactly(4).times { raise(Kafka::ConnectionError) }
consumer.each_message do |message|
consumer.stop
end
end
context 'message from #fetch_batches is old, and from a partition not assigned to this consumer' do
include_context 'from unassigned partition'
it 'does not update offsets for messages from unassigned partitions' do
consumer.each_message do |message|
consumer.stop
end
expect(offset_manager).to have_received(:commit_offsets_if_necessary).twice
offsets = consumer.instance_variable_get(:@current_offsets)
expect(offsets['greetings'].keys).not_to include(1)
end
it 'does not process messages from unassigned partitions' do
@yield_count = 0
consumer.each_message do |message|
@yield_count += 1
consumer.stop
end
expect(offset_manager).to have_received(:commit_offsets_if_necessary).twice
expect(@yield_count).to eq 1
end
end
context 'consumer joins a new group' do
include_context 'with partition reassignment'
let(:group) { double(:group).as_null_object }
let(:fetcher) { double(:fetcher).as_null_object }
let(:current_offsets) { consumer.instance_variable_get(:@current_offsets) }
let(:assigned_partitions) { { 'greetings' => [0] } }
let(:reassigned_partitions) { { 'greetings' => [1] } }
before do
allow(heartbeat).to receive(:trigger) do
next unless @encounter_rebalance
@encounter_rebalance = false
raise Kafka::RebalanceInProgress
end
consumer.each_message do |message|
consumer.stop
end
allow(group).to receive(:assigned_partitions).and_return(reassigned_partitions)
allow(group).to receive(:assigned_to?).with('greetings', 1) { true }
allow(group).to receive(:assigned_to?).with('greetings', 0) { false }
allow(group).to receive(:generation_id).and_return(*generation_ids)
@encounter_rebalance = true
end
context 'with subsequent group generations' do
let(:generation_ids) { [1, 2] }
it 'removes local offsets for partitions it is no longer assigned' do
expect(offset_manager).to receive(:clear_offsets_excluding).with(reassigned_partitions)
expect do
consumer.each_message do |message|
consumer.stop
end
end.to change { current_offsets['greetings'].keys }.from([0]).to([1])
end
end
context 'with group generations further apart' do
let(:generation_ids) { [1, 3] }
it 'clears local offsets' do
expect(offset_manager).to receive(:clear_offsets)
expect do
consumer.each_message do |message|
consumer.stop
end
end.to change { current_offsets['greetings'].keys }.from([0]).to([1])
end
end
end
end
describe "#commit_offsets" do
it "delegates to offset_manager" do
expect(offset_manager).to receive(:commit_offsets)
consumer.commit_offsets
end
end
describe "#each_batch" do
let(:messages) {
[
double(:message, {
value: "hello",
key: nil,
headers: {},
topic: "greetings",
partition: 0,
offset: 13,
create_time: Time.now,
is_control_record: false
})
]
}
let(:fetched_batches) {
[
Kafka::FetchedBatch.new(
topic: "greetings",
partition: 0,
last_offset: 13,
highwater_mark_offset: 42,
messages: messages,
)
]
}
it "does not mark as processed when automatically_mark_as_processed is false" do
expect(offset_manager).not_to receive(:mark_as_processed)
consumer.each_batch(automatically_mark_as_processed: false) do |message|
consumer.stop
end
end
it "raises ProcessingError if the processing code fails" do
expect {
consumer.each_batch do |message|
raise "yolo"
end
}.to raise_exception(Kafka::ProcessingError) {|exception|
expect(exception.topic).to eq "greetings"
expect(exception.partition).to eq 0
expect(exception.offset).to eq 13..13
cause = exception.cause
expect(cause.class).to eq RuntimeError
expect(cause.message).to eq "yolo"
}
expect(log.string).to include "Exception raised when processing greetings/0 in offset range 13..13 -- RuntimeError: yolo"
end
context 'message from #fetch_batches is old, and from a partition not assigned to this consumer.' do
include_context 'from unassigned partition'
it 'does not update offsets for messages from unassigned partitions' do
consumer.each_batch do |batch|
consumer.stop
end
expect(offset_manager).to have_received(:commit_offsets_if_necessary).twice
offsets = consumer.instance_variable_get(:@current_offsets)
expect(offsets['greetings'].keys).not_to include(1)
end
it 'does not process messages from unassigned partitions' do
@yield_count = 0
consumer.each_batch do |batch|
batch.messages.each do |message|
@yield_count += 1
end
consumer.stop
end
expect(offset_manager).to have_received(:commit_offsets_if_necessary).twice
expect(@yield_count).to eq 1
end
end
end
describe "#seek" do
it "looks for the given topic-partition-offset" do
expect(offset_manager).to receive(:seek_to).with("greetings", 0, 14)
consumer.seek("greetings", 0, 14)
end
end
describe "#trigger_heartbeat" do
it "sends heartbeat if necessary" do
expect(heartbeat).to receive(:trigger)
consumer.trigger_heartbeat
end
end
describe "#trigger_heartbeat!" do
it "always sends heartbeat" do
expect(heartbeat).to receive(:trigger!)
consumer.trigger_heartbeat!
end
end
describe '#send_heartbeat_if_necessary' do
subject(:method_original_name) { consumer.method(:send_heartbeat_if_necessary).original_name }
it { expect(method_original_name).to eq(:trigger_heartbeat) }
end
describe '#send_heartbeat' do
subject(:method_original_name) { consumer.method(:send_heartbeat).original_name }
it { expect(method_original_name).to eq(:trigger_heartbeat!) }
end
describe '#interceptor' do
it "creates and stops a consumer with interceptor" do
interceptor = FakeConsumerInterceptor.new
consumer = Kafka::Consumer.new(
cluster: cluster,
logger: logger,
instrumenter: instrumenter,
group: group,
offset_manager: offset_manager,
fetcher: fetcher,
session_timeout: session_timeout,
heartbeat: heartbeat,
interceptors: [interceptor]
)
consumer.stop
end
it "chains call" do
interceptor1 = FakeConsumerInterceptor.new(append_s: 'hello2')
interceptor2 = FakeConsumerInterceptor.new(append_s: 'hello3')
interceptors = Kafka::Interceptors.new(interceptors: [interceptor1, interceptor2], logger: logger)
intercepted_batch = interceptors.call(fetched_batches[0])
expect(intercepted_batch.messages[0].value).to eq "hellohello2hello3"
end
it "does not break the call chain" do
interceptor1 = FakeConsumerInterceptor.new(append_s: 'hello2', on_call_error: true)
interceptor2 = FakeConsumerInterceptor.new(append_s: 'hello3')
interceptors = Kafka::Interceptors.new(interceptors: [interceptor1, interceptor2], logger: logger)
intercepted_batch = interceptors.call(fetched_batches[0])
expect(intercepted_batch.messages[0].value).to eq "hellohello3"
end
it "returns original batch when all interceptors fail" do
interceptor1 = FakeConsumerInterceptor.new(append_s: 'hello2', on_call_error: true)
interceptor2 = FakeConsumerInterceptor.new(append_s: 'hello3', on_call_error: true)
interceptors = Kafka::Interceptors.new(interceptors: [interceptor1, interceptor2], logger: logger)
intercepted_batch = interceptors.call(fetched_batches[0])
expect(intercepted_batch.messages[0].value).to eq "hello"
end
end
end