-
-
Notifications
You must be signed in to change notification settings - Fork 530
/
index.js
899 lines (835 loc) · 31.4 KB
/
index.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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
const Long = require('../utils/long')
const Lock = require('../utils/lock')
const { Types: Compression } = require('../protocol/message/compression')
const { requests, lookup } = require('../protocol/requests')
const { KafkaJSNonRetriableError } = require('../errors')
const apiKeys = require('../protocol/requests/apiKeys')
const SASLAuthenticator = require('./saslAuthenticator')
const shuffle = require('../utils/shuffle')
const PRIVATE = {
SHOULD_REAUTHENTICATE: Symbol('private:Broker:shouldReauthenticate'),
SEND_REQUEST: Symbol('private:Broker:sendRequest'),
}
/**
* Each node in a Kafka cluster is called broker. This class contains
* the high-level operations a node can perform.
*
* @type {import("../../types").Broker}
* @param {Connection} connection
* @param {Object} logger
* @param {Object} [versions=null] The object with all available versions and APIs
* supported by this cluster. The output of broker#apiVersions
* @param {number} [authenticationTimeout=1000]
* @param {boolean} [allowAutoTopicCreation=true] If this and the broker config 'auto.create.topics.enable'
* are true, topics that don't exist will be created when
* fetching metadata.
* @param {boolean} [supportAuthenticationProtocol=null] If the server supports the SASLAuthenticate protocol
*/
module.exports = class Broker {
constructor({
connection,
logger,
nodeId = null,
versions = null,
authenticationTimeout = 1000,
reauthenticationThreshold = 10000,
allowAutoTopicCreation = true,
supportAuthenticationProtocol = null,
}) {
this.connection = connection
this.nodeId = nodeId
this.rootLogger = logger
this.logger = logger.namespace('Broker')
this.versions = versions
this.authenticationTimeout = authenticationTimeout
this.reauthenticationThreshold = reauthenticationThreshold
this.allowAutoTopicCreation = allowAutoTopicCreation
this.supportAuthenticationProtocol = supportAuthenticationProtocol
this.authenticatedAt = null
this.sessionLifetime = Long.ZERO
// The lock timeout has twice the connectionTimeout because the same timeout is used
// for the first apiVersions call
const lockTimeout = 2 * this.connection.connectionTimeout + this.authenticationTimeout
this.brokerAddress = `${this.connection.host}:${this.connection.port}`
this.lock = new Lock({
timeout: lockTimeout,
description: `connect to broker ${this.brokerAddress}`,
})
this.lookupRequest = () => {
throw new Error('Broker not connected')
}
}
/**
* @public
* @returns {boolean}
*/
isConnected() {
const { connected, sasl } = this.connection
const isAuthenticated = this.authenticatedAt != null && !this[PRIVATE.SHOULD_REAUTHENTICATE]()
return sasl ? connected && isAuthenticated : connected
}
/**
* @public
* @returns {Promise}
*/
async connect() {
try {
await this.lock.acquire()
if (this.isConnected()) {
return
}
this.authenticatedAt = null
await this.connection.connect()
if (!this.versions) {
this.versions = await this.apiVersions()
}
this.lookupRequest = lookup(this.versions)
if (this.supportAuthenticationProtocol === null) {
try {
this.lookupRequest(apiKeys.SaslAuthenticate, requests.SaslAuthenticate)
this.supportAuthenticationProtocol = true
} catch (_) {
this.supportAuthenticationProtocol = false
}
this.logger.debug(`Verified support for SaslAuthenticate`, {
broker: this.brokerAddress,
supportAuthenticationProtocol: this.supportAuthenticationProtocol,
})
}
if (this.authenticatedAt == null && this.connection.sasl) {
const authenticator = new SASLAuthenticator(
this.connection,
this.rootLogger,
this.versions,
this.supportAuthenticationProtocol
)
await authenticator.authenticate()
this.authenticatedAt = process.hrtime()
this.sessionLifetime = Long.fromValue(authenticator.sessionLifetime)
}
} finally {
await this.lock.release()
}
}
/**
* @public
* @returns {Promise}
*/
async disconnect() {
this.authenticatedAt = null
await this.connection.disconnect()
}
/**
* @public
* @returns {Promise}
*/
async apiVersions() {
let response
const availableVersions = requests.ApiVersions.versions
.map(Number)
.sort()
.reverse()
// Find the best version implemented by the server
for (const candidateVersion of availableVersions) {
try {
const apiVersions = requests.ApiVersions.protocol({ version: candidateVersion })
response = await this[PRIVATE.SEND_REQUEST]({
...apiVersions(),
requestTimeout: this.connection.connectionTimeout,
})
break
} catch (e) {
if (e.type !== 'UNSUPPORTED_VERSION') {
throw e
}
}
}
if (!response) {
throw new KafkaJSNonRetriableError('API Versions not supported')
}
return response.apiVersions.reduce(
(obj, version) =>
Object.assign(obj, {
[version.apiKey]: {
minVersion: version.minVersion,
maxVersion: version.maxVersion,
},
}),
{}
)
}
/**
* @public
* @type {import("../../types").Broker['metadata']}
* @param {Array} [topics=[]] An array of topics to fetch metadata for.
* If no topics are specified fetch metadata for all topics
*/
async metadata(topics = []) {
const metadata = this.lookupRequest(apiKeys.Metadata, requests.Metadata)
const shuffledTopics = shuffle(topics)
return await this[PRIVATE.SEND_REQUEST](
metadata({ topics: shuffledTopics, allowAutoTopicCreation: this.allowAutoTopicCreation })
)
}
/**
* @public
* @param {Array} topicData An array of messages per topic and per partition, example:
* [
* {
* topic: 'test-topic-1',
* partitions: [
* {
* partition: 0,
* firstSequence: 0,
* messages: [
* { key: '1', value: 'A' },
* { key: '2', value: 'B' },
* ]
* },
* {
* partition: 1,
* firstSequence: 0,
* messages: [
* { key: '3', value: 'C' },
* ]
* }
* ]
* },
* {
* topic: 'test-topic-2',
* partitions: [
* {
* partition: 4,
* firstSequence: 0,
* messages: [
* { key: '32', value: 'E' },
* ]
* },
* ]
* },
* ]
* @param {number} [acks=-1] Control the number of required acks.
* -1 = all replicas must acknowledge
* 0 = no acknowledgments
* 1 = only waits for the leader to acknowledge
* @param {number} [timeout=30000] The time to await a response in ms
* @param {string} [transactionalId=null]
* @param {number} [producerId=-1] Broker assigned producerId
* @param {number} [producerEpoch=0] Broker assigned producerEpoch
* @param {Compression.Types} [compression=Compression.Types.None] Compression codec
* @returns {Promise}
*/
async produce({
topicData,
transactionalId,
producerId,
producerEpoch,
acks = -1,
timeout = 30000,
compression = Compression.None,
}) {
const produce = this.lookupRequest(apiKeys.Produce, requests.Produce)
return await this[PRIVATE.SEND_REQUEST](
produce({
acks,
timeout,
compression,
topicData,
transactionalId,
producerId,
producerEpoch,
})
)
}
/**
* @public
* @param {number} replicaId=-1 Broker id of the follower. For normal consumers, use -1
* @param {number} isolationLevel=1 This setting controls the visibility of transactional records. Default READ_COMMITTED.
* @param {number} maxWaitTime=5000 Maximum time in ms to wait for the response
* @param {number} minBytes=1 Minimum bytes to accumulate in the response
* @param {number} maxBytes=10485760 Maximum bytes to accumulate in the response. Note that this is
* not an absolute maximum, if the first message in the first non-empty
* partition of the fetch is larger than this value, the message will still
* be returned to ensure that progress can be made. Default 10MB.
* @param {Array} topics Topics to fetch
* [
* {
* topic: 'topic-name',
* partitions: [
* {
* partition: 0,
* fetchOffset: '4124',
* maxBytes: 2048
* }
* ]
* }
* ]
* @param {string} rackId='' A rack identifier for this client. This can be any string value which indicates where this
* client is physically located. It corresponds with the broker config `broker.rack`.
* @returns {Promise}
*/
async fetch({
replicaId,
isolationLevel,
maxWaitTime = 5000,
minBytes = 1,
maxBytes = 10485760,
topics,
rackId = '',
}) {
// TODO: validate topics not null/empty
const fetch = this.lookupRequest(apiKeys.Fetch, requests.Fetch)
// Shuffle topic-partitions to ensure fair response allocation across partitions (KIP-74)
const flattenedTopicPartitions = topics.reduce((topicPartitions, { topic, partitions }) => {
partitions.forEach(partition => {
topicPartitions.push({ topic, partition })
})
return topicPartitions
}, [])
const shuffledTopicPartitions = shuffle(flattenedTopicPartitions)
// Consecutive partitions for the same topic can be combined into a single `topic` entry
const consolidatedTopicPartitions = shuffledTopicPartitions.reduce(
(topicPartitions, { topic, partition }) => {
const last = topicPartitions[topicPartitions.length - 1]
if (last != null && last.topic === topic) {
topicPartitions[topicPartitions.length - 1].partitions.push(partition)
} else {
topicPartitions.push({ topic, partitions: [partition] })
}
return topicPartitions
},
[]
)
return await this[PRIVATE.SEND_REQUEST](
fetch({
replicaId,
isolationLevel,
maxWaitTime,
minBytes,
maxBytes,
topics: consolidatedTopicPartitions,
rackId,
})
)
}
/**
* @public
* @param {string} groupId The group id
* @param {number} groupGenerationId The generation of the group
* @param {string} memberId The member id assigned by the group coordinator
* @returns {Promise}
*/
async heartbeat({ groupId, groupGenerationId, memberId }) {
const heartbeat = this.lookupRequest(apiKeys.Heartbeat, requests.Heartbeat)
return await this[PRIVATE.SEND_REQUEST](heartbeat({ groupId, groupGenerationId, memberId }))
}
/**
* @public
* @param {string} groupId The unique group id
* @param {CoordinatorType} coordinatorType The type of coordinator to find
* @returns {Promise}
*/
async findGroupCoordinator({ groupId, coordinatorType }) {
// TODO: validate groupId, mandatory
const findCoordinator = this.lookupRequest(apiKeys.GroupCoordinator, requests.GroupCoordinator)
return await this[PRIVATE.SEND_REQUEST](findCoordinator({ groupId, coordinatorType }))
}
/**
* @public
* @param {string} groupId The unique group id
* @param {number} sessionTimeout The coordinator considers the consumer dead if it receives
* no heartbeat after this timeout in ms
* @param {number} rebalanceTimeout The maximum time that the coordinator will wait for each member
* to rejoin when rebalancing the group
* @param {string} [memberId=""] The assigned consumer id or an empty string for a new consumer
* @param {string} [protocolType="consumer"] Unique name for class of protocols implemented by group
* @param {Array} groupProtocols List of protocols that the member supports (assignment strategy)
* [{ name: 'AssignerName', metadata: '{"version": 1, "topics": []}' }]
* @returns {Promise}
*/
async joinGroup({
groupId,
sessionTimeout,
rebalanceTimeout,
memberId = '',
protocolType = 'consumer',
groupProtocols,
}) {
const joinGroup = this.lookupRequest(apiKeys.JoinGroup, requests.JoinGroup)
const makeRequest = (assignedMemberId = memberId) =>
this[PRIVATE.SEND_REQUEST](
joinGroup({
groupId,
sessionTimeout,
rebalanceTimeout,
memberId: assignedMemberId,
protocolType,
groupProtocols,
})
)
try {
return await makeRequest()
} catch (error) {
if (error.name === 'KafkaJSMemberIdRequired') {
return makeRequest(error.memberId)
}
throw error
}
}
/**
* @public
* @param {string} groupId
* @param {string} memberId
* @returns {Promise}
*/
async leaveGroup({ groupId, memberId }) {
const leaveGroup = this.lookupRequest(apiKeys.LeaveGroup, requests.LeaveGroup)
return await this[PRIVATE.SEND_REQUEST](leaveGroup({ groupId, memberId }))
}
/**
* @public
* @param {string} groupId
* @param {number} generationId
* @param {string} memberId
* @param {object} groupAssignment
* @returns {Promise}
*/
async syncGroup({ groupId, generationId, memberId, groupAssignment }) {
const syncGroup = this.lookupRequest(apiKeys.SyncGroup, requests.SyncGroup)
return await this[PRIVATE.SEND_REQUEST](
syncGroup({
groupId,
generationId,
memberId,
groupAssignment,
})
)
}
/**
* @public
* @param {number} replicaId=-1 Broker id of the follower. For normal consumers, use -1
* @param {number} isolationLevel=1 This setting controls the visibility of transactional records (default READ_COMMITTED, Kafka >0.11 only)
* @param {TopicPartitionOffset[]} topics e.g:
*
* @typedef {Object} TopicPartitionOffset
* @property {string} topic
* @property {PartitionOffset[]} partitions
*
* @typedef {Object} PartitionOffset
* @property {number} partition
* @property {number} [timestamp=-1]
*
*
* @returns {Promise}
*/
async listOffsets({ replicaId, isolationLevel, topics }) {
const listOffsets = this.lookupRequest(apiKeys.ListOffsets, requests.ListOffsets)
const result = await this[PRIVATE.SEND_REQUEST](
listOffsets({ replicaId, isolationLevel, topics })
)
// ListOffsets >= v1 will return a single `offset` rather than an array of `offsets` (ListOffsets V0).
// Normalize to just return `offset`.
for (const response of result.responses) {
response.partitions = response.partitions.map(({ offsets, ...partitionData }) => {
return offsets ? { ...partitionData, offset: offsets.pop() } : partitionData
})
}
return result
}
/**
* @public
* @param {string} groupId
* @param {number} groupGenerationId
* @param {string} memberId
* @param {number} [retentionTime=-1] -1 signals to the broker that its default configuration
* should be used.
* @param {object} topics Topics to commit offsets, e.g:
* [
* {
* topic: 'topic-name',
* partitions: [
* { partition: 0, offset: '11' }
* ]
* }
* ]
* @returns {Promise}
*/
async offsetCommit({ groupId, groupGenerationId, memberId, retentionTime, topics }) {
const offsetCommit = this.lookupRequest(apiKeys.OffsetCommit, requests.OffsetCommit)
return await this[PRIVATE.SEND_REQUEST](
offsetCommit({
groupId,
groupGenerationId,
memberId,
retentionTime,
topics,
})
)
}
/**
* @public
* @param {string} groupId
* @param {object} topics - If the topic array is null fetch offsets for all topics. e.g:
* [
* {
* topic: 'topic-name',
* partitions: [
* { partition: 0 }
* ]
* }
* ]
* @returns {Promise}
*/
async offsetFetch({ groupId, topics }) {
const offsetFetch = this.lookupRequest(apiKeys.OffsetFetch, requests.OffsetFetch)
return await this[PRIVATE.SEND_REQUEST](offsetFetch({ groupId, topics }))
}
/**
* @public
* @param {Array} groupIds
* @returns {Promise}
*/
async describeGroups({ groupIds }) {
const describeGroups = this.lookupRequest(apiKeys.DescribeGroups, requests.DescribeGroups)
return await this[PRIVATE.SEND_REQUEST](describeGroups({ groupIds }))
}
/**
* @public
* @param {Array} topics e.g:
* [
* {
* topic: 'topic-name',
* numPartitions: 1,
* replicationFactor: 1
* }
* ]
* @param {boolean} [validateOnly=false] If this is true, the request will be validated, but the topic
* won't be created
* @param {number} [timeout=5000] The time in ms to wait for a topic to be completely created
* on the controller node
* @returns {Promise}
*/
async createTopics({ topics, validateOnly = false, timeout = 5000 }) {
const createTopics = this.lookupRequest(apiKeys.CreateTopics, requests.CreateTopics)
return await this[PRIVATE.SEND_REQUEST](createTopics({ topics, validateOnly, timeout }))
}
/**
* @public
* @param {Array} topicPartitions e.g:
* [
* {
* topic: 'topic-name',
* count: 3,
* assignments: []
* }
* ]
* @param {boolean} [validateOnly=false] If this is true, the request will be validated, but the topic
* won't be created
* @param {number} [timeout=5000] The time in ms to wait for a topic to be completely created
* on the controller node
* @returns {Promise<void>}
*/
async createPartitions({ topicPartitions, validateOnly = false, timeout = 5000 }) {
const createPartitions = this.lookupRequest(apiKeys.CreatePartitions, requests.CreatePartitions)
return await this[PRIVATE.SEND_REQUEST](
createPartitions({ topicPartitions, validateOnly, timeout })
)
}
/**
* @public
* @param {Array<string>} topics An array of topics to be deleted
* @param {number} [timeout=5000] The time in ms to wait for a topic to be completely deleted on the
* controller node. Values <= 0 will trigger topic deletion and return
* immediately
* @returns {Promise}
*/
async deleteTopics({ topics, timeout = 5000 }) {
const deleteTopics = this.lookupRequest(apiKeys.DeleteTopics, requests.DeleteTopics)
return await this[PRIVATE.SEND_REQUEST](deleteTopics({ topics, timeout }))
}
/**
* @public
* @param {Array<ResourceQuery>} resources
* [{
* type: RESOURCE_TYPES.TOPIC,
* name: 'topic-name',
* configNames: ['compression.type', 'retention.ms']
* }]
* @param {boolean} [includeSynonyms=false]
* @returns {Promise}
*/
async describeConfigs({ resources, includeSynonyms = false }) {
const describeConfigs = this.lookupRequest(apiKeys.DescribeConfigs, requests.DescribeConfigs)
return await this[PRIVATE.SEND_REQUEST](describeConfigs({ resources, includeSynonyms }))
}
/**
* @public
* @param {Array<ResourceConfig>} resources
* [{
* type: RESOURCE_TYPES.TOPIC,
* name: 'topic-name',
* configEntries: [
* {
* name: 'cleanup.policy',
* value: 'compact'
* }
* ]
* }]
* @param {boolean} [validateOnly=false]
* @returns {Promise}
*/
async alterConfigs({ resources, validateOnly = false }) {
const alterConfigs = this.lookupRequest(apiKeys.AlterConfigs, requests.AlterConfigs)
return await this[PRIVATE.SEND_REQUEST](alterConfigs({ resources, validateOnly }))
}
/**
* Send an `InitProducerId` request to fetch a PID and bump the producer epoch.
*
* Request should be made to the transaction coordinator.
* @public
* @param {number} transactionTimeout The time in ms to wait for before aborting idle transactions
* @param {number} [transactionalId] The transactional id or null if the producer is not transactional
* @returns {Promise}
*/
async initProducerId({ transactionalId, transactionTimeout }) {
const initProducerId = this.lookupRequest(apiKeys.InitProducerId, requests.InitProducerId)
return await this[PRIVATE.SEND_REQUEST](initProducerId({ transactionalId, transactionTimeout }))
}
/**
* Send an `AddPartitionsToTxn` request to mark a TopicPartition as participating in the transaction.
*
* Request should be made to the transaction coordinator.
* @public
* @param {string} transactionalId The transactional id corresponding to the transaction.
* @param {number} producerId Current producer id in use by the transactional id.
* @param {number} producerEpoch Current epoch associated with the producer id.
* @param {object[]} topics e.g:
* [
* {
* topic: 'topic-name',
* partitions: [ 0, 1]
* }
* ]
* @returns {Promise}
*/
async addPartitionsToTxn({ transactionalId, producerId, producerEpoch, topics }) {
const addPartitionsToTxn = this.lookupRequest(
apiKeys.AddPartitionsToTxn,
requests.AddPartitionsToTxn
)
return await this[PRIVATE.SEND_REQUEST](
addPartitionsToTxn({ transactionalId, producerId, producerEpoch, topics })
)
}
/**
* Send an `AddOffsetsToTxn` request.
*
* Request should be made to the transaction coordinator.
* @public
* @param {string} transactionalId The transactional id corresponding to the transaction.
* @param {number} producerId Current producer id in use by the transactional id.
* @param {number} producerEpoch Current epoch associated with the producer id.
* @param {string} groupId The unique group identifier (for the consumer group)
* @returns {Promise}
*/
async addOffsetsToTxn({ transactionalId, producerId, producerEpoch, groupId }) {
const addOffsetsToTxn = this.lookupRequest(apiKeys.AddOffsetsToTxn, requests.AddOffsetsToTxn)
return await this[PRIVATE.SEND_REQUEST](
addOffsetsToTxn({ transactionalId, producerId, producerEpoch, groupId })
)
}
/**
* Send a `TxnOffsetCommit` request to persist the offsets in the `__consumer_offsets` topics.
*
* Request should be made to the consumer coordinator.
* @public
* @param {OffsetCommitTopic[]} topics
* @param {string} transactionalId The transactional id corresponding to the transaction.
* @param {string} groupId The unique group identifier (for the consumer group)
* @param {number} producerId Current producer id in use by the transactional id.
* @param {number} producerEpoch Current epoch associated with the producer id.
* @param {OffsetCommitTopic[]} topics
*
* @typedef {Object} OffsetCommitTopic
* @property {string} topic
* @property {OffsetCommitTopicPartition[]} partitions
*
* @typedef {Object} OffsetCommitTopicPartition
* @property {number} partition
* @property {number} offset
* @property {string} [metadata]
*
* @returns {Promise}
*/
async txnOffsetCommit({ transactionalId, groupId, producerId, producerEpoch, topics }) {
const txnOffsetCommit = this.lookupRequest(apiKeys.TxnOffsetCommit, requests.TxnOffsetCommit)
return await this[PRIVATE.SEND_REQUEST](
txnOffsetCommit({ transactionalId, groupId, producerId, producerEpoch, topics })
)
}
/**
* Send an `EndTxn` request to indicate transaction should be committed or aborted.
*
* Request should be made to the transaction coordinator.
* @public
* @param {string} transactionalId The transactional id corresponding to the transaction.
* @param {number} producerId Current producer id in use by the transactional id.
* @param {number} producerEpoch Current epoch associated with the producer id.
* @param {boolean} transactionResult The result of the transaction (false = ABORT, true = COMMIT)
* @returns {Promise}
*/
async endTxn({ transactionalId, producerId, producerEpoch, transactionResult }) {
const endTxn = this.lookupRequest(apiKeys.EndTxn, requests.EndTxn)
return await this[PRIVATE.SEND_REQUEST](
endTxn({ transactionalId, producerId, producerEpoch, transactionResult })
)
}
/**
* Send request for list of groups
* @public
* @returns {Promise}
*/
async listGroups() {
const listGroups = this.lookupRequest(apiKeys.ListGroups, requests.ListGroups)
return await this[PRIVATE.SEND_REQUEST](listGroups())
}
/**
* Send request to delete groups
* @param {Array<string>} groupIds
* @public
* @returns {Promise}
*/
async deleteGroups(groupIds) {
const deleteGroups = this.lookupRequest(apiKeys.DeleteGroups, requests.DeleteGroups)
return await this[PRIVATE.SEND_REQUEST](deleteGroups(groupIds))
}
/**
* Send request to delete records
* @public
* @param {Array<Object>} topics
* [
* {
* topic: 'my-topic-name',
* partitions: [
* { partition: 0, offset 2 },
* { partition: 1, offset 4 },
* ],
* }
* ]
* @returns {Promise<Array>} example:
* {
* throttleTime: 0
* [
* {
* topic: 'my-topic-name',
* partitions: [
* { partition: 0, lowWatermark: '2n', errorCode: 0 },
* { partition: 1, lowWatermark: '4n', errorCode: 0 },
* ],
* },
* ]
* }
*/
async deleteRecords({ topics }) {
const deleteRecords = this.lookupRequest(apiKeys.DeleteRecords, requests.DeleteRecords)
return await this[PRIVATE.SEND_REQUEST](deleteRecords({ topics }))
}
/**
* @public
* @param {Array} ACL e.g:
* [
* {
* resourceType: AclResourceTypes.TOPIC,
* resourceName: 'topic-name',
* resourcePatternType: ResourcePatternTypes.LITERAL,
* principal: 'User:bob',
* host: '*',
* operation: AclOperationTypes.ALL,
* permissionType: AclPermissionTypes.DENY,
* }
* ]
* @returns {Promise<void>}
*/
async createAcls({ acl }) {
const createAcls = this.lookupRequest(apiKeys.CreateAcls, requests.CreateAcls)
return await this[PRIVATE.SEND_REQUEST](createAcls({ creations: acl }))
}
/**
* @public
* @param {number} resourceType The type of resource
* @param {string} resourceName The name of the resource
* @param {number} resourcePatternType The resource pattern type filter
* @param {string} principal The principal name
* @param {string} host The hostname
* @param {number} operation The type of operation
* @param {number} permissionType The type of permission
* @returns {Promise<void>}
*/
async describeAcls({
resourceType,
resourceName,
resourcePatternType,
principal,
host,
operation,
permissionType,
}) {
const describeAcls = this.lookupRequest(apiKeys.DescribeAcls, requests.DescribeAcls)
return await this[PRIVATE.SEND_REQUEST](
describeAcls({
resourceType,
resourceName,
resourcePatternType,
principal,
host,
operation,
permissionType,
})
)
}
/**
* @public
* @param {number} resourceType The type of resource
* @param {string} resourceName The name of the resource
* @param {number} resourcePatternType The resource pattern type filter
* @param {string} principal The principal name
* @param {string} host The hostname
* @param {number} operation The type of operation
* @param {number} permissionType The type of permission
* @returns {Promise<void>}
*/
async deleteAcls({ filters }) {
const deleteAcls = this.lookupRequest(apiKeys.DeleteAcls, requests.DeleteAcls)
return await this[PRIVATE.SEND_REQUEST](deleteAcls({ filters }))
}
/***
* @private
*/
[PRIVATE.SHOULD_REAUTHENTICATE]() {
if (this.sessionLifetime.equals(Long.ZERO)) {
return false
}
if (this.authenticatedAt == null) {
return true
}
const [secondsSince, remainingNanosSince] = process.hrtime(this.authenticatedAt)
const millisSince = Long.fromValue(secondsSince)
.multiply(1000)
.add(Long.fromValue(remainingNanosSince).divide(1000000))
const reauthenticateAt = millisSince.add(this.reauthenticationThreshold)
return reauthenticateAt.greaterThanOrEqual(this.sessionLifetime)
}
/**
* @private
*/
async [PRIVATE.SEND_REQUEST](protocolRequest) {
try {
return await this.connection.send(protocolRequest)
} catch (e) {
if (e.name === 'KafkaJSConnectionClosedError') {
await this.disconnect()
}
throw e
}
}
}