-
-
Notifications
You must be signed in to change notification settings - Fork 541
/
Copy pathrunner.js
518 lines (447 loc) · 15.1 KB
/
runner.js
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
const { EventEmitter } = require('events')
const Long = require('../utils/long')
const createRetry = require('../retry')
const { isKafkaJSError, isRebalancing } = require('../errors')
const {
events: { FETCH, FETCH_START, START_BATCH_PROCESS, END_BATCH_PROCESS, REBALANCING },
} = require('./instrumentationEvents')
const createFetchManager = require('./fetchManager')
const isSameOffset = (offsetA, offsetB) => Long.fromValue(offsetA).equals(Long.fromValue(offsetB))
const CONSUMING_START = 'consuming-start'
const CONSUMING_STOP = 'consuming-stop'
module.exports = class Runner extends EventEmitter {
/**
* @param {object} options
* @param {import("../../types").Logger} options.logger
* @param {import("./consumerGroup")} options.consumerGroup
* @param {import("../instrumentation/emitter")} options.instrumentationEmitter
* @param {boolean} [options.eachBatchAutoResolve=true]
* @param {number} options.concurrency
* @param {(payload: import("../../types").EachBatchPayload) => Promise<void>} [options.eachBatch]
* @param {(payload: import("../../types").EachMessagePayload) => Promise<void>} [options.eachMessage]
* @param {number} [options.heartbeatInterval]
* @param {(reason: Error) => void} options.onCrash
* @param {import("../../types").RetryOptions} [options.retry]
* @param {boolean} [options.autoCommit=true]
*/
constructor({
logger,
consumerGroup,
instrumentationEmitter,
eachBatchAutoResolve = true,
concurrency,
eachBatch,
eachMessage,
heartbeatInterval,
onCrash,
retry,
autoCommit = true,
}) {
super()
this.logger = logger.namespace('Runner')
this.consumerGroup = consumerGroup
this.instrumentationEmitter = instrumentationEmitter
this.eachBatchAutoResolve = eachBatchAutoResolve
this.eachBatch = eachBatch
this.eachMessage = eachMessage
this.heartbeatInterval = heartbeatInterval
this.retrier = createRetry(Object.assign({}, retry))
this.onCrash = onCrash
this.autoCommit = autoCommit
this.fetchManager = createFetchManager({
logger: this.logger,
getNodeIds: () => this.consumerGroup.getNodeIds(),
fetch: nodeId => this.fetch(nodeId),
handler: batch => this.handleBatch(batch),
concurrency,
})
this.running = false
this.consuming = false
}
get consuming() {
return this._consuming
}
set consuming(value) {
if (this._consuming !== value) {
this._consuming = value
this.emit(value ? CONSUMING_START : CONSUMING_STOP)
}
}
async start() {
if (this.running) {
return
}
try {
await this.consumerGroup.connect()
await this.consumerGroup.joinAndSync()
} catch (e) {
return this.onCrash(e)
}
this.running = true
this.scheduleFetchManager()
}
scheduleFetchManager() {
if (!this.running) {
this.consuming = false
this.logger.info('consumer not running, exiting', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
return
}
this.consuming = true
this.retrier(async (bail, retryCount, retryTime) => {
if (!this.running) {
return
}
try {
await this.fetchManager.start()
} catch (e) {
if (isRebalancing(e)) {
this.logger.warn('The group is rebalancing, re-joining', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
error: e.message,
})
this.instrumentationEmitter.emit(REBALANCING, {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
await this.consumerGroup.joinAndSync()
return
}
if (e.type === 'UNKNOWN_MEMBER_ID') {
this.logger.error('The coordinator is not aware of this member, re-joining the group', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
error: e.message,
})
this.consumerGroup.memberId = null
await this.consumerGroup.joinAndSync()
return
}
if (e.name === 'KafkaJSNotImplemented') {
return bail(e)
}
if (e.name === 'KafkaJSNoBrokerAvailableError') {
return bail(e)
}
this.logger.debug('Error while scheduling fetch manager, trying again...', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
error: e.message,
stack: e.stack,
retryCount,
retryTime,
})
throw e
}
})
.then(() => {
this.scheduleFetchManager()
})
.catch(e => {
this.onCrash(e)
this.consuming = false
this.running = false
})
}
async stop() {
if (!this.running) {
return
}
this.logger.debug('stop consumer group', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
this.running = false
try {
await this.fetchManager.stop()
await this.waitForConsumer()
await this.consumerGroup.leave()
} catch (e) {}
}
waitForConsumer() {
return new Promise(resolve => {
if (!this.consuming) {
return resolve()
}
this.logger.debug('waiting for consumer to finish...', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
this.once(CONSUMING_STOP, () => resolve())
})
}
async heartbeat() {
try {
await this.consumerGroup.heartbeat({ interval: this.heartbeatInterval })
} catch (e) {
if (isRebalancing(e)) {
await this.autoCommitOffsets()
}
throw e
}
}
async processEachMessage(batch) {
const { topic, partition } = batch
const pause = () => {
this.consumerGroup.pause([{ topic, partitions: [partition] }])
return () => this.consumerGroup.resume([{ topic, partitions: [partition] }])
}
for (const message of batch.messages) {
if (!this.running || this.consumerGroup.hasSeekOffset({ topic, partition })) {
break
}
try {
await this.eachMessage({
topic,
partition,
message,
heartbeat: () => this.heartbeat(),
pause,
})
} catch (e) {
if (!isKafkaJSError(e)) {
this.logger.error(`Error when calling eachMessage`, {
topic,
partition,
offset: message.offset,
stack: e.stack,
error: e,
})
}
// In case of errors, commit the previously consumed offsets unless autoCommit is disabled
await this.autoCommitOffsets()
throw e
}
this.consumerGroup.resolveOffset({ topic, partition, offset: message.offset })
await this.heartbeat()
await this.autoCommitOffsetsIfNecessary()
if (this.consumerGroup.isPaused(topic, partition)) {
break
}
}
}
async processEachBatch(batch) {
const { topic, partition } = batch
const lastFilteredMessage = batch.messages[batch.messages.length - 1]
const pause = () => {
this.consumerGroup.pause([{ topic, partitions: [partition] }])
return () => this.consumerGroup.resume([{ topic, partitions: [partition] }])
}
try {
await this.eachBatch({
batch,
resolveOffset: offset => {
/**
* The transactional producer generates a control record after committing the transaction.
* The control record is the last record on the RecordBatch, and it is filtered before it
* reaches the eachBatch callback. When disabling auto-resolve, the user-land code won't
* be able to resolve the control record offset, since it never reaches the callback,
* causing stuck consumers as the consumer will never move the offset marker.
*
* When the last offset of the batch is resolved, we should automatically resolve
* the control record offset as this entry doesn't have any meaning to the user-land code,
* and won't interfere with the stream processing.
*
* @see https://github.com/apache/kafka/blob/9aa660786e46c1efbf5605a6a69136a1dac6edb9/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java#L1499-L1505
*/
const offsetToResolve =
lastFilteredMessage && isSameOffset(offset, lastFilteredMessage.offset)
? batch.lastOffset()
: offset
this.consumerGroup.resolveOffset({ topic, partition, offset: offsetToResolve })
},
heartbeat: () => this.heartbeat(),
/**
* Pause consumption for the current topic-partition being processed
*/
pause,
/**
* Commit offsets if provided. Otherwise commit most recent resolved offsets
* if the autoCommit conditions are met.
*
* @param {import('../../types').OffsetsByTopicPartition} [offsets] Optional.
*/
commitOffsetsIfNecessary: async offsets => {
return offsets
? this.consumerGroup.commitOffsets(offsets)
: this.consumerGroup.commitOffsetsIfNecessary()
},
uncommittedOffsets: () => this.consumerGroup.uncommittedOffsets(),
isRunning: () => this.running,
isStale: () => this.consumerGroup.hasSeekOffset({ topic, partition }),
})
} catch (e) {
if (!isKafkaJSError(e)) {
this.logger.error(`Error when calling eachBatch`, {
topic,
partition,
offset: batch.firstOffset(),
stack: e.stack,
error: e,
})
}
// eachBatch has a special resolveOffset which can be used
// to keep track of the messages
await this.autoCommitOffsets()
throw e
}
// resolveOffset for the last offset can be disabled to allow the users of eachBatch to
// stop their consumers without resolving unprocessed offsets (issues/18)
if (this.eachBatchAutoResolve) {
this.consumerGroup.resolveOffset({ topic, partition, offset: batch.lastOffset() })
}
}
async fetch(nodeId) {
if (!this.running) {
this.logger.debug('consumer not running, exiting', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
return []
}
const startFetch = Date.now()
this.instrumentationEmitter.emit(FETCH_START, { nodeId })
const batches = await this.consumerGroup.fetch(nodeId)
this.instrumentationEmitter.emit(FETCH, {
/**
* PR #570 removed support for the number of batches in this instrumentation event;
* The new implementation uses an async generation to deliver the batches, which makes
* this number impossible to get. The number is set to 0 to keep the event backward
* compatible until we bump KafkaJS to version 2, following the end of node 8 LTS.
*
* @since 2019-11-29
*/
numberOfBatches: 0,
duration: Date.now() - startFetch,
nodeId,
})
if (batches.length === 0) {
await this.heartbeat()
}
return batches
}
async handleBatch(batch) {
if (!this.running) {
this.logger.debug('consumer not running, exiting', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
})
return
}
/** @param {import('./batch')} batch */
const onBatch = async batch => {
const startBatchProcess = Date.now()
const payload = {
topic: batch.topic,
partition: batch.partition,
highWatermark: batch.highWatermark,
offsetLag: batch.offsetLag(),
/**
* @since 2019-06-24 (>= 1.8.0)
*
* offsetLag returns the lag based on the latest offset in the batch, to
* keep the event backward compatible we just introduced "offsetLagLow"
* which calculates the lag based on the first offset in the batch
*/
offsetLagLow: batch.offsetLagLow(),
batchSize: batch.messages.length,
firstOffset: batch.firstOffset(),
lastOffset: batch.lastOffset(),
}
/**
* If the batch contained only control records or only aborted messages then we still
* need to resolve and auto-commit to ensure the consumer can move forward.
*
* We also need to emit batch instrumentation events to allow any listeners keeping
* track of offsets to know about the latest point of consumption.
*
* Added in #1256
*
* @see https://github.com/apache/kafka/blob/9aa660786e46c1efbf5605a6a69136a1dac6edb9/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java#L1499-L1505
*/
if (batch.isEmptyDueToFiltering()) {
this.instrumentationEmitter.emit(START_BATCH_PROCESS, payload)
this.consumerGroup.resolveOffset({
topic: batch.topic,
partition: batch.partition,
offset: batch.lastOffset(),
})
await this.autoCommitOffsetsIfNecessary()
this.instrumentationEmitter.emit(END_BATCH_PROCESS, {
...payload,
duration: Date.now() - startBatchProcess,
})
await this.heartbeat()
return
}
if (batch.isEmpty()) {
await this.heartbeat()
return
}
this.instrumentationEmitter.emit(START_BATCH_PROCESS, payload)
if (this.eachMessage) {
await this.processEachMessage(batch)
} else if (this.eachBatch) {
await this.processEachBatch(batch)
}
this.instrumentationEmitter.emit(END_BATCH_PROCESS, {
...payload,
duration: Date.now() - startBatchProcess,
})
await this.autoCommitOffsets()
await this.heartbeat()
}
await onBatch(batch)
}
autoCommitOffsets() {
if (this.autoCommit) {
return this.consumerGroup.commitOffsets()
}
}
autoCommitOffsetsIfNecessary() {
if (this.autoCommit) {
return this.consumerGroup.commitOffsetsIfNecessary()
}
}
commitOffsets(offsets) {
if (!this.running) {
this.logger.debug('consumer not running, exiting', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
offsets,
})
return
}
return this.retrier(async (bail, retryCount, retryTime) => {
try {
await this.consumerGroup.commitOffsets(offsets)
} catch (e) {
if (!this.running) {
this.logger.debug('consumer not running, exiting', {
error: e.message,
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
offsets,
})
return
}
if (e.name === 'KafkaJSNotImplemented') {
return bail(e)
}
this.logger.debug('Error while committing offsets, trying again...', {
groupId: this.consumerGroup.groupId,
memberId: this.consumerGroup.memberId,
error: e.message,
stack: e.stack,
retryCount,
retryTime,
offsets,
})
throw e
}
})
}
}