-
-
Notifications
You must be signed in to change notification settings - Fork 532
/
Copy pathindex.js
1606 lines (1392 loc) · 48.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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const createRetry = require('../retry')
const waitFor = require('../utils/waitFor')
const groupBy = require('../utils/groupBy')
const createConsumer = require('../consumer')
const InstrumentationEventEmitter = require('../instrumentation/emitter')
const { events, wrap: wrapEvent, unwrap: unwrapEvent } = require('./instrumentationEvents')
const { LEVELS } = require('../loggers')
const {
KafkaJSNonRetriableError,
KafkaJSDeleteGroupsError,
KafkaJSBrokerNotFound,
KafkaJSDeleteTopicRecordsError,
KafkaJSAggregateError,
} = require('../errors')
const { staleMetadata } = require('../protocol/error')
const CONFIG_RESOURCE_TYPES = require('../protocol/configResourceTypes')
const ACL_RESOURCE_TYPES = require('../protocol/aclResourceTypes')
const ACL_OPERATION_TYPES = require('../protocol/aclOperationTypes')
const ACL_PERMISSION_TYPES = require('../protocol/aclPermissionTypes')
const RESOURCE_PATTERN_TYPES = require('../protocol/resourcePatternTypes')
const { EARLIEST_OFFSET, LATEST_OFFSET } = require('../constants')
const { CONNECT, DISCONNECT } = events
const NO_CONTROLLER_ID = -1
const { values, keys, entries } = Object
const eventNames = values(events)
const eventKeys = keys(events)
.map(key => `admin.events.${key}`)
.join(', ')
const retryOnLeaderNotAvailable = (fn, opts = {}) => {
const callback = async () => {
try {
return await fn()
} catch (e) {
if (e.type !== 'LEADER_NOT_AVAILABLE') {
throw e
}
return false
}
}
return waitFor(callback, opts)
}
const isConsumerGroupRunning = description => ['Empty', 'Dead'].includes(description.state)
const findTopicPartitions = async (cluster, topic) => {
await cluster.addTargetTopic(topic)
await cluster.refreshMetadataIfNecessary()
return cluster
.findTopicPartitionMetadata(topic)
.map(({ partitionId }) => partitionId)
.sort()
}
const indexByPartition = array =>
array.reduce(
(obj, { partition, ...props }) => Object.assign(obj, { [partition]: { ...props } }),
{}
)
/**
*
* @param {Object} params
* @param {import("../../types").Logger} params.logger
* @param {InstrumentationEventEmitter} [params.instrumentationEmitter]
* @param {import('../../types').RetryOptions} params.retry
* @param {import("../../types").Cluster} params.cluster
*
* @returns {import("../../types").Admin}
*/
module.exports = ({
logger: rootLogger,
instrumentationEmitter: rootInstrumentationEmitter,
retry,
cluster,
}) => {
const logger = rootLogger.namespace('Admin')
const instrumentationEmitter = rootInstrumentationEmitter || new InstrumentationEventEmitter()
/**
* @returns {Promise}
*/
const connect = async () => {
await cluster.connect()
instrumentationEmitter.emit(CONNECT)
}
/**
* @return {Promise}
*/
const disconnect = async () => {
await cluster.disconnect()
instrumentationEmitter.emit(DISCONNECT)
}
/**
* @return {Promise}
*/
const listTopics = async () => {
const { topicMetadata } = await cluster.metadata()
const topics = topicMetadata.map(t => t.topic)
return topics
}
/**
* @param {Object} request
* @param {array} request.topics
* @param {boolean} [request.validateOnly=false]
* @param {number} [request.timeout=5000]
* @param {boolean} [request.waitForLeaders=true]
* @return {Promise}
*/
const createTopics = async ({ topics, validateOnly, timeout, waitForLeaders = true }) => {
if (!topics || !Array.isArray(topics)) {
throw new KafkaJSNonRetriableError(`Invalid topics array ${topics}`)
}
if (topics.filter(({ topic }) => typeof topic !== 'string').length > 0) {
throw new KafkaJSNonRetriableError(
'Invalid topics array, the topic names have to be a valid string'
)
}
const topicNames = new Set(topics.map(({ topic }) => topic))
if (topicNames.size < topics.length) {
throw new KafkaJSNonRetriableError(
'Invalid topics array, it cannot have multiple entries for the same topic'
)
}
for (const { topic, configEntries } of topics) {
if (configEntries == null) {
continue
}
if (!Array.isArray(configEntries)) {
throw new KafkaJSNonRetriableError(
`Invalid configEntries for topic "${topic}", must be an array`
)
}
configEntries.forEach((entry, index) => {
if (typeof entry !== 'object' || entry == null) {
throw new KafkaJSNonRetriableError(
`Invalid configEntries for topic "${topic}". Entry ${index} must be an object`
)
}
for (const requiredProperty of ['name', 'value']) {
if (
!Object.prototype.hasOwnProperty.call(entry, requiredProperty) ||
typeof entry[requiredProperty] !== 'string'
) {
throw new KafkaJSNonRetriableError(
`Invalid configEntries for topic "${topic}". Entry ${index} must have a valid "${requiredProperty}" property`
)
}
}
})
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.refreshMetadata()
const broker = await cluster.findControllerBroker()
await broker.createTopics({ topics, validateOnly, timeout })
if (waitForLeaders) {
const topicNamesArray = Array.from(topicNames.values())
await retryOnLeaderNotAvailable(async () => await broker.metadata(topicNamesArray), {
delay: 100,
maxWait: timeout,
timeoutMessage: 'Timed out while waiting for topic leaders',
})
}
return true
} catch (e) {
if (e.type === 'NOT_CONTROLLER') {
logger.warn('Could not create topics', { error: e.message, retryCount, retryTime })
throw e
}
if (e instanceof KafkaJSAggregateError) {
if (e.errors.every(error => error.type === 'TOPIC_ALREADY_EXISTS')) {
return false
}
}
bail(e)
}
})
}
/**
* @param {array} topicPartitions
* @param {boolean} [validateOnly=false]
* @param {number} [timeout=5000]
* @return {Promise<void>}
*/
const createPartitions = async ({ topicPartitions, validateOnly, timeout }) => {
if (!topicPartitions || !Array.isArray(topicPartitions)) {
throw new KafkaJSNonRetriableError(`Invalid topic partitions array ${topicPartitions}`)
}
if (topicPartitions.length === 0) {
throw new KafkaJSNonRetriableError(`Empty topic partitions array`)
}
if (topicPartitions.filter(({ topic }) => typeof topic !== 'string').length > 0) {
throw new KafkaJSNonRetriableError(
'Invalid topic partitions array, the topic names have to be a valid string'
)
}
const topicNames = new Set(topicPartitions.map(({ topic }) => topic))
if (topicNames.size < topicPartitions.length) {
throw new KafkaJSNonRetriableError(
'Invalid topic partitions array, it cannot have multiple entries for the same topic'
)
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.refreshMetadata()
const broker = await cluster.findControllerBroker()
await broker.createPartitions({ topicPartitions, validateOnly, timeout })
} catch (e) {
if (e.type === 'NOT_CONTROLLER') {
logger.warn('Could not create topics', { error: e.message, retryCount, retryTime })
throw e
}
bail(e)
}
})
}
/**
* @param {string[]} topics
* @param {number} [timeout=5000]
* @return {Promise}
*/
const deleteTopics = async ({ topics, timeout }) => {
if (!topics || !Array.isArray(topics)) {
throw new KafkaJSNonRetriableError(`Invalid topics array ${topics}`)
}
if (topics.filter(topic => typeof topic !== 'string').length > 0) {
throw new KafkaJSNonRetriableError('Invalid topics array, the names must be a valid string')
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.refreshMetadata()
const broker = await cluster.findControllerBroker()
await broker.deleteTopics({ topics, timeout })
// Remove deleted topics
for (const topic of topics) {
cluster.targetTopics.delete(topic)
}
await cluster.refreshMetadata()
} catch (e) {
if (['NOT_CONTROLLER', 'UNKNOWN_TOPIC_OR_PARTITION'].includes(e.type)) {
logger.warn('Could not delete topics', { error: e.message, retryCount, retryTime })
throw e
}
if (e.type === 'REQUEST_TIMED_OUT') {
logger.error(
'Could not delete topics, check if "delete.topic.enable" is set to "true" (the default value is "false") or increase the timeout',
{
error: e.message,
retryCount,
retryTime,
}
)
}
bail(e)
}
})
}
/**
* @param {string} topic
*/
const fetchTopicOffsets = async topic => {
if (!topic || typeof topic !== 'string') {
throw new KafkaJSNonRetriableError(`Invalid topic ${topic}`)
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.addTargetTopic(topic)
await cluster.refreshMetadataIfNecessary()
const metadata = cluster.findTopicPartitionMetadata(topic)
const high = await cluster.fetchTopicsOffset([
{
topic,
fromBeginning: false,
partitions: metadata.map(p => ({ partition: p.partitionId })),
},
])
const low = await cluster.fetchTopicsOffset([
{
topic,
fromBeginning: true,
partitions: metadata.map(p => ({ partition: p.partitionId })),
},
])
const { partitions: highPartitions } = high.pop()
const { partitions: lowPartitions } = low.pop()
return highPartitions.map(({ partition, offset }) => ({
partition,
offset,
high: offset,
low: lowPartitions.find(({ partition: lowPartition }) => lowPartition === partition)
.offset,
}))
} catch (e) {
if (e.type === 'UNKNOWN_TOPIC_OR_PARTITION') {
await cluster.refreshMetadata()
throw e
}
bail(e)
}
})
}
/**
* @param {string} topic
* @param {number} [timestamp]
*/
const fetchTopicOffsetsByTimestamp = async (topic, timestamp) => {
if (!topic || typeof topic !== 'string') {
throw new KafkaJSNonRetriableError(`Invalid topic ${topic}`)
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.addTargetTopic(topic)
await cluster.refreshMetadataIfNecessary()
const metadata = cluster.findTopicPartitionMetadata(topic)
const partitions = metadata.map(p => ({ partition: p.partitionId }))
const high = await cluster.fetchTopicsOffset([
{
topic,
fromBeginning: false,
partitions,
},
])
const { partitions: highPartitions } = high.pop()
const offsets = await cluster.fetchTopicsOffset([
{
topic,
fromTimestamp: timestamp,
partitions,
},
])
const { partitions: lowPartitions } = offsets.pop()
return lowPartitions.map(({ partition, offset }) => ({
partition,
offset:
parseInt(offset, 10) >= 0
? offset
: highPartitions.find(({ partition: highPartition }) => highPartition === partition)
.offset,
}))
} catch (e) {
if (e.type === 'UNKNOWN_TOPIC_OR_PARTITION') {
await cluster.refreshMetadata()
throw e
}
bail(e)
}
})
}
/**
* Fetch offsets for a topic or multiple topics
*
* Note: set either topic or topics but not both.
*
* @param {string} groupId
* @param {string[]} topics - list of topics to fetch offsets for, defaults to `[]` which fetches all topics for `groupId`.
* @param {boolean} [resolveOffsets=false]
* @return {Promise}
*/
const fetchOffsets = async ({ groupId, topics, resolveOffsets = false }) => {
if (!groupId) {
throw new KafkaJSNonRetriableError(`Invalid groupId ${groupId}`)
}
if (!topics) {
topics = []
}
if (!Array.isArray(topics)) {
throw new KafkaJSNonRetriableError('Expected topics array to be set')
}
const coordinator = await cluster.findGroupCoordinator({ groupId })
const topicsToFetch = await Promise.all(
topics.map(async topic => {
const partitions = await findTopicPartitions(cluster, topic)
const partitionsToFetch = partitions.map(partition => ({ partition }))
return { topic, partitions: partitionsToFetch }
})
)
let { responses: consumerOffsets } = await coordinator.offsetFetch({
groupId,
topics: topicsToFetch,
})
if (resolveOffsets) {
consumerOffsets = await Promise.all(
consumerOffsets.map(async ({ topic, partitions }) => {
const indexedOffsets = indexByPartition(await fetchTopicOffsets(topic))
const recalculatedPartitions = partitions.map(({ offset, partition, ...props }) => {
let resolvedOffset = offset
if (Number(offset) === EARLIEST_OFFSET) {
resolvedOffset = indexedOffsets[partition].low
}
if (Number(offset) === LATEST_OFFSET) {
resolvedOffset = indexedOffsets[partition].high
}
return {
partition,
offset: resolvedOffset,
...props,
}
})
await setOffsets({ groupId, topic, partitions: recalculatedPartitions })
return {
topic,
partitions: recalculatedPartitions,
}
})
)
}
return consumerOffsets.map(({ topic, partitions }) => {
const completePartitions = partitions.map(({ partition, offset, metadata }) => ({
partition,
offset,
metadata: metadata || null,
}))
return { topic, partitions: completePartitions }
})
}
/**
* @param {string} groupId
* @param {string} topic
* @param {boolean} [earliest=false]
* @return {Promise}
*/
const resetOffsets = async ({ groupId, topic, earliest = false }) => {
if (!groupId) {
throw new KafkaJSNonRetriableError(`Invalid groupId ${groupId}`)
}
if (!topic) {
throw new KafkaJSNonRetriableError(`Invalid topic ${topic}`)
}
const partitions = await findTopicPartitions(cluster, topic)
const partitionsToSeek = partitions.map(partition => ({
partition,
offset: cluster.defaultOffset({ fromBeginning: earliest }),
}))
return setOffsets({ groupId, topic, partitions: partitionsToSeek })
}
/**
* @param {string} groupId
* @param {string} topic
* @param {Array<SeekEntry>} partitions
* @return {Promise}
*
* @typedef {Object} SeekEntry
* @property {number} partition
* @property {string} offset
*/
const setOffsets = async ({ groupId, topic, partitions }) => {
if (!groupId) {
throw new KafkaJSNonRetriableError(`Invalid groupId ${groupId}`)
}
if (!topic) {
throw new KafkaJSNonRetriableError(`Invalid topic ${topic}`)
}
if (!partitions || partitions.length === 0) {
throw new KafkaJSNonRetriableError(`Invalid partitions`)
}
const consumer = createConsumer({
logger: rootLogger.namespace('Admin', LEVELS.NOTHING),
cluster,
groupId,
})
await consumer.subscribe({ topic, fromBeginning: true })
const description = await consumer.describeGroup()
if (!isConsumerGroupRunning(description)) {
throw new KafkaJSNonRetriableError(
`The consumer group must have no running instances, current state: ${description.state}`
)
}
return new Promise((resolve, reject) => {
consumer.on(consumer.events.FETCH, async () =>
consumer
.stop()
.then(resolve)
.catch(reject)
)
consumer
.run({
eachBatchAutoResolve: false,
eachBatch: async () => true,
})
.catch(reject)
// This consumer doesn't need to consume any data
consumer.pause([{ topic }])
for (const seekData of partitions) {
consumer.seek({ topic, ...seekData })
}
})
}
const isBrokerConfig = type =>
[CONFIG_RESOURCE_TYPES.BROKER, CONFIG_RESOURCE_TYPES.BROKER_LOGGER].includes(type)
/**
* Broker configs can only be returned by the target broker
*
* @see
* https://github.com/apache/kafka/blob/821c1ac6641845aeca96a43bc2b946ecec5cba4f/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java#L3783
* https://github.com/apache/kafka/blob/821c1ac6641845aeca96a43bc2b946ecec5cba4f/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java#L2027
*
* @param {Broker} defaultBroker. Broker used in case the configuration is not a broker config
*/
const groupResourcesByBroker = ({ resources, defaultBroker }) =>
groupBy(resources, async ({ type, name: nodeId }) => {
return isBrokerConfig(type)
? await cluster.findBroker({ nodeId: String(nodeId) })
: defaultBroker
})
/**
* @param {Array<ResourceConfigQuery>} resources
* @param {boolean} [includeSynonyms=false]
* @return {Promise}
*
* @typedef {Object} ResourceConfigQuery
* @property {ConfigResourceType} type
* @property {string} name
* @property {Array<String>} [configNames=[]]
*/
const describeConfigs = async ({ resources, includeSynonyms }) => {
if (!resources || !Array.isArray(resources)) {
throw new KafkaJSNonRetriableError(`Invalid resources array ${resources}`)
}
if (resources.length === 0) {
throw new KafkaJSNonRetriableError('Resources array cannot be empty')
}
const validResourceTypes = Object.values(CONFIG_RESOURCE_TYPES)
const invalidType = resources.find(r => !validResourceTypes.includes(r.type))
if (invalidType) {
throw new KafkaJSNonRetriableError(
`Invalid resource type ${invalidType.type}: ${JSON.stringify(invalidType)}`
)
}
const invalidName = resources.find(r => !r.name || typeof r.name !== 'string')
if (invalidName) {
throw new KafkaJSNonRetriableError(
`Invalid resource name ${invalidName.name}: ${JSON.stringify(invalidName)}`
)
}
const invalidConfigs = resources.find(
r => !Array.isArray(r.configNames) && r.configNames != null
)
if (invalidConfigs) {
const { configNames } = invalidConfigs
throw new KafkaJSNonRetriableError(
`Invalid resource configNames ${configNames}: ${JSON.stringify(invalidConfigs)}`
)
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.refreshMetadata()
const controller = await cluster.findControllerBroker()
const resourcerByBroker = await groupResourcesByBroker({
resources,
defaultBroker: controller,
})
const describeConfigsAction = async broker => {
const targetBroker = broker || controller
return targetBroker.describeConfigs({
resources: resourcerByBroker.get(targetBroker),
includeSynonyms,
})
}
const brokers = Array.from(resourcerByBroker.keys())
const responses = await Promise.all(brokers.map(describeConfigsAction))
const responseResources = responses.reduce(
(result, { resources }) => [...result, ...resources],
[]
)
return { resources: responseResources }
} catch (e) {
if (e.type === 'NOT_CONTROLLER') {
logger.warn('Could not describe configs', { error: e.message, retryCount, retryTime })
throw e
}
bail(e)
}
})
}
/**
* @param {Array<ResourceConfig>} resources
* @param {boolean} [validateOnly=false]
* @return {Promise}
*
* @typedef {Object} ResourceConfig
* @property {ConfigResourceType} type
* @property {string} name
* @property {Array<ResourceConfigEntry>} configEntries
*
* @typedef {Object} ResourceConfigEntry
* @property {string} name
* @property {string} value
*/
const alterConfigs = async ({ resources, validateOnly }) => {
if (!resources || !Array.isArray(resources)) {
throw new KafkaJSNonRetriableError(`Invalid resources array ${resources}`)
}
if (resources.length === 0) {
throw new KafkaJSNonRetriableError('Resources array cannot be empty')
}
const validResourceTypes = Object.values(CONFIG_RESOURCE_TYPES)
const invalidType = resources.find(r => !validResourceTypes.includes(r.type))
if (invalidType) {
throw new KafkaJSNonRetriableError(
`Invalid resource type ${invalidType.type}: ${JSON.stringify(invalidType)}`
)
}
const invalidName = resources.find(r => !r.name || typeof r.name !== 'string')
if (invalidName) {
throw new KafkaJSNonRetriableError(
`Invalid resource name ${invalidName.name}: ${JSON.stringify(invalidName)}`
)
}
const invalidConfigs = resources.find(r => !Array.isArray(r.configEntries))
if (invalidConfigs) {
const { configEntries } = invalidConfigs
throw new KafkaJSNonRetriableError(
`Invalid resource configEntries ${configEntries}: ${JSON.stringify(invalidConfigs)}`
)
}
const invalidConfigValue = resources.find(r =>
r.configEntries.some(e => typeof e.name !== 'string' || typeof e.value !== 'string')
)
if (invalidConfigValue) {
throw new KafkaJSNonRetriableError(
`Invalid resource config value: ${JSON.stringify(invalidConfigValue)}`
)
}
const retrier = createRetry(retry)
return retrier(async (bail, retryCount, retryTime) => {
try {
await cluster.refreshMetadata()
const controller = await cluster.findControllerBroker()
const resourcerByBroker = await groupResourcesByBroker({
resources,
defaultBroker: controller,
})
const alterConfigsAction = async broker => {
const targetBroker = broker || controller
return targetBroker.alterConfigs({
resources: resourcerByBroker.get(targetBroker),
validateOnly: !!validateOnly,
})
}
const brokers = Array.from(resourcerByBroker.keys())
const responses = await Promise.all(brokers.map(alterConfigsAction))
const responseResources = responses.reduce(
(result, { resources }) => [...result, ...resources],
[]
)
return { resources: responseResources }
} catch (e) {
if (e.type === 'NOT_CONTROLLER') {
logger.warn('Could not alter configs', { error: e.message, retryCount, retryTime })
throw e
}
bail(e)
}
})
}
/**
* Fetch metadata for provided topics.
*
* If no topics are provided fetch metadata for all topics.
* @see https://kafka.apache.org/protocol#The_Messages_Metadata
*
* @param {Object} [options]
* @param {string[]} [options.topics]
* @return {Promise<TopicsMetadata>}
*
* @typedef {Object} TopicsMetadata
* @property {Array<TopicMetadata>} topics
*
* @typedef {Object} TopicMetadata
* @property {String} name
* @property {Array<PartitionMetadata>} partitions
*
* @typedef {Object} PartitionMetadata
* @property {number} partitionErrorCode Response error code
* @property {number} partitionId Topic partition id
* @property {number} leader The id of the broker acting as leader for this partition.
* @property {Array<number>} replicas The set of all nodes that host this partition.
* @property {Array<number>} isr The set of nodes that are in sync with the leader for this partition.
*/
const fetchTopicMetadata = async ({ topics = [] } = {}) => {
if (topics) {
topics.forEach(topic => {
if (!topic || typeof topic !== 'string') {
throw new KafkaJSNonRetriableError(`Invalid topic ${topic}`)
}
})
}
const metadata = await cluster.metadata({ topics })
return {
topics: metadata.topicMetadata.map(topicMetadata => ({
name: topicMetadata.topic,
partitions: topicMetadata.partitionMetadata,
})),
}
}
/**
* Describe cluster
*
* @return {Promise<ClusterMetadata>}
*
* @typedef {Object} ClusterMetadata
* @property {Array<Broker>} brokers
* @property {Number} controller Current controller id. Returns null if unknown.
* @property {String} clusterId
*
* @typedef {Object} Broker
* @property {Number} nodeId
* @property {String} host
* @property {Number} port
*/
const describeCluster = async () => {
const { brokers: nodes, clusterId, controllerId } = await cluster.metadata({ topics: [] })
const brokers = nodes.map(({ nodeId, host, port }) => ({
nodeId,
host,
port,
}))
const controller =
controllerId == null || controllerId === NO_CONTROLLER_ID ? null : controllerId
return {
brokers,
controller,
clusterId,
}
}
/**
* List groups in a broker
*
* @return {Promise<ListGroups>}
*
* @typedef {Object} ListGroups
* @property {Array<ListGroup>} groups
*
* @typedef {Object} ListGroup
* @property {string} groupId
* @property {string} protocolType
*/
const listGroups = async () => {
await cluster.refreshMetadata()
let groups = []
for (var nodeId in cluster.brokerPool.brokers) {
const broker = await cluster.findBroker({ nodeId })
const response = await broker.listGroups()
groups = groups.concat(response.groups)
}
return { groups }
}
/**
* Describe groups by group ids
* @param {Array<string>} groupIds
*
* @typedef {Object} GroupDescriptions
* @property {Array<GroupDescription>} groups
*
* @return {Promise<GroupDescriptions>}
*/
const describeGroups = async groupIds => {
const coordinatorsForGroup = await Promise.all(
groupIds.map(async groupId => {
const coordinator = await cluster.findGroupCoordinator({ groupId })
return {
coordinator,
groupId,
}
})
)
const groupsByCoordinator = Object.values(
coordinatorsForGroup.reduce((coordinators, { coordinator, groupId }) => {
const group = coordinators[coordinator.nodeId]
if (group) {
coordinators[coordinator.nodeId] = {
...group,
groupIds: [...group.groupIds, groupId],
}
} else {
coordinators[coordinator.nodeId] = { coordinator, groupIds: [groupId] }
}
return coordinators
}, {})
)
const responses = await Promise.all(
groupsByCoordinator.map(async ({ coordinator, groupIds }) => {
const retrier = createRetry(retry)
const { groups } = await retrier(() => coordinator.describeGroups({ groupIds }))
return groups
})
)
const groups = [].concat.apply([], responses)
return { groups }
}
/**
* Delete groups in a broker
*
* @param {string[]} [groupIds]
* @return {Promise<DeleteGroups>}
*
* @typedef {Array} DeleteGroups
* @property {string} groupId
* @property {number} errorCode
*/
const deleteGroups = async groupIds => {
if (!groupIds || !Array.isArray(groupIds)) {
throw new KafkaJSNonRetriableError(`Invalid groupIds array ${groupIds}`)
}
const invalidGroupId = groupIds.some(g => typeof g !== 'string')
if (invalidGroupId) {
throw new KafkaJSNonRetriableError(`Invalid groupId name: ${JSON.stringify(invalidGroupId)}`)
}
const retrier = createRetry(retry)
let results = []
let clonedGroupIds = groupIds.slice()
return retrier(async (bail, retryCount, retryTime) => {
try {
if (clonedGroupIds.length === 0) return []
await cluster.refreshMetadata()
const brokersPerGroups = {}
const brokersPerNode = {}
for (const groupId of clonedGroupIds) {
const broker = await cluster.findGroupCoordinator({ groupId })
if (brokersPerGroups[broker.nodeId] === undefined) brokersPerGroups[broker.nodeId] = []
brokersPerGroups[broker.nodeId].push(groupId)
brokersPerNode[broker.nodeId] = broker
}
const res = await Promise.all(
Object.keys(brokersPerNode).map(
async nodeId => await brokersPerNode[nodeId].deleteGroups(brokersPerGroups[nodeId])
)
)
const errors = res
.flatMap(({ results }) =>
results.map(({ groupId, errorCode, error }) => {
return { groupId, errorCode, error }
})
)
.filter(({ errorCode }) => errorCode !== 0)
clonedGroupIds = errors.map(({ groupId }) => groupId)
if (errors.length > 0) throw new KafkaJSDeleteGroupsError('Error in DeleteGroups', errors)
results = res.flatMap(({ results }) => results)
return results
} catch (e) {
if (e.type === 'NOT_CONTROLLER' || e.type === 'COORDINATOR_NOT_AVAILABLE') {
logger.warn('Could not delete groups', { error: e.message, retryCount, retryTime })
throw e
}
bail(e)
}
})
}
/**
* Delete topic records up to the selected partition offsets
*
* @param {string} topic
* @param {Array<SeekEntry>} partitions
* @return {Promise}
*
* @typedef {Object} SeekEntry
* @property {number} partition
* @property {string} offset
*/
const deleteTopicRecords = async ({ topic, partitions }) => {