@azure/event-hubs 6.0.1-alpha.20250619.1 → 6.0.1-alpha.20250730.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/browser/batchingPartitionChannel.js +23 -17
  2. package/dist/browser/batchingPartitionChannel.js.map +1 -1
  3. package/dist/browser/connectionContext.js +18 -32
  4. package/dist/browser/connectionContext.js.map +1 -1
  5. package/dist/browser/diagnostics/instrumentEventData.js +6 -7
  6. package/dist/browser/diagnostics/instrumentEventData.js.map +1 -1
  7. package/dist/browser/eventData.js +6 -4
  8. package/dist/browser/eventData.js.map +1 -1
  9. package/dist/browser/eventDataAdapter.js +5 -2
  10. package/dist/browser/eventDataAdapter.js.map +1 -1
  11. package/dist/browser/eventDataBatch.js +61 -9
  12. package/dist/browser/eventDataBatch.js.map +1 -1
  13. package/dist/browser/eventHubBufferedProducerClient.js +65 -50
  14. package/dist/browser/eventHubBufferedProducerClient.js.map +1 -1
  15. package/dist/browser/eventHubConsumerClient.js +70 -24
  16. package/dist/browser/eventHubConsumerClient.js.map +1 -1
  17. package/dist/browser/eventHubProducerClient.js +58 -15
  18. package/dist/browser/eventHubProducerClient.js.map +1 -1
  19. package/dist/browser/eventHubSender.js +118 -35
  20. package/dist/browser/eventHubSender.js.map +1 -1
  21. package/dist/browser/eventProcessor.js +27 -5
  22. package/dist/browser/eventProcessor.js.map +1 -1
  23. package/dist/browser/impl/awaitableQueue.js +6 -2
  24. package/dist/browser/impl/awaitableQueue.js.map +1 -1
  25. package/dist/browser/impl/partitionAssigner.js +2 -4
  26. package/dist/browser/impl/partitionAssigner.js.map +1 -1
  27. package/dist/browser/impl/partitionGate.js +1 -3
  28. package/dist/browser/impl/partitionGate.js.map +1 -1
  29. package/dist/browser/inMemoryCheckpointStore.js +10 -8
  30. package/dist/browser/inMemoryCheckpointStore.js.map +1 -1
  31. package/dist/browser/loadBalancerStrategies/balancedStrategy.js +1 -0
  32. package/dist/browser/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  33. package/dist/browser/loadBalancerStrategies/greedyStrategy.js +1 -0
  34. package/dist/browser/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  35. package/dist/browser/managementClient.js +53 -19
  36. package/dist/browser/managementClient.js.map +1 -1
  37. package/dist/browser/partitionProcessor.js +5 -2
  38. package/dist/browser/partitionProcessor.js.map +1 -1
  39. package/dist/browser/partitionPump.js +15 -6
  40. package/dist/browser/partitionPump.js.map +1 -1
  41. package/dist/browser/partitionReceiver.js +30 -25
  42. package/dist/browser/partitionReceiver.js.map +1 -1
  43. package/dist/browser/pumpManager.js +3 -1
  44. package/dist/browser/pumpManager.js.map +1 -1
  45. package/dist/browser/util/delayWithoutThrow.js +1 -1
  46. package/dist/browser/util/delayWithoutThrow.js.map +1 -1
  47. package/dist/commonjs/batchingPartitionChannel.js +23 -17
  48. package/dist/commonjs/batchingPartitionChannel.js.map +1 -1
  49. package/dist/commonjs/connectionContext.js +18 -32
  50. package/dist/commonjs/connectionContext.js.map +1 -1
  51. package/dist/commonjs/diagnostics/instrumentEventData.js +6 -7
  52. package/dist/commonjs/diagnostics/instrumentEventData.js.map +1 -1
  53. package/dist/commonjs/eventData.js +6 -4
  54. package/dist/commonjs/eventData.js.map +1 -1
  55. package/dist/commonjs/eventDataAdapter.js +5 -2
  56. package/dist/commonjs/eventDataAdapter.js.map +1 -1
  57. package/dist/commonjs/eventDataBatch.js +61 -9
  58. package/dist/commonjs/eventDataBatch.js.map +1 -1
  59. package/dist/commonjs/eventHubBufferedProducerClient.js +65 -50
  60. package/dist/commonjs/eventHubBufferedProducerClient.js.map +1 -1
  61. package/dist/commonjs/eventHubConsumerClient.js +70 -24
  62. package/dist/commonjs/eventHubConsumerClient.js.map +1 -1
  63. package/dist/commonjs/eventHubProducerClient.js +58 -15
  64. package/dist/commonjs/eventHubProducerClient.js.map +1 -1
  65. package/dist/commonjs/eventHubSender.js +118 -35
  66. package/dist/commonjs/eventHubSender.js.map +1 -1
  67. package/dist/commonjs/eventProcessor.js +27 -5
  68. package/dist/commonjs/eventProcessor.js.map +1 -1
  69. package/dist/commonjs/impl/awaitableQueue.js +6 -2
  70. package/dist/commonjs/impl/awaitableQueue.js.map +1 -1
  71. package/dist/commonjs/impl/partitionAssigner.js +2 -4
  72. package/dist/commonjs/impl/partitionAssigner.js.map +1 -1
  73. package/dist/commonjs/impl/partitionGate.js +1 -3
  74. package/dist/commonjs/impl/partitionGate.js.map +1 -1
  75. package/dist/commonjs/inMemoryCheckpointStore.js +10 -8
  76. package/dist/commonjs/inMemoryCheckpointStore.js.map +1 -1
  77. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js +1 -0
  78. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  79. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js +1 -0
  80. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  81. package/dist/commonjs/managementClient.js +53 -19
  82. package/dist/commonjs/managementClient.js.map +1 -1
  83. package/dist/commonjs/partitionProcessor.js +5 -2
  84. package/dist/commonjs/partitionProcessor.js.map +1 -1
  85. package/dist/commonjs/partitionPump.js +15 -6
  86. package/dist/commonjs/partitionPump.js.map +1 -1
  87. package/dist/commonjs/partitionReceiver.js +30 -25
  88. package/dist/commonjs/partitionReceiver.js.map +1 -1
  89. package/dist/commonjs/pumpManager.js +3 -1
  90. package/dist/commonjs/pumpManager.js.map +1 -1
  91. package/dist/commonjs/tsdoc-metadata.json +11 -11
  92. package/dist/commonjs/util/delayWithoutThrow.js +1 -1
  93. package/dist/commonjs/util/delayWithoutThrow.js.map +1 -1
  94. package/dist/esm/batchingPartitionChannel.js +23 -17
  95. package/dist/esm/batchingPartitionChannel.js.map +1 -1
  96. package/dist/esm/connectionContext.js +18 -32
  97. package/dist/esm/connectionContext.js.map +1 -1
  98. package/dist/esm/diagnostics/instrumentEventData.js +6 -7
  99. package/dist/esm/diagnostics/instrumentEventData.js.map +1 -1
  100. package/dist/esm/eventData.js +6 -4
  101. package/dist/esm/eventData.js.map +1 -1
  102. package/dist/esm/eventDataAdapter.js +5 -2
  103. package/dist/esm/eventDataAdapter.js.map +1 -1
  104. package/dist/esm/eventDataBatch.js +61 -9
  105. package/dist/esm/eventDataBatch.js.map +1 -1
  106. package/dist/esm/eventHubBufferedProducerClient.js +65 -50
  107. package/dist/esm/eventHubBufferedProducerClient.js.map +1 -1
  108. package/dist/esm/eventHubConsumerClient.js +70 -24
  109. package/dist/esm/eventHubConsumerClient.js.map +1 -1
  110. package/dist/esm/eventHubProducerClient.js +58 -15
  111. package/dist/esm/eventHubProducerClient.js.map +1 -1
  112. package/dist/esm/eventHubSender.js +118 -35
  113. package/dist/esm/eventHubSender.js.map +1 -1
  114. package/dist/esm/eventProcessor.js +27 -5
  115. package/dist/esm/eventProcessor.js.map +1 -1
  116. package/dist/esm/impl/awaitableQueue.js +6 -2
  117. package/dist/esm/impl/awaitableQueue.js.map +1 -1
  118. package/dist/esm/impl/partitionAssigner.js +2 -4
  119. package/dist/esm/impl/partitionAssigner.js.map +1 -1
  120. package/dist/esm/impl/partitionGate.js +1 -3
  121. package/dist/esm/impl/partitionGate.js.map +1 -1
  122. package/dist/esm/inMemoryCheckpointStore.js +10 -8
  123. package/dist/esm/inMemoryCheckpointStore.js.map +1 -1
  124. package/dist/esm/loadBalancerStrategies/balancedStrategy.js +1 -0
  125. package/dist/esm/loadBalancerStrategies/balancedStrategy.js.map +1 -1
  126. package/dist/esm/loadBalancerStrategies/greedyStrategy.js +1 -0
  127. package/dist/esm/loadBalancerStrategies/greedyStrategy.js.map +1 -1
  128. package/dist/esm/managementClient.js +53 -19
  129. package/dist/esm/managementClient.js.map +1 -1
  130. package/dist/esm/partitionProcessor.js +5 -2
  131. package/dist/esm/partitionProcessor.js.map +1 -1
  132. package/dist/esm/partitionPump.js +15 -6
  133. package/dist/esm/partitionPump.js.map +1 -1
  134. package/dist/esm/partitionReceiver.js +30 -25
  135. package/dist/esm/partitionReceiver.js.map +1 -1
  136. package/dist/esm/pumpManager.js +3 -1
  137. package/dist/esm/pumpManager.js.map +1 -1
  138. package/dist/esm/util/delayWithoutThrow.js +1 -1
  139. package/dist/esm/util/delayWithoutThrow.js.map +1 -1
  140. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"eventProcessor.js","sourceRoot":"","sources":["../../src/eventProcessor.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,8DAAqD;AAErD,mEAA6D;AAE7D,yDAA0E;AAE1E,qDAAmD;AACnD,2CAAyD;AACzD,kDAAiD;AAMjD,sEAAgE;AAChE,8CAAgD;AAChD,gDAAwD;AAqJxD;;;;;;;;;;GAUG;AACH,MAAa,cAAc;IAsBzB;;;;;;;;;;;OAWG;IACH,YACU,cAAsB,EACtB,QAA2B,EAC3B,0BAAqD,EACrD,gBAAiC,EACzC,OAAkC;QAJ1B,mBAAc,GAAd,cAAc,CAAQ;QACtB,aAAQ,GAAR,QAAQ,CAAmB;QAC3B,+BAA0B,GAA1B,0BAA0B,CAA2B;QACrD,qBAAgB,GAAhB,gBAAgB,CAAiB;QAlCnC,eAAU,GAAY,KAAK,CAAC;QAqClC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC;YAC3B,kBAAM,CAAC,OAAO,CAAC,oCAAoC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACjE,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,GAAG,GAAG,IAAA,wBAAa,GAAE,CAAC;YAC3B,kBAAM,CAAC,OAAO,CAAC,kDAAkD,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAC/E,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;QACrD,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,QAAQ,C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GAAG,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QAC5D,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5B,iCAAiC,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QAC1E,CAAC;QACD,IAAI,SAAS,CAAC,OAAO,KAAK,EAAE,IAAI,wBAAwB,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC;YAChF,iBAAiB,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAED,4FAA4F;IAC5F,gCAAgC;IAChC,8EAA8E;IAC9E,4CAA4C;IAC5C,qEAAqE;IACrE,MAAM,iBAAiB,GAAG,qBAAqB,CAAC,oBAAoB,CAClE,EAAE,EACF,iCAAiC,EACjC,YAAY,CACb,CAAC;IACF,iBAAiB,CAAC,IAAI,CAAC,GAAG,iBAAiB,CAAC,CAAC;IAE7C,OAAO;QACL,iBAAiB,EAAE,IAAI,GAAG,CAAC,iBAAiB,CAAC;QAC7C,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport type { Checkpoint } from \"./partitionProcessor.js\";\nimport { PartitionProcessor } from \"./partitionProcessor.js\";\nimport type { EventPosition } from \"./eventPosition.js\";\nimport { isEventPosition, latestEventPosition } from \"./eventPosition.js\";\nimport type { PumpManager } from \"./pumpManager.js\";\nimport { PumpManagerImpl } from \"./pumpManager.js\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport type { CommonEventProcessorOptions } from \"./models/private.js\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { LoadBalancingStrategy } from \"./loadBalancerStrategies/loadBalancingStrategy.js\";\nimport type { OperationOptions } from \"./util/operationOptions.js\";\nimport type { SubscriptionEventHandlers } from \"./eventHubConsumerClientModels.js\";\nimport { delayWithoutThrow } from \"./util/delayWithoutThrow.js\";\nimport { getRandomName } from \"./util/utils.js\";\nimport { StandardAbortMessage } from \"@azure/core-amqp\";\n\n/**\n * An interface representing the details on which instance of a `EventProcessor` owns processing\n * of a given partition from a consumer group of an Event Hub instance.\n *\n * **Note**: This is used internally by the `EventProcessor` and user never has to create it directly.\n */\nexport interface PartitionOwnership {\n /**\n * The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n */\n fullyQualifiedNamespace: string;\n /**\n * The event hub name\n */\n eventHubName: string;\n /**\n * The consumer group name\n */\n consumerGroup: string;\n /**\n * The identifier of the Event Hub partition.\n */\n partitionId: string;\n /**\n * The unique identifier of the event processor.\n */\n ownerId: string;\n /**\n * The last modified time.\n */\n lastModifiedTimeInMs?: number;\n /**\n * The unique identifier for the operation.\n */\n etag?: string;\n}\n\n/**\n * A checkpoint store stores and retrieves partition ownership information and checkpoint details\n * for each partition in a given consumer group of an event hub instance.\n *\n * Users are not meant to implement an `CheckpointStore`.\n * Users are expected to choose existing implementations of this interface, instantiate it, and pass\n * it to the `EventHubConsumerClient` class constructor when instantiating a client.\n * Users are not expected to use any of the methods on a checkpoint store, these are used internally by\n * the client.\n *\n * Implementations of `CheckpointStore` can be found on npm by searching for packages with the prefix &commat;azure/eventhub-checkpointstore-.\n */\nexport interface CheckpointStore {\n /**\n * Called to get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partition ownership details of all the partitions that have/had an owner.\n */\n listOwnership(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n /**\n * Called to claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partitions this instance successfully claimed ownership.\n */\n claimOwnership(\n partitionOwnership: PartitionOwnership[],\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n */\n updateCheckpoint(checkpoint: Checkpoint, options?: OperationOptions): Promise<void>;\n\n /**\n * Lists all the checkpoints in a data store for a given namespace, eventhub and consumer group.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of checkpoints for a given namespace, eventhub, and consumer group.\n */\n listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<Checkpoint[]>;\n}\n\n/**\n * A set of options to pass to the constructor of `EventProcessor`.\n * You can specify\n * - `maxBatchSize`: The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds`: The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n *\n * Example usage with default values:\n * ```ts snippet:ignore\n * {\n * maxBatchSize: 1,\n * maxWaitTimeInSeconds: 60,\n * }\n * ```\n * @internal\n */\nexport interface FullEventProcessorOptions extends CommonEventProcessorOptions {\n /**\n * An optional pump manager to use, rather than instantiating one internally\n * @internal\n */\n pumpManager?: PumpManager;\n /**\n * The amount of time between load balancing attempts.\n */\n loopIntervalInMs: number;\n /**\n * A specific partition to target.\n */\n processingTarget?: string;\n}\n\n/**\n * Event Processor based applications consist of one or more instances of EventProcessor which have been\n * configured to consume events from the same Event Hub and consumer group. They balance the\n * workload across different instances by distributing the partitions to be processed among themselves.\n * They also allow the user to track progress when events are processed using checkpoints.\n *\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * @internal\n */\nexport class EventProcessor {\n private _processorOptions: FullEventProcessorOptions;\n private _pumpManager: PumpManager;\n private _id: string;\n private _isRunning: boolean = false;\n private _loopTask?: PromiseLike<void>;\n private _abortController?: AbortController;\n /**\n * A specific partition to target.\n */\n private _processingTarget?: string;\n /**\n * Determines which partitions to claim as part of load balancing.\n */\n private _loadBalancingStrategy: LoadBalancingStrategy;\n /**\n * The amount of time between load balancing attempts.\n */\n private _loopIntervalInMs: number;\n private _eventHubName: string;\n private _fullyQualifiedNamespace: string;\n\n /**\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param eventHubClient - An instance of `EventHubClient` that was created for the Event Hub instance.\n * @param PartitionProcessorClass - A user-provided class that extends the `PartitionProcessor` class.\n * This class will be responsible for processing and checkpointing events.\n * @param checkpointStore - An instance of `CheckpointStore`. See &commat;azure/eventhubs-checkpointstore-blob for an implementation.\n * For production, choose an implementation that will store checkpoints and partition ownership details to a durable store.\n * @param options - A set of options to configure the Event Processor\n * - `maxBatchSize` : The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds` : The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n */\n constructor(\n private _consumerGroup: string,\n private _context: ConnectionContext,\n private _subscriptionEventHandlers: SubscriptionEventHandlers,\n private _checkpointStore: CheckpointStore,\n options: FullEventProcessorOptions,\n ) {\n if (options.ownerId) {\n this._id = options.ownerId;\n logger.verbose(`Starting event processor with ID ${this._id}`);\n } else {\n this._id = getRandomName();\n logger.verbose(`Starting event processor with autogenerated ID ${this._id}`);\n }\n\n this._eventHubName = this._context.config.entityPath;\n this._fullyQualifiedNamespace = this._context.config.host;\n this._processorOptions = options;\n this._pumpManager =\n options.pumpManager || new PumpManagerImpl(this._id, this._processorOptions);\n this._processingTarget = options.processingTarget;\n this._loopIntervalInMs = options.loopIntervalInMs;\n this._loadBalancingStrategy = options.loadBalancingStrategy;\n }\n\n /**\n * The unique identifier for the EventProcessor.\n */\n get id(): string {\n return this._id;\n }\n\n private _createPartitionOwnershipRequest(\n partitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIdToClaim: string,\n ): PartitionOwnership {\n const previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);\n const partitionOwnership: PartitionOwnership = {\n ownerId: this._id,\n partitionId: partitionIdToClaim,\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n consumerGroup: this._consumerGroup,\n eventHubName: this._eventHubName,\n etag: previousPartitionOwnership ? previousPartitionOwnership.etag : undefined,\n };\n\n return partitionOwnership;\n }\n\n /*\n * Claim ownership of the given partition if it's available\n */\n private async _claimOwnership(\n ownershipRequest: PartitionOwnership,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] Subscription was closed before claiming ownership of ${ownershipRequest.partitionId}.`,\n );\n return;\n }\n logger.info(\n `[${this._id}] Attempting to claim ownership of partition ${ownershipRequest.partitionId}.`,\n );\n try {\n const claimedOwnerships = await this._checkpointStore.claimOwnership([ownershipRequest]);\n\n // can happen if the partition was claimed out from underneath us - we shouldn't\n // attempt to spin up a processor.\n if (!claimedOwnerships.length) {\n return;\n }\n\n logger.info(\n `[${this._id}] Successfully claimed ownership of partition ${ownershipRequest.partitionId}.`,\n );\n\n await this._startPump(ownershipRequest.partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] Failed to claim ownership of partition ${ownershipRequest.partitionId}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n }\n }\n\n private async _startPump(partitionId: string, abortSignal: AbortSignalLike): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] The subscription was closed before starting to read from ${partitionId}.`,\n );\n return;\n }\n\n if (this._pumpManager.isReceivingFromPartition(partitionId)) {\n logger.verbose(\n `[${this._id}] There is already an active partitionPump for partition \"${partitionId}\", skipping pump creation.`,\n );\n return;\n }\n\n logger.verbose(\n `[${this._id}] [${partitionId}] Calling user-provided PartitionProcessorFactory.`,\n );\n\n const partitionProcessor = new PartitionProcessor(\n this._subscriptionEventHandlers,\n this._checkpointStore,\n {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: partitionId,\n eventProcessorId: this._id,\n },\n );\n\n const eventPosition = await this._getStartingPosition(partitionId);\n await this._pumpManager.createPump(\n eventPosition,\n this._context,\n partitionProcessor,\n abortSignal,\n );\n\n logger.verbose(`[${this._id}] PartitionPump created successfully.`);\n }\n\n private async _getStartingPosition(partitionIdToClaim: string): Promise<EventPosition> {\n const availableCheckpoints = await this._checkpointStore.listCheckpoints(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n const validCheckpoints = availableCheckpoints.filter(\n (chk) => chk.partitionId === partitionIdToClaim,\n );\n\n if (validCheckpoints.length > 0) {\n return { offset: validCheckpoints[0].offset };\n }\n\n logger.verbose(\n `No checkpoint found for partition ${partitionIdToClaim}. Looking for fallback.`,\n );\n return getStartPosition(partitionIdToClaim, this._processorOptions.startPosition);\n }\n\n private async _runLoopForSinglePartition(\n partitionId: string,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n while (!abortSignal.aborted) {\n try {\n await this._startPump(partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occurred within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n } finally {\n // sleep for some time after which we can attempt to create a pump again.\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${this._loopIntervalInMs} ms.`,\n );\n // swallow errors from delay since it's fine for delay to exit early\n await delayWithoutThrow(this._loopIntervalInMs, abortSignal);\n }\n }\n this._isRunning = false;\n }\n\n /**\n * Every loop to this method will result in this EventProcessor owning at most one new partition.\n *\n * The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active\n * EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,\n * this algorithm converges gradually towards a steady state.\n *\n * When a new partition is claimed, this method is also responsible for starting a partition pump that creates an\n * EventHubConsumer for processing events from that partition.\n */\n private async _runLoopWithLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n let cancelLoopResolver;\n // This provides a mechanism for exiting the loop early\n // if the subscription has had `close` called.\n const cancelLoopPromise = new Promise<void>((resolve) => {\n cancelLoopResolver = resolve;\n if (abortSignal.aborted) {\n resolve();\n return;\n }\n\n abortSignal.addEventListener(\"abort\", resolve);\n });\n\n // Periodically check if any partitions need to be claimed and claim them.\n while (!abortSignal.aborted) {\n const iterationStartTimeInMs = Date.now();\n try {\n const { partitionIds } = await this._context.managementSession!.getEventHubProperties({\n abortSignal,\n });\n await this._performLoadBalancing(loadBalancingStrategy, partitionIds, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occurred within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n // Protect against the scenario where the user awaits on subscription.close() from inside processError.\n await Promise.race([this._handleSubscriptionError(err), cancelLoopPromise]);\n } finally {\n // Sleep for some time, then continue the loop.\n const iterationDeltaInMs = Date.now() - iterationStartTimeInMs;\n const delayDurationInMs = Math.max(this._loopIntervalInMs - iterationDeltaInMs, 0);\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${delayDurationInMs} ms.`,\n );\n // Swallow the error since it's fine to exit early from the delay.\n await delayWithoutThrow(delayDurationInMs, abortSignal);\n }\n }\n\n if (cancelLoopResolver) {\n abortSignal.removeEventListener(\"abort\", cancelLoopResolver);\n }\n this._isRunning = false;\n }\n\n private async _performLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n partitionIds: string[],\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) throw new AbortError(StandardAbortMessage);\n\n // Retrieve current partition ownership details from the datastore.\n const partitionOwnership = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n if (abortSignal.aborted) throw new AbortError(StandardAbortMessage);\n\n const { partitionOwnershipMap, partitionsToClaim } = computePartitionsToClaim({\n id: this._id,\n isReceivingFromPartition: (partitionId: string) =>\n this._pumpManager.isReceivingFromPartition(partitionId),\n loadBalancingStrategy,\n partitionIds,\n partitionOwnership,\n });\n\n for (const partitionToClaim of partitionsToClaim) {\n const partitionOwnershipRequest = this._createPartitionOwnershipRequest(\n partitionOwnershipMap,\n partitionToClaim,\n );\n\n await this._claimOwnership(partitionOwnershipRequest, abortSignal);\n }\n }\n\n /**\n * This is called when there are errors that are not specific to a partition (ex: load balancing)\n */\n private async _handleSubscriptionError(err: Error): Promise<void> {\n // filter out any internal \"expected\" errors\n if (err.name === \"AbortError\") {\n return;\n }\n\n if (this._subscriptionEventHandlers.processError) {\n try {\n await this._subscriptionEventHandlers.processError(err, {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: \"\",\n updateCheckpoint: async () => {\n /* no-op */\n },\n });\n } catch (errorFromUser: any) {\n logger.verbose(\n `[${this._id}] An error was thrown from the user's processError handler: ${errorFromUser}`,\n );\n }\n }\n }\n\n /**\n * Starts the `EventProcessor`. Based on the number of instances of `EventProcessor` that are running for the\n * same consumer group, the partitions are distributed among these instances to process events.\n *\n * For each partition, the user provided `PartitionProcessor` is instantiated.\n *\n * Subsequent calls to start will be ignored if this event processor is already running.\n * Calling `start()` after `stop()` is called will restart this event processor.\n *\n */\n start(): void {\n if (this._isRunning) {\n logger.verbose(`[${this._id}] Attempted to start an already running EventProcessor.`);\n return;\n }\n\n this._isRunning = true;\n this._abortController = new AbortController();\n logger.verbose(`[${this._id}] Starting an EventProcessor.`);\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] Single partition target: ${this._processingTarget}`);\n this._loopTask = this._runLoopForSinglePartition(\n this._processingTarget,\n this._abortController.signal,\n );\n } else {\n logger.verbose(`[${this._id}] Multiple partitions, using load balancer`);\n this._loopTask = this._runLoopWithLoadBalancing(\n this._loadBalancingStrategy,\n this._abortController.signal,\n );\n }\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Stops processing events for all partitions owned by this event processor.\n * All `PartitionProcessor` will be shutdown and any open resources will be closed.\n *\n * Subsequent calls to stop will be ignored if the event processor is not running.\n *\n */\n async stop(): Promise<void> {\n logger.verbose(`[${this._id}] Stopping an EventProcessor.`);\n // cancel the event processor loop\n this._abortController?.abort();\n\n try {\n // remove all existing pumps\n await this._pumpManager.removeAllPumps(CloseReason.Shutdown);\n\n // waits for the event processor loop to complete\n // will complete immediately if _loopTask is undefined\n if (this._loopTask) {\n await this._loopTask;\n }\n } catch (err: any) {\n logger.verbose(`[${this._id}] An error occurred while stopping the EventProcessor: ${err}`);\n } finally {\n logger.verbose(`[${this._id}] EventProcessor stopped.`);\n }\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] No partitions owned, skipping abandoning.`);\n } else {\n await this.abandonPartitionOwnerships();\n }\n }\n\n private async abandonPartitionOwnerships(): Promise<PartitionOwnership[]> {\n logger.verbose(`[${this._id}] Abandoning owned partitions`);\n const allOwnerships = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n const ourOwnerships = allOwnerships.filter((ownership) => ownership.ownerId === this._id);\n // unclaim any partitions that we currently own\n for (const ownership of ourOwnerships) {\n ownership.ownerId = \"\";\n }\n return this._checkpointStore.claimOwnership(ourOwnerships);\n }\n}\n\nfunction isAbandoned(ownership: PartitionOwnership): boolean {\n return ownership.ownerId === \"\";\n}\n\nfunction getStartPosition(\n partitionIdToClaim: string,\n startPositions?: EventPosition | { [partitionId: string]: EventPosition },\n): EventPosition {\n if (startPositions == null) {\n return latestEventPosition;\n }\n\n if (isEventPosition(startPositions)) {\n return startPositions;\n }\n\n const startPosition = (startPositions as { [partitionId: string]: EventPosition })[\n partitionIdToClaim\n ];\n\n if (startPosition == null) {\n return latestEventPosition;\n }\n\n return startPosition;\n}\n\nfunction computePartitionsToClaim(inputs: {\n partitionOwnership: PartitionOwnership[];\n id: string;\n isReceivingFromPartition: (id: string) => boolean;\n loadBalancingStrategy: LoadBalancingStrategy;\n partitionIds: string[];\n}): {\n partitionsToClaim: Set<string>;\n partitionOwnershipMap: Map<string, PartitionOwnership>;\n} {\n const { partitionOwnership, id, isReceivingFromPartition, loadBalancingStrategy, partitionIds } =\n inputs;\n\n const partitionOwnershipMap = new Map<string, PartitionOwnership>();\n const nonAbandonedPartitionOwnershipMap = new Map<string, PartitionOwnership>();\n const partitionsToRenew: string[] = [];\n\n // Separate abandoned ownerships from claimed ownerships.\n // We only want to pass active partition ownerships to the\n // load balancer, but we need to hold onto the abandoned\n // partition ownerships because we need the etag to claim them.\n for (const ownership of partitionOwnership) {\n partitionOwnershipMap.set(ownership.partitionId, ownership);\n if (!isAbandoned(ownership)) {\n nonAbandonedPartitionOwnershipMap.set(ownership.partitionId, ownership);\n }\n if (ownership.ownerId === id && isReceivingFromPartition(ownership.partitionId)) {\n partitionsToRenew.push(ownership.partitionId);\n }\n }\n\n // Pass the list of all the partition ids and the collection of claimed partition ownerships\n // to the load balance strategy.\n // The load balancing strategy only needs to know the full list of partitions,\n // and which of those are currently claimed.\n // Since abandoned partitions are no longer claimed, we exclude them.\n const partitionsToClaim = loadBalancingStrategy.getPartitionsToClaim(\n id,\n nonAbandonedPartitionOwnershipMap,\n partitionIds,\n );\n partitionsToClaim.push(...partitionsToRenew);\n\n return {\n partitionsToClaim: new Set(partitionsToClaim),\n partitionOwnershipMap,\n };\n}\n"]}
1
+ {"version":3,"file":"eventProcessor.js","sourceRoot":"","sources":["../../src/eventProcessor.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,8DAAqD;AAErD,mEAA6D;AAE7D,yDAA0E;AAE1E,qDAAmD;AACnD,2CAAyD;AACzD,kDAAiD;AAMjD,sEAAgE;AAChE,8CAAgD;AAChD,gDAAwD;AAqJxD;;;;;;;;;;GAUG;AACH,MAAa,cAAc;IAmCf;IACA;IACA;IACA;IArCF,iBAAiB,CAA4B;IAC7C,YAAY,CAAc;IAC1B,GAAG,CAAS;IACZ,UAAU,GAAY,KAAK,CAAC;IAC5B,SAAS,CAAqB;IAC9B,gBAAgB,CAAmB;IAC3C;;OAEG;IACK,iBAAiB,CAAU;IACnC;;OAEG;IACK,sBAAsB,CAAwB;IACtD;;OAEG;IACK,iBAAiB,CAAS;IAC1B,aAAa,CAAS;IACtB,wBAAwB,CAAS;IAEzC;;;;;;;;;;;OAWG;IACH,YACU,cAAsB,EACtB,QAA2B,EAC3B,0BAAqD,EACrD,gBAAiC,EACzC,OAAkC;QAJ1B,mBAAc,GAAd,cAAc,CAAQ;QACtB,aAAQ,GAAR,QAAQ,CAAmB;QAC3B,+BAA0B,GAA1B,0BAA0B,CAA2B;QACrD,qBAAgB,GAAhB,gBAAgB,CAAiB;QAGzC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC;YAC3B,kBAAM,CAAC,OAAO,CAAC,oCAAoC,IAAI,CAAC,GAAG,E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iC,GAAG,IAAI,GAAG,EAA8B,CAAC;IAChF,MAAM,iBAAiB,GAAa,EAAE,CAAC;IAEvC,yDAAyD;IACzD,0DAA0D;IAC1D,wDAAwD;IACxD,+DAA+D;IAC/D,KAAK,MAAM,SAAS,IAAI,kBAAkB,EAAE,CAAC;QAC3C,qBAAqB,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QAC5D,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5B,iCAAiC,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QAC1E,CAAC;QACD,IAAI,SAAS,CAAC,OAAO,KAAK,EAAE,IAAI,wBAAwB,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC;YAChF,iBAAiB,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAED,4FAA4F;IAC5F,gCAAgC;IAChC,8EAA8E;IAC9E,4CAA4C;IAC5C,qEAAqE;IACrE,MAAM,iBAAiB,GAAG,qBAAqB,CAAC,oBAAoB,CAClE,EAAE,EACF,iCAAiC,EACjC,YAAY,CACb,CAAC;IACF,iBAAiB,CAAC,IAAI,CAAC,GAAG,iBAAiB,CAAC,CAAC;IAE7C,OAAO;QACL,iBAAiB,EAAE,IAAI,GAAG,CAAC,iBAAiB,CAAC;QAC7C,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport type { Checkpoint } from \"./partitionProcessor.js\";\nimport { PartitionProcessor } from \"./partitionProcessor.js\";\nimport type { EventPosition } from \"./eventPosition.js\";\nimport { isEventPosition, latestEventPosition } from \"./eventPosition.js\";\nimport type { PumpManager } from \"./pumpManager.js\";\nimport { PumpManagerImpl } from \"./pumpManager.js\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { CloseReason } from \"./models/public.js\";\nimport type { CommonEventProcessorOptions } from \"./models/private.js\";\nimport type { ConnectionContext } from \"./connectionContext.js\";\nimport type { LoadBalancingStrategy } from \"./loadBalancerStrategies/loadBalancingStrategy.js\";\nimport type { OperationOptions } from \"./util/operationOptions.js\";\nimport type { SubscriptionEventHandlers } from \"./eventHubConsumerClientModels.js\";\nimport { delayWithoutThrow } from \"./util/delayWithoutThrow.js\";\nimport { getRandomName } from \"./util/utils.js\";\nimport { StandardAbortMessage } from \"@azure/core-amqp\";\n\n/**\n * An interface representing the details on which instance of a `EventProcessor` owns processing\n * of a given partition from a consumer group of an Event Hub instance.\n *\n * **Note**: This is used internally by the `EventProcessor` and user never has to create it directly.\n */\nexport interface PartitionOwnership {\n /**\n * The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n */\n fullyQualifiedNamespace: string;\n /**\n * The event hub name\n */\n eventHubName: string;\n /**\n * The consumer group name\n */\n consumerGroup: string;\n /**\n * The identifier of the Event Hub partition.\n */\n partitionId: string;\n /**\n * The unique identifier of the event processor.\n */\n ownerId: string;\n /**\n * The last modified time.\n */\n lastModifiedTimeInMs?: number;\n /**\n * The unique identifier for the operation.\n */\n etag?: string;\n}\n\n/**\n * A checkpoint store stores and retrieves partition ownership information and checkpoint details\n * for each partition in a given consumer group of an event hub instance.\n *\n * Users are not meant to implement an `CheckpointStore`.\n * Users are expected to choose existing implementations of this interface, instantiate it, and pass\n * it to the `EventHubConsumerClient` class constructor when instantiating a client.\n * Users are not expected to use any of the methods on a checkpoint store, these are used internally by\n * the client.\n *\n * Implementations of `CheckpointStore` can be found on npm by searching for packages with the prefix &commat;azure/eventhub-checkpointstore-.\n */\nexport interface CheckpointStore {\n /**\n * Called to get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partition ownership details of all the partitions that have/had an owner.\n */\n listOwnership(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n /**\n * Called to claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partitions this instance successfully claimed ownership.\n */\n claimOwnership(\n partitionOwnership: PartitionOwnership[],\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n */\n updateCheckpoint(checkpoint: Checkpoint, options?: OperationOptions): Promise<void>;\n\n /**\n * Lists all the checkpoints in a data store for a given namespace, eventhub and consumer group.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of checkpoints for a given namespace, eventhub, and consumer group.\n */\n listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<Checkpoint[]>;\n}\n\n/**\n * A set of options to pass to the constructor of `EventProcessor`.\n * You can specify\n * - `maxBatchSize`: The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds`: The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n *\n * Example usage with default values:\n * ```ts snippet:ignore\n * {\n * maxBatchSize: 1,\n * maxWaitTimeInSeconds: 60,\n * }\n * ```\n * @internal\n */\nexport interface FullEventProcessorOptions extends CommonEventProcessorOptions {\n /**\n * An optional pump manager to use, rather than instantiating one internally\n * @internal\n */\n pumpManager?: PumpManager;\n /**\n * The amount of time between load balancing attempts.\n */\n loopIntervalInMs: number;\n /**\n * A specific partition to target.\n */\n processingTarget?: string;\n}\n\n/**\n * Event Processor based applications consist of one or more instances of EventProcessor which have been\n * configured to consume events from the same Event Hub and consumer group. They balance the\n * workload across different instances by distributing the partitions to be processed among themselves.\n * They also allow the user to track progress when events are processed using checkpoints.\n *\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * @internal\n */\nexport class EventProcessor {\n private _processorOptions: FullEventProcessorOptions;\n private _pumpManager: PumpManager;\n private _id: string;\n private _isRunning: boolean = false;\n private _loopTask?: PromiseLike<void>;\n private _abortController?: AbortController;\n /**\n * A specific partition to target.\n */\n private _processingTarget?: string;\n /**\n * Determines which partitions to claim as part of load balancing.\n */\n private _loadBalancingStrategy: LoadBalancingStrategy;\n /**\n * The amount of time between load balancing attempts.\n */\n private _loopIntervalInMs: number;\n private _eventHubName: string;\n private _fullyQualifiedNamespace: string;\n\n /**\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param eventHubClient - An instance of `EventHubClient` that was created for the Event Hub instance.\n * @param PartitionProcessorClass - A user-provided class that extends the `PartitionProcessor` class.\n * This class will be responsible for processing and checkpointing events.\n * @param checkpointStore - An instance of `CheckpointStore`. See &commat;azure/eventhubs-checkpointstore-blob for an implementation.\n * For production, choose an implementation that will store checkpoints and partition ownership details to a durable store.\n * @param options - A set of options to configure the Event Processor\n * - `maxBatchSize` : The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds` : The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n */\n constructor(\n private _consumerGroup: string,\n private _context: ConnectionContext,\n private _subscriptionEventHandlers: SubscriptionEventHandlers,\n private _checkpointStore: CheckpointStore,\n options: FullEventProcessorOptions,\n ) {\n if (options.ownerId) {\n this._id = options.ownerId;\n logger.verbose(`Starting event processor with ID ${this._id}`);\n } else {\n this._id = getRandomName();\n logger.verbose(`Starting event processor with autogenerated ID ${this._id}`);\n }\n\n this._eventHubName = this._context.config.entityPath;\n this._fullyQualifiedNamespace = this._context.config.host;\n this._processorOptions = options;\n this._pumpManager =\n options.pumpManager || new PumpManagerImpl(this._id, this._processorOptions);\n this._processingTarget = options.processingTarget;\n this._loopIntervalInMs = options.loopIntervalInMs;\n this._loadBalancingStrategy = options.loadBalancingStrategy;\n }\n\n /**\n * The unique identifier for the EventProcessor.\n */\n get id(): string {\n return this._id;\n }\n\n private _createPartitionOwnershipRequest(\n partitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIdToClaim: string,\n ): PartitionOwnership {\n const previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);\n const partitionOwnership: PartitionOwnership = {\n ownerId: this._id,\n partitionId: partitionIdToClaim,\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n consumerGroup: this._consumerGroup,\n eventHubName: this._eventHubName,\n etag: previousPartitionOwnership ? previousPartitionOwnership.etag : undefined,\n };\n\n return partitionOwnership;\n }\n\n /*\n * Claim ownership of the given partition if it's available\n */\n private async _claimOwnership(\n ownershipRequest: PartitionOwnership,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] Subscription was closed before claiming ownership of ${ownershipRequest.partitionId}.`,\n );\n return;\n }\n logger.info(\n `[${this._id}] Attempting to claim ownership of partition ${ownershipRequest.partitionId}.`,\n );\n try {\n const claimedOwnerships = await this._checkpointStore.claimOwnership([ownershipRequest]);\n\n // can happen if the partition was claimed out from underneath us - we shouldn't\n // attempt to spin up a processor.\n if (!claimedOwnerships.length) {\n return;\n }\n\n logger.info(\n `[${this._id}] Successfully claimed ownership of partition ${ownershipRequest.partitionId}.`,\n );\n\n await this._startPump(ownershipRequest.partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] Failed to claim ownership of partition ${ownershipRequest.partitionId}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n }\n }\n\n private async _startPump(partitionId: string, abortSignal: AbortSignalLike): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] The subscription was closed before starting to read from ${partitionId}.`,\n );\n return;\n }\n\n if (this._pumpManager.isReceivingFromPartition(partitionId)) {\n logger.verbose(\n `[${this._id}] There is already an active partitionPump for partition \"${partitionId}\", skipping pump creation.`,\n );\n return;\n }\n\n logger.verbose(\n `[${this._id}] [${partitionId}] Calling user-provided PartitionProcessorFactory.`,\n );\n\n const partitionProcessor = new PartitionProcessor(\n this._subscriptionEventHandlers,\n this._checkpointStore,\n {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: partitionId,\n eventProcessorId: this._id,\n },\n );\n\n const eventPosition = await this._getStartingPosition(partitionId);\n await this._pumpManager.createPump(\n eventPosition,\n this._context,\n partitionProcessor,\n abortSignal,\n );\n\n logger.verbose(`[${this._id}] PartitionPump created successfully.`);\n }\n\n private async _getStartingPosition(partitionIdToClaim: string): Promise<EventPosition> {\n const availableCheckpoints = await this._checkpointStore.listCheckpoints(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n const validCheckpoints = availableCheckpoints.filter(\n (chk) => chk.partitionId === partitionIdToClaim,\n );\n\n if (validCheckpoints.length > 0) {\n return { offset: validCheckpoints[0].offset };\n }\n\n logger.verbose(\n `No checkpoint found for partition ${partitionIdToClaim}. Looking for fallback.`,\n );\n return getStartPosition(partitionIdToClaim, this._processorOptions.startPosition);\n }\n\n private async _runLoopForSinglePartition(\n partitionId: string,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n while (!abortSignal.aborted) {\n try {\n await this._startPump(partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occurred within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n } finally {\n // sleep for some time after which we can attempt to create a pump again.\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${this._loopIntervalInMs} ms.`,\n );\n // swallow errors from delay since it's fine for delay to exit early\n await delayWithoutThrow(this._loopIntervalInMs, abortSignal);\n }\n }\n this._isRunning = false;\n }\n\n /**\n * Every loop to this method will result in this EventProcessor owning at most one new partition.\n *\n * The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active\n * EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,\n * this algorithm converges gradually towards a steady state.\n *\n * When a new partition is claimed, this method is also responsible for starting a partition pump that creates an\n * EventHubConsumer for processing events from that partition.\n */\n private async _runLoopWithLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n let cancelLoopResolver;\n // This provides a mechanism for exiting the loop early\n // if the subscription has had `close` called.\n const cancelLoopPromise = new Promise<void>((resolve) => {\n cancelLoopResolver = resolve;\n if (abortSignal.aborted) {\n resolve();\n return;\n }\n\n abortSignal.addEventListener(\"abort\", resolve);\n });\n\n // Periodically check if any partitions need to be claimed and claim them.\n while (!abortSignal.aborted) {\n const iterationStartTimeInMs = Date.now();\n try {\n const { partitionIds } = await this._context.managementSession!.getEventHubProperties({\n abortSignal,\n });\n await this._performLoadBalancing(loadBalancingStrategy, partitionIds, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occurred within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n // Protect against the scenario where the user awaits on subscription.close() from inside processError.\n await Promise.race([this._handleSubscriptionError(err), cancelLoopPromise]);\n } finally {\n // Sleep for some time, then continue the loop.\n const iterationDeltaInMs = Date.now() - iterationStartTimeInMs;\n const delayDurationInMs = Math.max(this._loopIntervalInMs - iterationDeltaInMs, 0);\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${delayDurationInMs} ms.`,\n );\n // Swallow the error since it's fine to exit early from the delay.\n await delayWithoutThrow(delayDurationInMs, abortSignal);\n }\n }\n\n if (cancelLoopResolver) {\n abortSignal.removeEventListener(\"abort\", cancelLoopResolver);\n }\n this._isRunning = false;\n }\n\n private async _performLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n partitionIds: string[],\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) throw new AbortError(StandardAbortMessage);\n\n // Retrieve current partition ownership details from the datastore.\n const partitionOwnership = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n if (abortSignal.aborted) throw new AbortError(StandardAbortMessage);\n\n const { partitionOwnershipMap, partitionsToClaim } = computePartitionsToClaim({\n id: this._id,\n isReceivingFromPartition: (partitionId: string) =>\n this._pumpManager.isReceivingFromPartition(partitionId),\n loadBalancingStrategy,\n partitionIds,\n partitionOwnership,\n });\n\n for (const partitionToClaim of partitionsToClaim) {\n const partitionOwnershipRequest = this._createPartitionOwnershipRequest(\n partitionOwnershipMap,\n partitionToClaim,\n );\n\n await this._claimOwnership(partitionOwnershipRequest, abortSignal);\n }\n }\n\n /**\n * This is called when there are errors that are not specific to a partition (ex: load balancing)\n */\n private async _handleSubscriptionError(err: Error): Promise<void> {\n // filter out any internal \"expected\" errors\n if (err.name === \"AbortError\") {\n return;\n }\n\n if (this._subscriptionEventHandlers.processError) {\n try {\n await this._subscriptionEventHandlers.processError(err, {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: \"\",\n updateCheckpoint: async () => {\n /* no-op */\n },\n });\n } catch (errorFromUser: any) {\n logger.verbose(\n `[${this._id}] An error was thrown from the user's processError handler: ${errorFromUser}`,\n );\n }\n }\n }\n\n /**\n * Starts the `EventProcessor`. Based on the number of instances of `EventProcessor` that are running for the\n * same consumer group, the partitions are distributed among these instances to process events.\n *\n * For each partition, the user provided `PartitionProcessor` is instantiated.\n *\n * Subsequent calls to start will be ignored if this event processor is already running.\n * Calling `start()` after `stop()` is called will restart this event processor.\n *\n */\n start(): void {\n if (this._isRunning) {\n logger.verbose(`[${this._id}] Attempted to start an already running EventProcessor.`);\n return;\n }\n\n this._isRunning = true;\n this._abortController = new AbortController();\n logger.verbose(`[${this._id}] Starting an EventProcessor.`);\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] Single partition target: ${this._processingTarget}`);\n this._loopTask = this._runLoopForSinglePartition(\n this._processingTarget,\n this._abortController.signal,\n );\n } else {\n logger.verbose(`[${this._id}] Multiple partitions, using load balancer`);\n this._loopTask = this._runLoopWithLoadBalancing(\n this._loadBalancingStrategy,\n this._abortController.signal,\n );\n }\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Stops processing events for all partitions owned by this event processor.\n * All `PartitionProcessor` will be shutdown and any open resources will be closed.\n *\n * Subsequent calls to stop will be ignored if the event processor is not running.\n *\n */\n async stop(): Promise<void> {\n logger.verbose(`[${this._id}] Stopping an EventProcessor.`);\n // cancel the event processor loop\n this._abortController?.abort();\n\n try {\n // remove all existing pumps\n await this._pumpManager.removeAllPumps(CloseReason.Shutdown);\n\n // waits for the event processor loop to complete\n // will complete immediately if _loopTask is undefined\n if (this._loopTask) {\n await this._loopTask;\n }\n } catch (err: any) {\n logger.verbose(`[${this._id}] An error occurred while stopping the EventProcessor: ${err}`);\n } finally {\n logger.verbose(`[${this._id}] EventProcessor stopped.`);\n }\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] No partitions owned, skipping abandoning.`);\n } else {\n await this.abandonPartitionOwnerships();\n }\n }\n\n private async abandonPartitionOwnerships(): Promise<PartitionOwnership[]> {\n logger.verbose(`[${this._id}] Abandoning owned partitions`);\n const allOwnerships = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n const ourOwnerships = allOwnerships.filter((ownership) => ownership.ownerId === this._id);\n // unclaim any partitions that we currently own\n for (const ownership of ourOwnerships) {\n ownership.ownerId = \"\";\n }\n return this._checkpointStore.claimOwnership(ourOwnerships);\n }\n}\n\nfunction isAbandoned(ownership: PartitionOwnership): boolean {\n return ownership.ownerId === \"\";\n}\n\nfunction getStartPosition(\n partitionIdToClaim: string,\n startPositions?: EventPosition | { [partitionId: string]: EventPosition },\n): EventPosition {\n if (startPositions == null) {\n return latestEventPosition;\n }\n\n if (isEventPosition(startPositions)) {\n return startPositions;\n }\n\n const startPosition = (startPositions as { [partitionId: string]: EventPosition })[\n partitionIdToClaim\n ];\n\n if (startPosition == null) {\n return latestEventPosition;\n }\n\n return startPosition;\n}\n\nfunction computePartitionsToClaim(inputs: {\n partitionOwnership: PartitionOwnership[];\n id: string;\n isReceivingFromPartition: (id: string) => boolean;\n loadBalancingStrategy: LoadBalancingStrategy;\n partitionIds: string[];\n}): {\n partitionsToClaim: Set<string>;\n partitionOwnershipMap: Map<string, PartitionOwnership>;\n} {\n const { partitionOwnership, id, isReceivingFromPartition, loadBalancingStrategy, partitionIds } =\n inputs;\n\n const partitionOwnershipMap = new Map<string, PartitionOwnership>();\n const nonAbandonedPartitionOwnershipMap = new Map<string, PartitionOwnership>();\n const partitionsToRenew: string[] = [];\n\n // Separate abandoned ownerships from claimed ownerships.\n // We only want to pass active partition ownerships to the\n // load balancer, but we need to hold onto the abandoned\n // partition ownerships because we need the etag to claim them.\n for (const ownership of partitionOwnership) {\n partitionOwnershipMap.set(ownership.partitionId, ownership);\n if (!isAbandoned(ownership)) {\n nonAbandonedPartitionOwnershipMap.set(ownership.partitionId, ownership);\n }\n if (ownership.ownerId === id && isReceivingFromPartition(ownership.partitionId)) {\n partitionsToRenew.push(ownership.partitionId);\n }\n }\n\n // Pass the list of all the partition ids and the collection of claimed partition ownerships\n // to the load balance strategy.\n // The load balancing strategy only needs to know the full list of partitions,\n // and which of those are currently claimed.\n // Since abandoned partitions are no longer claimed, we exclude them.\n const partitionsToClaim = loadBalancingStrategy.getPartitionsToClaim(\n id,\n nonAbandonedPartitionOwnershipMap,\n partitionIds,\n );\n partitionsToClaim.push(...partitionsToRenew);\n\n return {\n partitionsToClaim: new Set(partitionsToClaim),\n partitionOwnershipMap,\n };\n}\n"]}
@@ -13,8 +13,9 @@ const core_util_1 = require("@azure/core-util");
13
13
  * @internal
14
14
  */
15
15
  class AwaitableQueue {
16
+ _items;
17
+ _resolvers = [];
16
18
  constructor() {
17
- this._resolvers = [];
18
19
  this._items = [];
19
20
  }
20
21
  size() {
@@ -28,7 +29,10 @@ class AwaitableQueue {
28
29
  if (typeof item !== "undefined") {
29
30
  return Promise.resolve(item);
30
31
  }
31
- return (0, core_util_1.createAbortablePromise)((resolve) => this._resolvers.push(resolve), Object.assign(Object.assign({}, options), { cleanupBeforeAbort: () => this._resolvers.pop() }));
32
+ return (0, core_util_1.createAbortablePromise)((resolve) => this._resolvers.push(resolve), {
33
+ ...options,
34
+ cleanupBeforeAbort: () => this._resolvers.pop(),
35
+ });
32
36
  }
33
37
  /**
34
38
  * Appends new item to the queue.
@@ -1 +1 @@
1
- {"version":3,"file":"awaitableQueue.js","sourceRoot":"","sources":["../../../src/impl/awaitableQueue.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,gDAA0D;AAE1D;;;;;;;GAOG;AACH,MAAa,cAAc;IAKzB;QAFiB,eAAU,GAA8B,EAAE,CAAC;QAG1D,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;IACnB,CAAC;IAEM,IAAI;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,OAAsB;QACjC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAED,OAAO,IAAA,kCAAsB,EAAI,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,kCACtE,OAAO,KACV,kBAAkB,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAC/C,CAAC;IACL,CAAC;IAED;;OAEG;IACI,IAAI,CAAC,IAAO;QACjB,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC;YACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;IACH,CAAC;IAEO,gBAAgB,CAAC,IAAO;QAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACzC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,KAAK,CAAC;QACf,CAAC;QAED,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA9CD,wCA8CC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortOptions } from \"@azure/core-util\";\nimport { createAbortablePromise } from \"@azure/core-util\";\n\n/**\n * `AwaitableQueue` stores items in the order that they are received.\n *\n * This differs from ordinary Queues in that `shift` returns a Promise for a value.\n * This allows a consumer of the queue to request an item that the queue does not yet have.\n *\n * @internal\n */\nexport class AwaitableQueue<T> {\n private readonly _items: T[];\n\n private readonly _resolvers: Array<(value: T) => void> = [];\n\n constructor() {\n this._items = [];\n }\n\n public size(): number {\n return this._items.length;\n }\n\n /**\n * Returns a Promise that will resolve with the next item in the queue.\n */\n public shift(options?: AbortOptions): Promise<T> {\n const item = this._items.shift();\n if (typeof item !== \"undefined\") {\n return Promise.resolve(item);\n }\n\n return createAbortablePromise<T>((resolve) => this._resolvers.push(resolve), {\n ...options,\n cleanupBeforeAbort: () => this._resolvers.pop(),\n });\n }\n\n /**\n * Appends new item to the queue.\n */\n public push(item: T): void {\n if (!this._resolveNextItem(item)) {\n this._items.push(item);\n }\n }\n\n private _resolveNextItem(item: T) {\n const resolver = this._resolvers.shift();\n if (!resolver) {\n return false;\n }\n\n resolver(item);\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"awaitableQueue.js","sourceRoot":"","sources":["../../../src/impl/awaitableQueue.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,gDAA0D;AAE1D;;;;;;;GAOG;AACH,MAAa,cAAc;IACR,MAAM,CAAM;IAEZ,UAAU,GAA8B,EAAE,CAAC;IAE5D;QACE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;IACnB,CAAC;IAEM,IAAI;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,OAAsB;QACjC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE,CAAC;YAChC,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QAED,OAAO,IAAA,kCAAsB,EAAI,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;YAC3E,GAAG,OAAO;YACV,kBAAkB,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE;SAChD,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,IAAI,CAAC,IAAO;QACjB,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC;YACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;IACH,CAAC;IAEO,gBAAgB,CAAC,IAAO;QAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACzC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,KAAK,CAAC;QACf,CAAC;QAED,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA9CD,wCA8CC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortOptions } from \"@azure/core-util\";\nimport { createAbortablePromise } from \"@azure/core-util\";\n\n/**\n * `AwaitableQueue` stores items in the order that they are received.\n *\n * This differs from ordinary Queues in that `shift` returns a Promise for a value.\n * This allows a consumer of the queue to request an item that the queue does not yet have.\n *\n * @internal\n */\nexport class AwaitableQueue<T> {\n private readonly _items: T[];\n\n private readonly _resolvers: Array<(value: T) => void> = [];\n\n constructor() {\n this._items = [];\n }\n\n public size(): number {\n return this._items.length;\n }\n\n /**\n * Returns a Promise that will resolve with the next item in the queue.\n */\n public shift(options?: AbortOptions): Promise<T> {\n const item = this._items.shift();\n if (typeof item !== \"undefined\") {\n return Promise.resolve(item);\n }\n\n return createAbortablePromise<T>((resolve) => this._resolvers.push(resolve), {\n ...options,\n cleanupBeforeAbort: () => this._resolvers.pop(),\n });\n }\n\n /**\n * Appends new item to the queue.\n */\n public push(item: T): void {\n if (!this._resolveNextItem(item)) {\n this._items.push(item);\n }\n }\n\n private _resolveNextItem(item: T) {\n const resolver = this._resolvers.shift();\n if (!resolver) {\n return false;\n }\n\n resolver(item);\n return true;\n }\n}\n"]}
@@ -10,10 +10,8 @@ const partitionKeyToIdMapper_js_1 = require("./partitionKeyToIdMapper.js");
10
10
  * Assigns a partition based on the partition ids it knows about and an optional partition id or partition key.
11
11
  */
12
12
  class PartitionAssigner {
13
- constructor() {
14
- this._partitions = [];
15
- this._lastRoundRobinPartitionIndex = -1;
16
- }
13
+ _partitions = [];
14
+ _lastRoundRobinPartitionIndex = -1;
17
15
  /**
18
16
  * Set the partition ids that can be used when assigning a partition.
19
17
  * @param partitionIds - All valid partition ids.
@@ -1 +1 @@
1
- {"version":3,"file":"partitionAssigner.js","sourceRoot":"","sources":["../../../src/impl/partitionAssigner.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,gDAA6C;AAC7C,2EAAkE;AAElE;;;GAGG;AACH,MAAa,iBAAiB;IAA9B;QACU,gBAAW,GAAa,EAAE,CAAC;QAE3B,kCAA6B,GAAW,CAAC,CAAC,CAAC;IA0DrD,CAAC;IAxDC;;;OAGG;IACI,eAAe,CAAC,YAAsB;QAC3C,IAAI,CAAC,WAAW,GAAG,YAAY,CAAC;IAClC,CAAC;IAED;;;;;;;;;OASG;IACH,eAAe,CAAC,EACd,WAAW,EACX,YAAY,GAIb;QACC,IAAI,IAAA,qBAAS,EAAC,WAAW,CAAC,IAAI,IAAA,qBAAS,EAAC,YAAY,CAAC,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CACb,oBAAoB,WAAW,uBAAuB,YAAY,6BAA6B,CAChG,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;QACjF,CAAC;QAED,IAAI,IAAA,qBAAS,EAAC,WAAW,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;YACrE,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,IAAI,IAAA,qBAAS,EAAC,YAAY,CAAC,EAAE,CAAC;YAC5B,OAAO,IAAA,+CAAmB,EAAC,YAAY,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC/E,CAAC;QAED,OAAO,IAAI,CAAC,0BAA0B,EAAE,CAAC;IAC3C,CAAC;IAEO,0BAA0B;QAChC,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;QACtD,MAAM,sBAAsB,GAAG,IAAI,CAAC,6BAA6B,GAAG,CAAC,CAAC;QAEtE,MAAM,kBAAkB,GACtB,sBAAsB,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,sBAAsB,CAAC;QAE1E,IAAI,CAAC,6BAA6B,GAAG,kBAAkB,CAAC;QACxD,OAAO,IAAI,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;IAC9C,CAAC;CACF;AA7DD,8CA6DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { isDefined } from \"@azure/core-util\";\nimport { mapPartitionKeyToId } from \"./partitionKeyToIdMapper.js\";\n\n/**\n * @internal\n * Assigns a partition based on the partition ids it knows about and an optional partition id or partition key.\n */\nexport class PartitionAssigner {\n private _partitions: string[] = [];\n\n private _lastRoundRobinPartitionIndex: number = -1;\n\n /**\n * Set the partition ids that can be used when assigning a partition.\n * @param partitionIds - All valid partition ids.\n */\n public setPartitionIds(partitionIds: string[]): void {\n this._partitions = partitionIds;\n }\n\n /**\n * Returns a partitionId from the list of partition ids set via `setPartitionIds`.\n *\n * If a partitionId is specified, then that will be returned directly.\n * If a partitionKey is specified, then a partitionId will be calculated based on the partitionKey.\n * Specifying both partitionId and partitionKey results in an error.\n *\n * If neither partitionId nor partitionKey are specified, then a partitionId will be selected\n * based on a round-robin approach.\n */\n assignPartition({\n partitionId,\n partitionKey,\n }: {\n partitionId?: string;\n partitionKey?: string;\n }): string {\n if (isDefined(partitionId) && isDefined(partitionKey)) {\n throw new Error(\n `The partitionId (${partitionId}) and partitionKey (${partitionKey}) cannot both be specified.`,\n );\n }\n\n if (!this._partitions.length) {\n throw new Error(`Unable to determine partitionIds, can't assign partitionId.`);\n }\n\n if (isDefined(partitionId) && this._partitions.includes(partitionId)) {\n return partitionId;\n }\n\n if (isDefined(partitionKey)) {\n return mapPartitionKeyToId(partitionKey, this._partitions.length).toString();\n }\n\n return this._assignRoundRobinPartition();\n }\n\n private _assignRoundRobinPartition(): string {\n const maxPartitionIndex = this._partitions.length - 1;\n const proposedPartitionIndex = this._lastRoundRobinPartitionIndex + 1;\n\n const nextPartitionIndex =\n proposedPartitionIndex > maxPartitionIndex ? 0 : proposedPartitionIndex;\n\n this._lastRoundRobinPartitionIndex = nextPartitionIndex;\n return this._partitions[nextPartitionIndex];\n }\n}\n"]}
1
+ {"version":3,"file":"partitionAssigner.js","sourceRoot":"","sources":["../../../src/impl/partitionAssigner.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,gDAA6C;AAC7C,2EAAkE;AAElE;;;GAGG;AACH,MAAa,iBAAiB;IACpB,WAAW,GAAa,EAAE,CAAC;IAE3B,6BAA6B,GAAW,CAAC,CAAC,CAAC;IAEnD;;;OAGG;IACI,eAAe,CAAC,YAAsB;QAC3C,IAAI,CAAC,WAAW,GAAG,YAAY,CAAC;IAClC,CAAC;IAED;;;;;;;;;OASG;IACH,eAAe,CAAC,EACd,WAAW,EACX,YAAY,GAIb;QACC,IAAI,IAAA,qBAAS,EAAC,WAAW,CAAC,IAAI,IAAA,qBAAS,EAAC,YAAY,CAAC,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CACb,oBAAoB,WAAW,uBAAuB,YAAY,6BAA6B,CAChG,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;QACjF,CAAC;QAED,IAAI,IAAA,qBAAS,EAAC,WAAW,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;YACrE,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,IAAI,IAAA,qBAAS,EAAC,YAAY,CAAC,EAAE,CAAC;YAC5B,OAAO,IAAA,+CAAmB,EAAC,YAAY,EAAE,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC/E,CAAC;QAED,OAAO,IAAI,CAAC,0BAA0B,EAAE,CAAC;IAC3C,CAAC;IAEO,0BAA0B;QAChC,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;QACtD,MAAM,sBAAsB,GAAG,IAAI,CAAC,6BAA6B,GAAG,CAAC,CAAC;QAEtE,MAAM,kBAAkB,GACtB,sBAAsB,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,sBAAsB,CAAC;QAE1E,IAAI,CAAC,6BAA6B,GAAG,kBAAkB,CAAC;QACxD,OAAO,IAAI,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;IAC9C,CAAC;CACF;AA7DD,8CA6DC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { isDefined } from \"@azure/core-util\";\nimport { mapPartitionKeyToId } from \"./partitionKeyToIdMapper.js\";\n\n/**\n * @internal\n * Assigns a partition based on the partition ids it knows about and an optional partition id or partition key.\n */\nexport class PartitionAssigner {\n private _partitions: string[] = [];\n\n private _lastRoundRobinPartitionIndex: number = -1;\n\n /**\n * Set the partition ids that can be used when assigning a partition.\n * @param partitionIds - All valid partition ids.\n */\n public setPartitionIds(partitionIds: string[]): void {\n this._partitions = partitionIds;\n }\n\n /**\n * Returns a partitionId from the list of partition ids set via `setPartitionIds`.\n *\n * If a partitionId is specified, then that will be returned directly.\n * If a partitionKey is specified, then a partitionId will be calculated based on the partitionKey.\n * Specifying both partitionId and partitionKey results in an error.\n *\n * If neither partitionId nor partitionKey are specified, then a partitionId will be selected\n * based on a round-robin approach.\n */\n assignPartition({\n partitionId,\n partitionKey,\n }: {\n partitionId?: string;\n partitionKey?: string;\n }): string {\n if (isDefined(partitionId) && isDefined(partitionKey)) {\n throw new Error(\n `The partitionId (${partitionId}) and partitionKey (${partitionKey}) cannot both be specified.`,\n );\n }\n\n if (!this._partitions.length) {\n throw new Error(`Unable to determine partitionIds, can't assign partitionId.`);\n }\n\n if (isDefined(partitionId) && this._partitions.includes(partitionId)) {\n return partitionId;\n }\n\n if (isDefined(partitionKey)) {\n return mapPartitionKeyToId(partitionKey, this._partitions.length).toString();\n }\n\n return this._assignRoundRobinPartition();\n }\n\n private _assignRoundRobinPartition(): string {\n const maxPartitionIndex = this._partitions.length - 1;\n const proposedPartitionIndex = this._lastRoundRobinPartitionIndex + 1;\n\n const nextPartitionIndex =\n proposedPartitionIndex > maxPartitionIndex ? 0 : proposedPartitionIndex;\n\n this._lastRoundRobinPartitionIndex = nextPartitionIndex;\n return this._partitions[nextPartitionIndex];\n }\n}\n"]}
@@ -14,9 +14,7 @@ exports.PartitionGate = void 0;
14
14
  * @internal
15
15
  */
16
16
  class PartitionGate {
17
- constructor() {
18
- this._partitions = new Set();
19
- }
17
+ _partitions = new Set();
20
18
  /**
21
19
  * Adds a partition, throwing an Error if there is a conflict with partitions (including "all")
22
20
  * that are already added.
@@ -1 +1 @@
1
- {"version":3,"file":"partitionGate.js","sourceRoot":"","sources":["../../../src/impl/partitionGate.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC;;;;;;;;;GASG;AACH,MAAa,aAAa;IAA1B;QACU,gBAAW,GAAG,IAAI,GAAG,EAAU,CAAC;IA4B1C,CAAC;IA1BC;;;;;OAKG;IACH,GAAG,CAAC,WAA2B;QAC7B,IACE,CAAC,WAAW,KAAK,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,CAAC;YACpD,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC;YACjC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAC3B,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QACzD,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,WAA2B;QAChC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IACvC,CAAC;CACF;AA7BD,sCA6BC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Used by EventHubConsumerClient to prevent accidentally spinning up multiple\n * subscriptions against the same set of partitions.\n *\n * This is needed now that EventHubConsumerClient only uses a single CheckpointStore\n * instance - otherwise users will see unpredictable results as their event processor\n * continually steals/overwrites checkpointing and ownership with itself.\n *\n * @internal\n */\nexport class PartitionGate {\n private _partitions = new Set<string>();\n\n /**\n * Adds a partition, throwing an Error if there is a conflict with partitions (including \"all\")\n * that are already added.\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n add(partitionId: string | \"all\"): void {\n if (\n (partitionId === \"all\" && this._partitions.size > 0) ||\n this._partitions.has(partitionId) ||\n this._partitions.has(\"all\")\n ) {\n throw new Error(`Partition already has a subscriber.`);\n }\n\n this._partitions.add(partitionId);\n }\n\n /**\n * Removes a partition\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n remove(partitionId: string | \"all\"): void {\n this._partitions.delete(partitionId);\n }\n}\n"]}
1
+ {"version":3,"file":"partitionGate.js","sourceRoot":"","sources":["../../../src/impl/partitionGate.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC;;;;;;;;;GASG;AACH,MAAa,aAAa;IAChB,WAAW,GAAG,IAAI,GAAG,EAAU,CAAC;IAExC;;;;;OAKG;IACH,GAAG,CAAC,WAA2B;QAC7B,IACE,CAAC,WAAW,KAAK,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,CAAC;YACpD,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC;YACjC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAC3B,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QACzD,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,WAA2B;QAChC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IACvC,CAAC;CACF;AA7BD,sCA6BC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Used by EventHubConsumerClient to prevent accidentally spinning up multiple\n * subscriptions against the same set of partitions.\n *\n * This is needed now that EventHubConsumerClient only uses a single CheckpointStore\n * instance - otherwise users will see unpredictable results as their event processor\n * continually steals/overwrites checkpointing and ownership with itself.\n *\n * @internal\n */\nexport class PartitionGate {\n private _partitions = new Set<string>();\n\n /**\n * Adds a partition, throwing an Error if there is a conflict with partitions (including \"all\")\n * that are already added.\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n add(partitionId: string | \"all\"): void {\n if (\n (partitionId === \"all\" && this._partitions.size > 0) ||\n this._partitions.has(partitionId) ||\n this._partitions.has(\"all\")\n ) {\n throw new Error(`Partition already has a subscriber.`);\n }\n\n this._partitions.add(partitionId);\n }\n\n /**\n * Removes a partition\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n remove(partitionId: string | \"all\"): void {\n this._partitions.delete(partitionId);\n }\n}\n"]}
@@ -17,10 +17,8 @@ const utils_js_1 = require("./util/utils.js");
17
17
  * @internal
18
18
  */
19
19
  class InMemoryCheckpointStore {
20
- constructor() {
21
- this._partitionOwnershipMap = new Map();
22
- this._committedCheckpoints = new Map();
23
- }
20
+ _partitionOwnershipMap = new Map();
21
+ _committedCheckpoints = new Map();
24
22
  /**
25
23
  * Get the list of all existing partition ownership from the underlying data store. Could return empty
26
24
  * results if there are is no existing ownership information.
@@ -34,7 +32,7 @@ class InMemoryCheckpointStore {
34
32
  async listOwnership(_fullyQualifiedNamespace, _eventHubName, _consumerGroup) {
35
33
  const ownerships = [];
36
34
  for (const value of this._partitionOwnershipMap.values()) {
37
- ownerships.push(Object.assign({}, value));
35
+ ownerships.push({ ...value });
38
36
  }
39
37
  return ownerships;
40
38
  }
@@ -51,7 +49,11 @@ class InMemoryCheckpointStore {
51
49
  if (!this._partitionOwnershipMap.has(ownership.partitionId) ||
52
50
  this._partitionOwnershipMap.get(ownership.partitionId).etag === ownership.etag) {
53
51
  const date = new Date();
54
- const newOwnership = Object.assign(Object.assign({}, ownership), { etag: (0, utils_js_1.getRandomName)(), lastModifiedTimeInMs: date.getTime() });
52
+ const newOwnership = {
53
+ ...ownership,
54
+ etag: (0, utils_js_1.getRandomName)(),
55
+ lastModifiedTimeInMs: date.getTime(),
56
+ };
55
57
  this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);
56
58
  claimedOwnerships.push(newOwnership);
57
59
  }
@@ -66,7 +68,7 @@ class InMemoryCheckpointStore {
66
68
  async updateCheckpoint(checkpoint) {
67
69
  (0, error_js_1.throwTypeErrorIfParameterMissing)("", "updateCheckpoint", "sequenceNumber", checkpoint.sequenceNumber);
68
70
  (0, error_js_1.throwTypeErrorIfParameterMissing)("", "updateCheckpoint", "offset", checkpoint.offset);
69
- checkpoint = Object.assign({}, checkpoint);
71
+ checkpoint = { ...checkpoint };
70
72
  const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);
71
73
  if (partitionOwnership) {
72
74
  partitionOwnership.etag = (0, utils_js_1.getRandomName)();
@@ -87,7 +89,7 @@ class InMemoryCheckpointStore {
87
89
  }
88
90
  const checkpoints = [];
89
91
  for (const value of partitionMap.values()) {
90
- checkpoints.push(Object.assign({}, value));
92
+ checkpoints.push({ ...value });
91
93
  }
92
94
  return checkpoints;
93
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"inMemoryCheckpointStore.js","sourceRoot":"","sources":["../../src/inMemoryCheckpointStore.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAIlC,8CAAmE;AACnE,8CAAgD;AAEhD;;;;;;;;;;GAUG;AACH,MAAa,uBAAuB;IAApC;QACU,2BAAsB,GAAoC,IAAI,GAAG,EAAE,CAAC;QACpE,0BAAqB,GAAyC,IAAI,GAAG,EAAE,CAAC;IA6GlF,CAAC;IA3GC;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CACjB,wBAAgC,EAChC,aAAqB,EACrB,cAAsB;QAEtB,MAAM,UAAU,GAAG,EAAE,CAAC;QAEtB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,sBAAsB,CAAC,MAAM,EAAE,EAAE,CAAC;YACzD,UAAU,CAAC,IAAI,mBAAM,KAAK,EAAG,CAAC;QAChC,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,cAAc,CAAC,kBAAwC;QAC3D,MAAM,iBAAiB,GAAG,EAAE,CAAC;QAE7B,KAAK,MAAM,SAAS,IAAI,kBAAkB,EAAE,CAAC;YAC3C,IACE,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,CAAC;gBACvD,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,CAAE,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,EAC/E,CAAC;gBACD,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;gBAExB,MAAM,YAAY,mCACb,SAAS,KACZ,IAAI,EAAE,IAAA,wBAAa,GAAE,EACrB,oBAAoB,EAAE,IA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qB;QAErB,MAAM,GAAG,GAAG,GAAG,uBAAuB,IAAI,YAAY,IAAI,aAAa,EAAE,CAAC;QAE1E,MAAM,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEzD,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;YACzB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,EAAE,CAAC;QAEvB,KAAK,MAAM,KAAK,IAAI,YAAY,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1C,WAAW,CAAC,IAAI,mBAAM,KAAK,EAAG,CAAC;QACjC,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AA/GD,0DA+GC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { CheckpointStore, PartitionOwnership } from \"./eventProcessor.js\";\nimport type { Checkpoint } from \"./partitionProcessor.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * The `EventProcessor` relies on a `CheckpointStore` to store checkpoints and handle partition\n * ownerships. `InMemoryCheckpointStore` is simple partition manager that stores checkpoints and\n * partition ownerships in memory of your program.\n *\n * You can use the `InMemoryCheckpointStore` to get started with using the `EventProcessor`.\n * But in production, you should choose an implementation of the `CheckpointStore` interface that will\n * store the checkpoints and partition ownerships to a durable store instead.\n *\n * @internal\n */\nexport class InMemoryCheckpointStore implements CheckpointStore {\n private _partitionOwnershipMap: Map<string, PartitionOwnership> = new Map();\n private _committedCheckpoints: Map<string, Map<string, Checkpoint>> = new Map();\n\n /**\n * Get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @returns Partition ownership details of all the partitions that have/had an owner..\n */\n async listOwnership(\n _fullyQualifiedNamespace: string,\n _eventHubName: string,\n _consumerGroup: string,\n ): Promise<PartitionOwnership[]> {\n const ownerships = [];\n\n for (const value of this._partitionOwnershipMap.values()) {\n ownerships.push({ ...value });\n }\n\n return ownerships;\n }\n\n /**\n * Claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @returns A list partitions this instance successfully claimed ownership.\n */\n async claimOwnership(partitionOwnership: PartitionOwnership[]): Promise<PartitionOwnership[]> {\n const claimedOwnerships = [];\n\n for (const ownership of partitionOwnership) {\n if (\n !this._partitionOwnershipMap.has(ownership.partitionId) ||\n this._partitionOwnershipMap.get(ownership.partitionId)!.etag === ownership.etag\n ) {\n const date = new Date();\n\n const newOwnership = {\n ...ownership,\n etag: getRandomName(),\n lastModifiedTimeInMs: date.getTime(),\n };\n\n this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);\n claimedOwnerships.push(newOwnership);\n }\n }\n return claimedOwnerships;\n }\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n */\n async updateCheckpoint(checkpoint: Checkpoint): Promise<void> {\n throwTypeErrorIfParameterMissing(\n \"\",\n \"updateCheckpoint\",\n \"sequenceNumber\",\n checkpoint.sequenceNumber,\n );\n throwTypeErrorIfParameterMissing(\"\", \"updateCheckpoint\", \"offset\", checkpoint.offset);\n\n checkpoint = { ...checkpoint };\n\n const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);\n if (partitionOwnership) {\n partitionOwnership.etag = getRandomName();\n\n const key = `${checkpoint.fullyQualifiedNamespace}:${checkpoint.eventHubName}:${checkpoint.consumerGroup}`;\n let partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n partitionMap = new Map();\n this._committedCheckpoints.set(key, partitionMap);\n }\n\n partitionMap.set(checkpoint.partitionId, checkpoint);\n }\n }\n\n async listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n ): Promise<Checkpoint[]> {\n const key = `${fullyQualifiedNamespace}:${eventHubName}:${consumerGroup}`;\n\n const partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n return [];\n }\n\n const checkpoints = [];\n\n for (const value of partitionMap.values()) {\n checkpoints.push({ ...value });\n }\n\n return checkpoints;\n }\n}\n"]}
1
+ {"version":3,"file":"inMemoryCheckpointStore.js","sourceRoot":"","sources":["../../src/inMemoryCheckpointStore.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAIlC,8CAAmE;AACnE,8CAAgD;AAEhD;;;;;;;;;;GAUG;AACH,MAAa,uBAAuB;IAC1B,sBAAsB,GAAoC,IAAI,GAAG,EAAE,CAAC;IACpE,qBAAqB,GAAyC,IAAI,GAAG,EAAE,CAAC;IAEhF;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CACjB,wBAAgC,EAChC,aAAqB,EACrB,cAAsB;QAEtB,MAAM,UAAU,GAAG,EAAE,CAAC;QAEtB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,sBAAsB,CAAC,MAAM,EAAE,EAAE,CAAC;YACzD,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,cAAc,CAAC,kBAAwC;QAC3D,MAAM,iBAAiB,GAAG,EAAE,CAAC;QAE7B,KAAK,MAAM,SAAS,IAAI,kBAAkB,EAAE,CAAC;YAC3C,IACE,CAAC,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,CAAC;gBACvD,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,CAAE,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,EAC/E,CAAC;gBACD,MAAM,IAAI,GAAG,IAA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GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,uBAA+B,EAC/B,YAAoB,EACpB,aAAqB;QAErB,MAAM,GAAG,GAAG,GAAG,uBAAuB,IAAI,YAAY,IAAI,aAAa,EAAE,CAAC;QAE1E,MAAM,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEzD,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;YACzB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,EAAE,CAAC;QAEvB,KAAK,MAAM,KAAK,IAAI,YAAY,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1C,WAAW,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;QACjC,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AA/GD,0DA+GC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { CheckpointStore, PartitionOwnership } from \"./eventProcessor.js\";\nimport type { Checkpoint } from \"./partitionProcessor.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * The `EventProcessor` relies on a `CheckpointStore` to store checkpoints and handle partition\n * ownerships. `InMemoryCheckpointStore` is simple partition manager that stores checkpoints and\n * partition ownerships in memory of your program.\n *\n * You can use the `InMemoryCheckpointStore` to get started with using the `EventProcessor`.\n * But in production, you should choose an implementation of the `CheckpointStore` interface that will\n * store the checkpoints and partition ownerships to a durable store instead.\n *\n * @internal\n */\nexport class InMemoryCheckpointStore implements CheckpointStore {\n private _partitionOwnershipMap: Map<string, PartitionOwnership> = new Map();\n private _committedCheckpoints: Map<string, Map<string, Checkpoint>> = new Map();\n\n /**\n * Get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @returns Partition ownership details of all the partitions that have/had an owner..\n */\n async listOwnership(\n _fullyQualifiedNamespace: string,\n _eventHubName: string,\n _consumerGroup: string,\n ): Promise<PartitionOwnership[]> {\n const ownerships = [];\n\n for (const value of this._partitionOwnershipMap.values()) {\n ownerships.push({ ...value });\n }\n\n return ownerships;\n }\n\n /**\n * Claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @returns A list partitions this instance successfully claimed ownership.\n */\n async claimOwnership(partitionOwnership: PartitionOwnership[]): Promise<PartitionOwnership[]> {\n const claimedOwnerships = [];\n\n for (const ownership of partitionOwnership) {\n if (\n !this._partitionOwnershipMap.has(ownership.partitionId) ||\n this._partitionOwnershipMap.get(ownership.partitionId)!.etag === ownership.etag\n ) {\n const date = new Date();\n\n const newOwnership = {\n ...ownership,\n etag: getRandomName(),\n lastModifiedTimeInMs: date.getTime(),\n };\n\n this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);\n claimedOwnerships.push(newOwnership);\n }\n }\n return claimedOwnerships;\n }\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n */\n async updateCheckpoint(checkpoint: Checkpoint): Promise<void> {\n throwTypeErrorIfParameterMissing(\n \"\",\n \"updateCheckpoint\",\n \"sequenceNumber\",\n checkpoint.sequenceNumber,\n );\n throwTypeErrorIfParameterMissing(\"\", \"updateCheckpoint\", \"offset\", checkpoint.offset);\n\n checkpoint = { ...checkpoint };\n\n const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);\n if (partitionOwnership) {\n partitionOwnership.etag = getRandomName();\n\n const key = `${checkpoint.fullyQualifiedNamespace}:${checkpoint.eventHubName}:${checkpoint.consumerGroup}`;\n let partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n partitionMap = new Map();\n this._committedCheckpoints.set(key, partitionMap);\n }\n\n partitionMap.set(checkpoint.partitionId, checkpoint);\n }\n }\n\n async listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n ): Promise<Checkpoint[]> {\n const key = `${fullyQualifiedNamespace}:${eventHubName}:${consumerGroup}`;\n\n const partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n return [];\n }\n\n const checkpoints = [];\n\n for (const value of partitionMap.values()) {\n checkpoints.push({ ...value });\n }\n\n return checkpoints;\n }\n}\n"]}
@@ -14,6 +14,7 @@ const loadBalancingStrategy_js_1 = require("./loadBalancingStrategy.js");
14
14
  * @internal
15
15
  */
16
16
  class BalancedLoadBalancingStrategy {
17
+ _partitionOwnershipExpirationIntervalInMs;
17
18
  /**
18
19
  * Creates an instance of BalancedLoadBalancingStrategy.
19
20
  *
@@ -1 +1 @@
1
- {"version":3,"file":"balancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/balancedStrategy.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,yEAAqE;AAGrE;;;;;;;;GAQG;AACH,MAAa,6BAA6B;IACxC;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,MAAM,mBAAmB,GAAG,IAAA,kDAAuB,EACjD,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;QAEF,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,CAAC;YAChC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;QAC3E,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5C,CAAC;CACF;AAnCD,sEAmCC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * The BalancedLoadBalancerStrategy is meant to be used when the user\n * wants to reach a load balanced state with less partition 'thrashing'.\n *\n * Partition thrashing - where a partition changes owners - is minimized\n * by only returning a single partition to claim at a time.\n * This minimizes the number of times a partition should need to be stolen.\n * @internal\n */\nexport class BalancedLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of BalancedLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n const claimablePartitions = listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n\n if (!claimablePartitions.length) {\n return [];\n }\n\n const randomIndex = Math.floor(Math.random() * claimablePartitions.length);\n return [claimablePartitions[randomIndex]];\n }\n}\n"]}
1
+ {"version":3,"file":"balancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/balancedStrategy.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,yEAAqE;AAGrE;;;;;;;;GAQG;AACH,MAAa,6BAA6B;IAMX;IAL7B;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,MAAM,mBAAmB,GAAG,IAAA,kDAAuB,EACjD,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;QAEF,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,CAAC;YAChC,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;QAC3E,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,CAAC;IAC5C,CAAC;CACF;AAnCD,sEAmCC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * The BalancedLoadBalancerStrategy is meant to be used when the user\n * wants to reach a load balanced state with less partition 'thrashing'.\n *\n * Partition thrashing - where a partition changes owners - is minimized\n * by only returning a single partition to claim at a time.\n * This minimizes the number of times a partition should need to be stolen.\n * @internal\n */\nexport class BalancedLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of BalancedLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n const claimablePartitions = listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n\n if (!claimablePartitions.length) {\n return [];\n }\n\n const randomIndex = Math.floor(Math.random() * claimablePartitions.length);\n return [claimablePartitions[randomIndex]];\n }\n}\n"]}
@@ -8,6 +8,7 @@ const loadBalancingStrategy_js_1 = require("./loadBalancingStrategy.js");
8
8
  * @internal
9
9
  */
10
10
  class GreedyLoadBalancingStrategy {
11
+ _partitionOwnershipExpirationIntervalInMs;
11
12
  /**
12
13
  * Creates an instance of GreedyLoadBalancingStrategy.
13
14
  *
@@ -1 +1 @@
1
- {"version":3,"file":"greedyStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/greedyStrategy.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,yEAAqE;AAGrE;;GAEG;AACH,MAAa,2BAA2B;IACtC;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,OAAO,IAAA,kDAAuB,EAC5B,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;IACJ,CAAC;CACF;AA5BD,kEA4BC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * @internal\n */\nexport class GreedyLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of GreedyLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the new set of partitions to add.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n return listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"greedyStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/greedyStrategy.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAGlC,yEAAqE;AAGrE;;GAEG;AACH,MAAa,2BAA2B;IAMT;IAL7B;;;;OAIG;IACH,YAA6B,yCAAiD;QAAjD,8CAAyC,GAAzC,yCAAyC,CAAQ;IAAG,CAAC;IAElF;;;;;;;OAOG;IACI,oBAAoB,CACzB,UAAkB,EAClB,4BAA6D,EAC7D,YAAsB;QAEtB,OAAO,IAAA,kDAAuB,EAC5B,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;IACJ,CAAC;CACF;AA5BD,kEA4BC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { LoadBalancingStrategy } from \"./loadBalancingStrategy.js\";\nimport { listAvailablePartitions } from \"./loadBalancingStrategy.js\";\nimport type { PartitionOwnership } from \"../eventProcessor.js\";\n\n/**\n * @internal\n */\nexport class GreedyLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of GreedyLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the new set of partitions to add.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n return listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n }\n}\n"]}
@@ -17,6 +17,40 @@ const utils_js_1 = require("./util/utils.js");
17
17
  * to the $management endpoint over AMQP connection.
18
18
  */
19
19
  class ManagementClient {
20
+ managementLock = (0, utils_js_1.getRandomName)(core_amqp_1.Constants.managementRequestKey);
21
+ /**
22
+ * The name/path of the entity (hub name) for which the management
23
+ * request needs to be made.
24
+ */
25
+ entityPath;
26
+ /**
27
+ * The reply to Guid for the management client.
28
+ */
29
+ replyTo = (0, utils_js_1.getRandomName)();
30
+ /**
31
+ * $management sender, receiver on the same session.
32
+ */
33
+ _mgmtReqResLink;
34
+ /**
35
+ * The address in the following form:
36
+ * `"$management"`.
37
+ */
38
+ address;
39
+ /**
40
+ * The token audience in the following form:
41
+ * `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management"`.
42
+ */
43
+ audience;
44
+ /**
45
+ * Provides relevant information about the amqp connection,
46
+ * cbs and $management sessions, token provider, sender and receivers.
47
+ */
48
+ _context;
49
+ /**
50
+ * The authentication loop that keeps the token refreshed.
51
+ */
52
+ authLoop;
53
+ logger;
20
54
  /**
21
55
  * Instantiates the management client.
22
56
  * @param context - The connection context.
@@ -24,13 +58,8 @@ class ManagementClient {
24
58
  * `/messages/events/$management`.
25
59
  */
26
60
  constructor(context, { address, audience } = {}) {
27
- this.managementLock = (0, utils_js_1.getRandomName)(core_amqp_1.Constants.managementRequestKey);
28
- /**
29
- * The reply to Guid for the management client.
30
- */
31
- this.replyTo = (0, utils_js_1.getRandomName)();
32
- this.address = address !== null && address !== void 0 ? address : core_amqp_1.Constants.management;
33
- this.audience = audience !== null && audience !== void 0 ? audience : context.config.getManagementAudience();
61
+ this.address = address ?? core_amqp_1.Constants.management;
62
+ this.audience = audience ?? context.config.getManagementAudience();
34
63
  this._context = context;
35
64
  const logPrefix = (0, logger_js_1.createManagementLogPrefix)(this._context.connectionId);
36
65
  this.logger = (0, logger_js_1.createSimpleLogger)(logger_js_1.logger, logPrefix);
@@ -71,10 +100,13 @@ class ManagementClient {
71
100
  operation: core_amqp_1.Constants.readOperation,
72
101
  name: this.entityPath,
73
102
  type: `${core_amqp_1.Constants.vendorString}:${core_amqp_1.Constants.eventHub}`,
74
- security_token: securityToken === null || securityToken === void 0 ? void 0 : securityToken.token,
103
+ security_token: securityToken?.token,
75
104
  },
76
105
  };
77
- const info = await this._makeManagementRequest(request, Object.assign(Object.assign({}, updatedOptions), { requestName: "getHubRuntimeInformation" }));
106
+ const info = await this._makeManagementRequest(request, {
107
+ ...updatedOptions,
108
+ requestName: "getHubRuntimeInformation",
109
+ });
78
110
  const runtimeInfo = {
79
111
  name: info.name,
80
112
  createdOn: new Date(info.created_at),
@@ -85,7 +117,7 @@ class ManagementClient {
85
117
  return runtimeInfo;
86
118
  }
87
119
  catch (error) {
88
- logger_js_1.logger.warning(`an error occurred while getting the hub runtime information: ${error === null || error === void 0 ? void 0 : error.name}: ${error === null || error === void 0 ? void 0 : error.message}`);
120
+ logger_js_1.logger.warning(`an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`);
89
121
  (0, logger_js_1.logErrorStackTrace)(error);
90
122
  throw error;
91
123
  }
@@ -111,10 +143,13 @@ class ManagementClient {
111
143
  name: this.entityPath,
112
144
  type: `${core_amqp_1.Constants.vendorString}:${core_amqp_1.Constants.partition}`,
113
145
  partition: `${partitionId}`,
114
- security_token: securityToken === null || securityToken === void 0 ? void 0 : securityToken.token,
146
+ security_token: securityToken?.token,
115
147
  },
116
148
  };
117
- const info = await this._makeManagementRequest(request, Object.assign(Object.assign({}, updatedOptions), { requestName: "getPartitionInformation" }));
149
+ const info = await this._makeManagementRequest(request, {
150
+ ...updatedOptions,
151
+ requestName: "getPartitionInformation",
152
+ });
118
153
  const partitionInfo = {
119
154
  beginningSequenceNumber: info.begin_sequence_number,
120
155
  eventHubName: info.name,
@@ -128,7 +163,7 @@ class ManagementClient {
128
163
  return partitionInfo;
129
164
  }
130
165
  catch (error) {
131
- logger_js_1.logger.warning(`an error occurred while getting the partition information: ${error === null || error === void 0 ? void 0 : error.name}: ${error === null || error === void 0 ? void 0 : error.message}`);
166
+ logger_js_1.logger.warning(`an error occurred while getting the partition information: ${error?.name}: ${error?.message}`);
132
167
  (0, logger_js_1.logErrorStackTrace)(error);
133
168
  throw error;
134
169
  }
@@ -139,10 +174,9 @@ class ManagementClient {
139
174
  * returning a promise that will be resolved when disconnection is completed.
140
175
  */
141
176
  async close() {
142
- var _a;
143
177
  try {
144
178
  // Always stop the auth loop when closing the management link.
145
- (_a = this.authLoop) === null || _a === void 0 ? void 0 : _a.stop();
179
+ this.authLoop?.stop();
146
180
  if (this._isMgmtRequestResponseLinkOpen()) {
147
181
  const mgmtLink = this._mgmtReqResLink;
148
182
  this._mgmtReqResLink = undefined;
@@ -151,7 +185,7 @@ class ManagementClient {
151
185
  }
152
186
  }
153
187
  catch (err) {
154
- const msg = `an error occurred while closing the management session: ${err === null || err === void 0 ? void 0 : err.name}: ${err === null || err === void 0 ? void 0 : err.message}`;
188
+ const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;
155
189
  logger_js_1.logger.warning(msg);
156
190
  (0, logger_js_1.logErrorStackTrace)(err);
157
191
  throw new Error(msg);
@@ -192,7 +226,7 @@ class ManagementClient {
192
226
  }
193
227
  catch (err) {
194
228
  const translatedError = (0, core_amqp_1.translate)(err);
195
- logger_js_1.logger.warning(`an error occurred while establishing the links: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);
229
+ logger_js_1.logger.warning(`an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`);
196
230
  (0, logger_js_1.logErrorStackTrace)(translatedError);
197
231
  throw translatedError;
198
232
  }
@@ -222,7 +256,7 @@ class ManagementClient {
222
256
  }
223
257
  catch (err) {
224
258
  const translatedError = (0, core_amqp_1.translate)(err);
225
- logger_js_1.logger.warning("an error occurred while creating the link: %s", `${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);
259
+ logger_js_1.logger.warning("an error occurred while creating the link: %s", `${translatedError?.name}: ${translatedError?.message}`);
226
260
  (0, logger_js_1.logErrorStackTrace)(translatedError);
227
261
  throw translatedError;
228
262
  }
@@ -262,7 +296,7 @@ class ManagementClient {
262
296
  }
263
297
  catch (err) {
264
298
  const translatedError = (0, core_amqp_1.translate)(err);
265
- logger_js_1.logger.warning("an error occurred during send on management request-response link with address: %s", `${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);
299
+ logger_js_1.logger.warning("an error occurred during send on management request-response link with address: %s", `${translatedError?.name}: ${translatedError?.message}`);
266
300
  (0, logger_js_1.logErrorStackTrace)(translatedError);
267
301
  throw translatedError;
268
302
  }