All files / confluent-kafka-javascript/lib/kafkajs _admin.js

22.34% Statements 80/358
14.77% Branches 26/176
13.04% Functions 9/69
23.59% Lines 80/339

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 10291x 1x                   1x 1x 1x   1x                                                                         1x           1x           1x         1x           1x           1x             1x             1x         1x       2x                 1x 1x       1x 1x 1x       1x       1x 1x       1x     1x             1x   1x       1x                           1x 1x     1x       1x     1x   1x       1x       1x     1x                                             1x       1x   1x 1x   1x 1x 1x 1x                               1x 1x                             1x         1x       1x 1x 1x   1x 1x 1x 1x                             1x 1x 1x 1x   1x       1x 1x 1x       1x                         1x       1x       1x         1x 1x   1x   1x 1x 1x                     1x         1x 1x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x                                                      
const { OffsetSpec } = require('../admin');
const RdKafka = require('../rdkafka');
const { kafkaJSToRdKafkaConfig,
  createKafkaJsErrorFromLibRdKafkaError,
  DefaultLogger,
  CompatibilityErrorMessages,
  createBindingMessageMetadata,
  logLevel,
  checkAllowedKeys,
  loggerTrampoline,
  severityToLogLevel,
} = require('./_common');
const error = require('./_error');
const { hrtime } = require('process');
 
const AdminState = Object.freeze({
  INIT: 0,
  CONNECTING: 1,
  CONNECTED: 4,
  DISCONNECTING: 5,
  DISCONNECTED: 6,
});
 
/**
 * Admin client for administering Kafka clusters (promise-based, async API).
 *
 * This client is the way you can interface with the Kafka Admin APIs.
 * This class should not be instantiated directly, and rather, an instance of
 * [Kafka]{@link KafkaJS.Kafka} should be used to create it, or an existing
 * Producer or Consumer's `dependentAdmin` method may be used.
 *
 * @example
 * const { Kafka } = require('@confluentinc/kafka-javascript');
 * // From a Kafka object.
 * const kafka = new Kafka({ 'bootstrap.servers': 'localhost:9092' });
 * const admin = kafka.admin();
 * await admin.connect();
 * await admin.createTopics({ });
 *
 * // From a producer/consumer
 * const admin = preExistingProducer.dependentAdmin();
 * await admin.connect();
 * await admin.createTopics({ });
 *
 * @memberof KafkaJS
 * @see [Admin client examples]{@link https://github.com/confluentinc/confluent-kafka-javascript/blob/master/examples/kafkajs/admin}
 */
class Admin {
  /**
   * The config supplied by the user.
   * @type {import("../../types/kafkajs").AdminConstructorConfig|null}
   */
  #userConfig = null;
 
  /**
   * The config realized after processing any compatibility options.
   * @type {import("../../types/config").GlobalConfig|null}
   */
  #internalConfig = null;
 
  /**
   * internalClient is the node-rdkafka client used by the API.
   * @type {import("../rdkafka").AdminClient|null}
   */
  #internalClient = null;
  /**
   * state is the current state of the admin client.
   * @type {AdminState}
   */
  #state = AdminState.INIT;
 
  /**
   * A logger for the admin client.
   * @type {import("../../types/kafkajs").Logger}
   */
  #logger = new DefaultLogger();
 
  /**
   * connectPromiseFunc is the set of promise functions used to resolve/reject the connect() promise.
   * @type {{resolve: Function, reject: Function}|{}}
   */
  #connectPromiseFunc = null;
 
  /**
   * Stores the first error encountered while connecting (if any). This is what we
   * want to reject with.
   * @type {Error|null}
   */
  #connectionError = null;
 
  /**
   * The client name used by the admin client for logging - determined by librdkafka
   * using a combination of clientId and an integer.
   * @type {string|undefined}
   */
  #clientName = undefined;
 
  /**
   * The existing client to use as basis for this admin client, if any is provided.
   */
  #existingClient = null;
 
  // Convenience function to create the metadata object needed for logging.
  #createAdminBindingMessageMetadata() {
    return createBindingMessageMetadata(this.#clientName);
  }
 
  /**
   * @constructor
   * @param {import("../../types/kafkajs").AdminConstructorConfig?} config
   * @param {import("../../types/kafkajs").Client?} existingClient
   */
  constructor(config, existingClient) {
    this.#userConfig = config;
    this.#existingClient = existingClient;
  }
 
  #config() {
    Eif (!this.#internalConfig)
      this.#internalConfig = this.#finalizedConfig();
    return this.#internalConfig;
  }
 
  #kafkaJSToAdminConfig(kjsConfig) {
    Iif (!kjsConfig || Object.keys(kjsConfig).length === 0) {
      return {};
    }
 
    const disallowedKey = checkAllowedKeys('admin', kjsConfig);
    Iif (disallowedKey) {
      throw new error.KafkaJSError(CompatibilityErrorMessages.unsupportedKey(disallowedKey), { code: error.ErrorCodes.ERR__INVALID_ARG });
    }
 
    const rdKafkaConfig = kafkaJSToRdKafkaConfig(kjsConfig);
 
    /* Set the logger */
    Iif (Object.hasOwn(kjsConfig, 'logger')) {
      this.#logger = kjsConfig.logger;
    }
 
    /* Set the log level - INFO for compatibility with kafkaJS, or DEBUG if that is turned
    * on using the logLevel property. rdKafkaConfig.log_level is guaranteed to be set if we're
    * here, and containing the correct value. */
    this.#logger.setLogLevel(severityToLogLevel[rdKafkaConfig.log_level]);
 
    return rdKafkaConfig;
  }
 
  #finalizedConfig() {
    let compatibleConfig = this.#kafkaJSToAdminConfig(this.#userConfig.kafkaJS);
 
    /* There can be multiple different and conflicting config directives for setting the log level:
     * 1. If there's a kafkaJS block:
     *   a. If there's a logLevel directive in the kafkaJS block, set the logger level accordingly.
     *   b. If there's no logLevel directive, set the logger level to INFO.
     *   (both these are already handled in the conversion method above).
     * 2. If there is a log_level or debug directive in the main config, set the logger level accordingly.
     *    !This overrides any different value provided in the kafkaJS block!
     *   a. If there's a log_level directive, set the logger level accordingly.
     *   b. If there's a debug directive, set the logger level to DEBUG regardless of anything else. This is because
     *      librdkafka ignores log_level if debug is set, and our behaviour should be identical.
     * 3. There's nothing at all. Take no action in this case, let the logger use its default log level.
     */
    Eif (Object.hasOwn(this.#userConfig, 'log_level')) {
      this.#logger.setLogLevel(severityToLogLevel[this.#userConfig.log_level]);
    }
 
    Iif (Object.hasOwn(this.#userConfig, 'debug')) {
      this.#logger.setLogLevel(logLevel.DEBUG);
    }
 
    let rdKafkaConfig = Object.assign(compatibleConfig, this.#userConfig);
 
    /* Delete properties which are already processed, or cannot be passed to node-rdkafka */
    delete rdKafkaConfig.kafkaJS;
 
    return rdKafkaConfig;
  }
 
  #readyCb() {
    Iif (this.#state !== AdminState.CONNECTING) {
      /* The connectPromiseFunc might not be set, so we throw such an error. It's a state error that we can't recover from. Probably a bug. */
      throw new error.KafkaJSError(`Ready callback called in invalid state ${this.#state}`, { code: error.ErrorCodes.ERR__STATE });
    }
    this.#state = AdminState.CONNECTED;
 
    // Resolve the promise.
    this.#connectPromiseFunc['resolve']();
  }
 
  /**
   * Callback for the event.error event, either fails the initial connect(), or logs the error.
   * @param {Error} err
   * @private
   */
  #errorCb(err) {
    /* If we get an error in the middle of connecting, reject the promise later with this error. */
    if (this.#state < AdminState.CONNECTED) {
      if (!this.#connectionError)
        this.#connectionError = err;
    } else {
      this.#logger.error(`Error: ${err.message}`, this.#createAdminBindingMessageMetadata());
    }
  }
 
  /**
   * Set up the client and connect to the bootstrap brokers.
   * @returns {Promise<void>} Resolves when connection is complete, rejects on error.
   */
  async connect() {
    Iif (this.#state !== AdminState.INIT) {
      throw new error.KafkaJSError("Connect has already been called elsewhere.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    this.#state = AdminState.CONNECTING;
 
    return new Promise((resolve, reject) => {
      try {
        /* AdminClient creation is a synchronous operation for node-rdkafka */
        this.#connectPromiseFunc = { resolve, reject };
        if (!this.#existingClient) {
          const config = this.#config();
          this.#internalClient = RdKafka.AdminClient.create(config, {
            'error': this.#errorCb.bind(this),
            'ready': this.#readyCb.bind(this),
            'event.log': (msg) => loggerTrampoline(msg, this.#logger),
          });
        } else E{
          const underlyingClient = this.#existingClient._getInternalClient();
          if (!underlyingClient) {
            throw new error.KafkaJSError("Underlying client is not connected.", { code: error.ErrorCodes.ERR__STATE });
          }
          this.#logger = this.#existingClient.logger();
          this.#internalClient = RdKafka.AdminClient.createFrom(underlyingClient, {
            'ready': this.#readyCb.bind(this),
          });
        }
 
        this.#clientName = this.#internalClient.name;
        this.#logger.info("Admin client connected", this.#createAdminBindingMessageMetadata());
      } catch (err) {
        this.#state = AdminState.DISCONNECTED;
        const rejectionError = this.#connectionError ? this.#connectionError : err;
        reject(createKafkaJsErrorFromLibRdKafkaError(rejectionError));
      }
    });
  }
 
  /**
   * Disconnect from the brokers, clean-up and tear down the client.
   * @returns {Promise<void>} Resolves when disconnect is complete, rejects on error.
   */
  async disconnect() {
    /* Not yet connected - no error. */
    Iif (this.#state === AdminState.INIT) {
      return;
    }
 
    /* Already disconnecting, or disconnected. */
    Iif (this.#state >= AdminState.DISCONNECTING) {
      return;
    }
 
    this.#state = AdminState.DISCONNECTING;
    return new Promise((resolve, reject) => {
      try {
        /* AdminClient disconnect for node-rdkakfa is synchronous. */
        this.#internalClient.disconnect();
        this.#state = AdminState.DISCONNECTED;
        this.#logger.info("Admin client disconnected", this.#createAdminBindingMessageMetadata());
        resolve();
      } catch (err) {
        reject(createKafkaJsErrorFromLibRdKafkaError(err));
      }
    });
  }
 
 
  /**
   * Converts a topic configuration object from kafkaJS to a format suitable for node-rdkafka.
   * @param {import("../../types/kafkajs").ITopicConfig} topic
   * @returns {import("../../index").NewTopic}
   * @private
   */
  #topicConfigToRdKafka(topic) {
    let topicConfig = { topic: topic.topic };
    topicConfig.topic = topic.topic;
    topicConfig.num_partitions = topic.numPartitions ?? -1;
    topicConfig.replication_factor = topic.replicationFactor ?? -1;
 
    Iif (Object.hasOwn(topic, "replicaAssignment")) {
      throw new error.KafkaJSError("replicaAssignment is not yet implemented.", { code: error.ErrorCodes.ERR__NOT_IMPLEMENTED });
    }
 
    topicConfig.config = {};
    topic.configEntries = topic.configEntries ?? [];
    for (const configEntry of topic.configEntries) {
      topicConfig.config[configEntry.name] = configEntry.value;
    }
 
    return topicConfig;
  }
 
  /**
   * Create topics with the given configuration.
   * @param {object} options
   * @param {number?} options.timeout - The request timeout in milliseconds (default: 5000).
   * @param {Array<{topic: string, numPartitions: number | null, replicationFactor: number | null, configEntries: Array<{name: string, value: string}> | null}>} options.topics
   * The topics to create and optionally, the configuration for each topic.
   * @returns {Promise<boolean>} Resolves true when the topics are created, false if topic exists already, rejects on error.
   *                             In case even one topic already exists, this will return false.
   */
  async createTopics(options) {
    Iif (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    Iif (Object.hasOwn(options, "validateOnly")) {
      throw new error.KafkaJSError("validateOnly is not yet implemented.", { code: error.ErrorCodes.ERR__NOT_IMPLEMENTED });
    }
 
    Iif (Object.hasOwn(options, "waitForLeaders")) {
      throw new error.KafkaJSError("waitForLeaders is not yet implemented.", { code: error.ErrorCodes.ERR__NOT_IMPLEMENTED });
    }
 
    /* Convert each topic to a format suitable for node-rdkafka, and dispatch the call. */
    let allTopicsCreated = true;
    const errors = [];
    const ret =
      options.topics
        .map(this.#topicConfigToRdKafka)
        .map(topicConfig => new Promise(resolve => {
          this.#internalClient.createTopic(topicConfig, options.timeout ?? 5000, (err) => {
            Iif (err) {
              if (err.code === error.ErrorCodes.ERR_TOPIC_ALREADY_EXISTS) {
                allTopicsCreated = false;
                resolve();
                return;
              }
              const e = createKafkaJsErrorFromLibRdKafkaError(err);
              const createTopicError = new error.KafkaJSCreateTopicError(e, topicConfig.topic, e /* includes the properties */);
              errors.push(createTopicError);
              resolve(); // Don't reject this promise, instead, look at the errors array later.
            } else {
              resolve();
            }
          });
        }));
 
    await Promise.allSettled(ret);
    Iif (errors.length > 0) {
      throw new error.KafkaJSAggregateError("Topic creation errors", errors);
    }
    return allTopicsCreated;
  }
 
  /**
   * Deletes given topics.
   * @param {object} options
   * @param {Array<string>} options.topics - The topics to delete.
   * @param {number?} options.timeout - The request timeout in milliseconds (default: 5000).
   * @returns {Promise<void>} Resolves when the topics are deleted, rejects on error.
   */
  async deleteTopics(options) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    return Promise.all(
      options.topics.map(topic => new Promise((resolve, reject) => {
        this.#internalClient.deleteTopic(topic, options.timeout ?? 5000, err => {
          if (err) {
            reject(createKafkaJsErrorFromLibRdKafkaError(err));
          } else {
            resolve();
          }
        });
      }))
    );
  }
 
  /**
   * List consumer groups.
   *
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000).
   * @param {Array<KafkaJS.ConsumerGroupStates>?} options.matchConsumerGroupStates -
   *        A list of consumer group states to match. May be unset, fetches all states (default: unset).
   * @returns {Promise<{ groups: Array<{groupId: string, protocolType: string, isSimpleConsumerGroup: boolean, state: KafkaJS.ConsumerGroupStates}>, errors: Array<RdKafka.LibrdKafkaError> }>}
   *          Resolves with the list of consumer groups, rejects on error.
   */
  async listGroups(options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.listGroups(options, (err, groups) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
          resolve(groups);
        }
      });
    });
  }
 
  /**
   * Describe consumer groups.
   *
   * @param {Array<string>} groups - The names of the groups to describe.
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000)
   * @param {boolean?} options.includeAuthorizedOperations - If true, include operations allowed on the group by the calling client (default: false).
   * @returns {Promise<{groups: Array<object>}>} The descriptions of the requested groups.
   */
  async describeGroups(groups, options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.describeGroups(groups, options, (err, descriptions) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
          resolve(descriptions);
        }
      });
    });
  }
 
  /**
   * Delete consumer groups.
   * @param {Array<string>} groups - The names of the groups to delete.
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000)
   * @returns {Promise<Array<{groupId: string, errorCode: number | null, error: RdKafka.LibrdKafkaError | null}>>}
   *          Resolves with the list of deletion reports (including per-group errors).
   */
  async deleteGroups(groups, options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.deleteGroups(groups, options, (err, reports) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
          return;
        }
 
        /* Convert group-level errors to KafkaJS errors if required. */
        let errorsPresent = false;
        reports = reports.map(groupReport => {
          if (groupReport.error) {
            errorsPresent = true;
            groupReport.error = createKafkaJsErrorFromLibRdKafkaError(groupReport.error);
          }
          return groupReport;
        });
 
        if (errorsPresent) {
          reject(new error.KafkaJSDeleteGroupsError('Error in DeleteGroups', reports));
          return;
        }
        resolve(reports);
      });
    });
  }
 
  /**
   * List topics.
   *
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000).
   * @returns {Promise<Array<string>>} The list of all topics.
   */
  async listTopics(options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.listTopics(options, (err, topics) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
          resolve(topics);
        }
      });
    });
  }
 
  /**
   * Fetch the offsets for topic partition(s) for consumer group(s).
   *
   * @param {object?} options
   * @param {string} options.groupId - The group ID to fetch offsets for.
   * @param {Array<string> | Array<{topic: string, partitions: Array<number>}>} options.topics
   *        The topics to fetch offsets for. Can be specified as a list of topics (in case offsets for all topics are fetched),
   *        or as a list of objects, each containing a topic and a list of partitions.
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000).
   * @param {boolean?} options.requireStableOffsets - Whether broker should return stable offsets
   *                                                  (transaction-committed). (default: false).
   *
   * @returns {Promise<Array<{topic: string, partitions: Array<object>}>>}
   *          The list of requested offsets.
   */
  async fetchOffsets(options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    if (Object.hasOwn(options, "resolveOffsets")) {
      throw new error.KafkaJSError("resolveOffsets is not yet implemented.", { code: error.ErrorCodes.ERR__NOT_IMPLEMENTED });
    }
 
    const { groupId, topics } = options;
 
    if (!groupId) {
      throw new error.KafkaJSError("groupId is required.", { code: error.ErrorCodes.ERR__INVALID_ARG });
    }
 
    let partitions = null;
    let originalTopics = null;
 
    /*
      If the input is a list of topic string, the user expects us to
      fetch offsets for all all partitions of all the input topics. In
      librdkafka, we can only fetch offsets by topic partitions, or else,
      we can fetch all of them. Thus, we must fetch offsets for all topic
      partitions (by settings partitions to null) and filter by the topic strings later.
    */
    if (topics && Array.isArray(topics)) {
      if (typeof topics[0] === 'string') {
        originalTopics = topics;
        partitions = null;
      } else if (typeof topics[0] === 'object' && Array.isArray(topics[0].partitions)) {
        partitions = topics.flatMap(topic => topic.partitions.map(partition => ({
          topic: topic.topic,
          partition
        })));
      } else {
        throw new error.KafkaJSError("Invalid topics format.", { code: error.ErrorCodes.ERR__INVALID_ARG });
      }
    }
 
    const listGroupOffsets = [{
      groupId,
      partitions
    }];
 
 
    return new Promise((resolve, reject) => {
      this.#internalClient.listConsumerGroupOffsets(listGroupOffsets, options, (err, offsets) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
 
          /**
           * Offsets is an array of group results, each containing a group id,
           * an error and an array of partitions.
           * We need to convert it to the required format of an array of topics, each
           * containing an array of partitions.
           */
          const topicPartitionMap = new Map();
 
          if (offsets.length !== 1) {
            reject(new error.KafkaJSError("Unexpected number of group results."));
            return;
          }
 
          const groupResult = offsets[0];
 
          if (groupResult.error) {
            reject(createKafkaJsErrorFromLibRdKafkaError(groupResult.error));
            return;
          }
 
          // Traverse the partitions and group them by topic
          groupResult.partitions.forEach(partitionObj => {
            const { topic, partition, offset, leaderEpoch, metadata, error } = partitionObj;
            const fetchOffsetsPartition = {
              partition: partition,
              offset: String(offset),
              metadata: metadata || null,
              leaderEpoch: leaderEpoch || null,
              error: error || null
            };
 
            // Group partitions by topic
            if (!topicPartitionMap.has(topic)) {
              topicPartitionMap.set(topic, []);
            }
            topicPartitionMap.get(topic).push(fetchOffsetsPartition);
          });
 
          // Convert the map back to the desired array format
          let convertedOffsets = Array.from(topicPartitionMap, ([topic, partitions]) => ({
            topic,
            partitions
          }));
 
          if (originalTopics !== null) {
            convertedOffsets = convertedOffsets.filter(convertedOffset => originalTopics.includes(convertedOffset.topic));
          }
          resolve(convertedOffsets);
        }
      });
    });
  }
 
  /**
   * Deletes records (messages) in topic partitions older than the offsets provided.
   *
   * Provide -1 as offset to delete all records in the partition.
   *
   * @param {object} options
   * @param {string} options.topic - The topic to delete offsets for.
   * @param {Array<{partition: number, offset: string}>} options.partitions
   *        The partitions and associated offsets to delete up until.
   * @param {number?} options.operationTimeout - The operation timeout in milliseconds.
   *                                             May be unset (default: 60000).
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000).
   *
   * @returns {Promise<Array<{topic: string, partition: number, lowWatermark: number, error: RdKafka.LibrdKafkaError | null}>>}
   *          A list of results for each partition.
   */
  async deleteTopicRecords(options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    if (!Object.hasOwn(options, 'topic') || !Object.hasOwn(options, 'partitions') || !Array.isArray(options.partitions)) {
      throw new error.KafkaJSError("Options must include 'topic' and 'partitions', and 'partitions' must be an array.", { code: error.ErrorCodes.ERR__INVALID_ARG });
    }
 
    const { topic, partitions } = options;
 
    // Create an array of TopicPartitionOffset objects
    const topicPartitionOffsets = [];
 
    for (const partition of partitions) {
      if (partition.offset === null || partition.offset === undefined) {
        throw new error.KafkaJSError("Each partition must have a valid offset.", { code: error.ErrorCodes.ERR__INVALID_ARG });
      }
 
      const offset = +partition.offset;
      if (isNaN(offset)) {
        throw new error.KafkaJSError("Offset must be a valid number.", { code: error.ErrorCodes.ERR__INVALID_ARG });
      }
 
      topicPartitionOffsets.push({
        topic,
        partition: partition.partition,
        offset: offset,
      });
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.deleteRecords(topicPartitionOffsets, options, (err, results) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
          return;
        }
 
        let errorsPresent = false;
        results = results.map(result => {
          if (result.error) {
            errorsPresent = true;
            result.error = createKafkaJsErrorFromLibRdKafkaError(result.error);
          }
          return result;
        });
 
        if (errorsPresent) {
          const partitionsWithError =
          {
            /* Note that, for API compatibility, we must filter out partitions
             * without errors, even though it is more useful to return all of
             * them so the user can check offsets. */
            partitions:
              results.filter(result => result.error).map(result => ({
                partition: result.partition,
                offset: String(result.lowWatermark),
                error: result.error,
              }))
          };
          reject(new error.KafkaJSDeleteTopicRecordsError(partitionsWithError));
          return;
        }
        resolve(results);
      });
    });
  }
 
  /**
   * Describe topics.
   *
   * @param {object?} options
   * @param {Array<string>} options.topics - The topics to describe.
   *                                    If unset, all topics will be described.
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000).
   * @param {boolean?} options.includeAuthorizedOperations - If true, include operations allowed on the topic
   *                                                         by the calling client (default: false).
   *
   * @returns {Promise<{ topics: Array<object> }>}
   */
  async fetchTopicMetadata(options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    let topics = options.topics;
    if (!Object.hasOwn(options, 'topics')) {
      try {
        topics = await this.listTopics();
      } catch (err) {
        throw createKafkaJsErrorFromLibRdKafkaError(err);
      }
    }
 
    return new Promise((resolve, reject) => {
      this.#internalClient.describeTopics(topics, options, (err, metadata) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
 
          let errs = metadata.filter(topic => topic.error);
          if (errs.length > 0) {
            reject(createKafkaJsErrorFromLibRdKafkaError(errs[0].error));
            return;
          }
          const convertedMetadata = metadata.map(topic => ({
            name: topic.name,
            topicId: topic.topicId,
            isInternal: topic.isInternal,
            partitions: topic.partitions.map(partition => ({
              partitionErrorCode: error.ErrorCodes.ERR_NO_ERROR,
              partitionId: partition.partition,
              leader: partition.leader.id,
              leaderNode: partition.leader,
              replicas: partition.replicas.map(replica => replica.id),
              replicaNodes: partition.replicas,
              isr: partition.isr.map(isrNode => isrNode.id),
              isrNodes: partition.isr
            })),
            authorizedOperations: topic.authorizedOperations
          }));
 
          resolve(convertedMetadata);
        }
      });
    });
  }
 
  /**
   * List offsets for the specified topic partition(s).
   *
   * @param {string} topic - The topic to fetch offsets for.
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000)
   * @param {KafkaJS.IsolationLevel?} options.isolationLevel - The isolation level for reading the offsets.
   *                                                           (default: READ_UNCOMMITTED)
   *
   * @returns {Promise<Array<{partition: number, offset: string, high: string, low: string}>>}
   */
  async fetchTopicOffsets(topic, options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    if (!Object.hasOwn(options, 'timeout')) {
      options.timeout = 5000;
    }
 
    let topicData;
    let startTime, endTime, timeTaken;
 
    try {
      // Measure time taken for fetchTopicMetadata
      startTime = hrtime.bigint();
      topicData = await this.fetchTopicMetadata({ topics: [topic], timeout: options.timeout });
      endTime = hrtime.bigint();
      timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
      // Adjust timeout for the next request
      options.timeout -= timeTaken;
      if (options.timeout <= 0) {
        throw new error.KafkaJSError("Timeout exceeded while fetching topic metadata.", { code: error.ErrorCodes.ERR__TIMED_OUT });
      }
    } catch (err) {
      throw new createKafkaJsErrorFromLibRdKafkaError(err);
    }
 
    const partitionIds = topicData.flatMap(topic =>
      topic.partitions.map(partition => partition.partitionId)
    );
 
    const topicPartitionOffsetsLatest = partitionIds.map(partitionId => ({
      topic,
      partition: partitionId,
      offset: OffsetSpec.LATEST
    }));
 
    const topicPartitionOffsetsEarliest = partitionIds.map(partitionId => ({
      topic,
      partition: partitionId,
      offset: OffsetSpec.EARLIEST
    }));
 
    try {
      // Measure time taken for listOffsets (latest)
      startTime = hrtime.bigint();
      const latestOffsets = await this.#listOffsets(topicPartitionOffsetsLatest, options);
      endTime = hrtime.bigint();
      timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
      // Adjust timeout for the next request
      options.timeout -= timeTaken;
      if (options.timeout <= 0) {
        throw new error.KafkaJSError("Timeout exceeded while fetching latest offsets.", { code: error.ErrorCodes.ERR__TIMED_OUT });
      }
 
      // Measure time taken for listOffsets (earliest)
      startTime = hrtime.bigint();
      const earliestOffsets = await this.#listOffsets(topicPartitionOffsetsEarliest, options);
      endTime = hrtime.bigint();
      timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
      // Adjust timeout for the next request
      options.timeout -= timeTaken;
      if (options.timeout <= 0) {
        throw new error.KafkaJSError("Timeout exceeded while fetching earliest offsets.", { code: error.ErrorCodes.ERR__TIMED_OUT });
      }
 
      const combinedResults = partitionIds.map(partitionId => {
        const latest = latestOffsets.find(offset => offset.partition === partitionId);
        const earliest = earliestOffsets.find(offset => offset.partition === partitionId);
 
        return {
          partition: partitionId,
          offset: latest.offset.toString(),
          high: latest.offset.toString(),
          low: earliest.offset.toString()
        };
      });
 
      return combinedResults;
    } catch (err) {
      throw createKafkaJsErrorFromLibRdKafkaError(err);
    }
  }
 
  #listOffsets(partitionOffsets, options) {
    return new Promise((resolve, reject) => {
      this.#internalClient.listOffsets(partitionOffsets, options, (err, offsets) => {
        if (err) {
          reject(createKafkaJsErrorFromLibRdKafkaError(err));
        } else {
          resolve(offsets);
        }
      });
    });
  }
 
  /**
   * List offsets for the topic partition(s) by timestamp.
   *
   * @param {string} topic - The topic to fetch offsets for.
   * @param {number?} timestamp - The timestamp to fetch offsets for.
   * @param {object?} options
   * @param {number?} options.timeout - The request timeout in milliseconds.
   *                                    May be unset (default: 5000)
   * @param {KafkaJS.IsolationLevel?} options.isolationLevel - The isolation level for reading the offsets.
   *                                                           (default: READ_UNCOMMITTED)
   *
   * The returned topic partitions contain the earliest offset whose timestamp is greater than or equal to
   * the given timestamp. If there is no such offset, or if the timestamp is unset, the latest offset is returned instead.
   *
   * @returns {Promise<Array<{partition: number, offset: string}>>}
   */
  async fetchTopicOffsetsByTimestamp(topic, timestamp, options = {}) {
    if (this.#state !== AdminState.CONNECTED) {
      throw new error.KafkaJSError("Admin client is not connected.", { code: error.ErrorCodes.ERR__STATE });
    }
 
    if (!Object.hasOwn(options, 'timeout')) {
      options.timeout = 5000;
    }
 
    let topicData;
    let startTime, endTime, timeTaken;
 
    try {
      // Measure time taken for fetchTopicMetadata
      startTime = hrtime.bigint();
      topicData = await this.fetchTopicMetadata({ topics: [topic], timeout: options.timeout });
      endTime = hrtime.bigint();
      timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
      // Adjust timeout for the next request
      options.timeout -= timeTaken;
      if (options.timeout <= 0) {
        throw new error.KafkaJSError("Timeout exceeded while fetching topic metadata.", { code: error.ErrorCodes.ERR__TIMED_OUT });
      }
    } catch (err) {
      throw new createKafkaJsErrorFromLibRdKafkaError(err);
    }
 
    const partitionIds = topicData.flatMap(topic =>
      topic.partitions.map(partition => partition.partitionId)
    );
    let topicPartitionOffset = [];
    if (typeof timestamp === 'undefined') {
      topicPartitionOffset = partitionIds.map(partitionId => ({
        topic,
        partition: partitionId,
        offset: OffsetSpec.LATEST
      }));
    }
    else {
      topicPartitionOffset = partitionIds.map(partitionId => ({
        topic,
        partition: partitionId,
        offset: new OffsetSpec(timestamp)
      }));
    }
 
    const topicPartitionOffsetsLatest = partitionIds.map(partitionId => ({
      topic,
      partition: partitionId,
      offset: OffsetSpec.LATEST
    }));
 
    try {
      // Measure time taken for listOffsets (by timestamp)
      startTime = hrtime.bigint();
      const offsetsByTimeStamp = await this.#listOffsets(topicPartitionOffset, options);
      endTime = hrtime.bigint();
      timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
      // Adjust timeout for the next request
      options.timeout -= timeTaken;
      if (options.timeout <= 0) {
        throw new error.KafkaJSError("Timeout exceeded while fetching offsets.", { code: error.ErrorCodes.ERR__TIMED_OUT });
      }
 
      if (typeof timestamp === 'undefined') {
        // Return result from offsetsByTimestamp if timestamp is undefined
        return offsetsByTimeStamp.map(offset => ({
          partition: offset.partition,
          offset: offset.offset.toString(),
        }));
      } else {
        // Measure time taken for listOffsets(latest)
        startTime = hrtime.bigint();
        const latestOffsets = await this.#listOffsets(topicPartitionOffsetsLatest, options);
        endTime = hrtime.bigint();
        timeTaken = Number(endTime - startTime) / 1e6; // Convert nanoseconds to milliseconds
 
        // Adjust timeout for the next request
        options.timeout -= timeTaken;
        if (options.timeout <= 0) {
          throw new error.KafkaJSError("Timeout exceeded while fetching latest offsets.", { code: error.ErrorCodes.ERR__TIMED_OUT });
        }
 
        const combinedResults = partitionIds.map(partitionId => {
          const latest = latestOffsets.find(offset => offset.partition === partitionId);
          const timestampOffset = offsetsByTimeStamp.find(offset => offset.partition === partitionId);
 
          if (timestampOffset.offset === -1) {
            return {
              partition: partitionId,
              offset: latest.offset.toString(),
            };
          } else {
            return {
              partition: partitionId,
              offset: timestampOffset.offset.toString(),
            };
          }
        });
 
        return combinedResults;
      }
    } catch (err) {
      throw createKafkaJsErrorFromLibRdKafkaError(err);
    }
  }
}
 
module.exports = {
  Admin,
  /**
   * A list of consumer group states.
   * @enum {number}
   * @readonly
   * @memberof KafkaJS
   * @see RdKafka.ConsumerGroupStates
   */
  ConsumerGroupStates: RdKafka.AdminClient.ConsumerGroupStates,
  /**
   * A list of ACL operation types.
   * @enum {number}
   * @readonly
   * @memberof KafkaJS
   * @see RdKafka.AclOperationTypes
   */
  AclOperationTypes: RdKafka.AdminClient.AclOperationTypes,
  /**
   * A list of isolation levels.
   * @enum {number}
   * @readonly
   * @memberof KafkaJS
   * @see RdKafka.IsolationLevel
   */
  IsolationLevel: RdKafka.AdminClient.IsolationLevel
};