@azure/event-hubs 6.0.1-alpha.20250618.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,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAMjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAqJxD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,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,MAAM,C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AAM,qBAAqB,GAAG,IAAI,GAAG,EAA8B,CAAC;IACpE,MAAM,iCAAiC,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"]}
1
+ {"version":3,"file":"eventProcessor.js","sourceRoot":"","sources":["../../src/eventProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAMjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAqJxD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,cAAc;IAmCf;IACA;IACA;IACA;IArCF,iBAAiB,CAA4B;IAC7C,YAAY,CAAc;IA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B,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"]}
@@ -10,8 +10,9 @@ import { createAbortablePromise } from "@azure/core-util";
10
10
  * @internal
11
11
  */
12
12
  export class AwaitableQueue {
13
+ _items;
14
+ _resolvers = [];
13
15
  constructor() {
14
- this._resolvers = [];
15
16
  this._items = [];
16
17
  }
17
18
  size() {
@@ -25,7 +26,10 @@ export class AwaitableQueue {
25
26
  if (typeof item !== "undefined") {
26
27
  return Promise.resolve(item);
27
28
  }
28
- return createAbortablePromise((resolve) => this._resolvers.push(resolve), Object.assign(Object.assign({}, options), { cleanupBeforeAbort: () => this._resolvers.pop() }));
29
+ return createAbortablePromise((resolve) => this._resolvers.push(resolve), {
30
+ ...options,
31
+ cleanupBeforeAbort: () => this._resolvers.pop(),
32
+ });
29
33
  }
30
34
  /**
31
35
  * 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,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,OAAO,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,sBAAsB,CAAI,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","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,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,OAAO,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,sBAAsB,CAAI,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","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"]}
@@ -7,10 +7,8 @@ import { mapPartitionKeyToId } from "./partitionKeyToIdMapper.js";
7
7
  * Assigns a partition based on the partition ids it knows about and an optional partition id or partition key.
8
8
  */
9
9
  export class PartitionAssigner {
10
- constructor() {
11
- this._partitions = [];
12
- this._lastRoundRobinPartitionIndex = -1;
13
- }
10
+ _partitions = [];
11
+ _lastRoundRobinPartitionIndex = -1;
14
12
  /**
15
13
  * Set the partition ids that can be used when assigning a partition.
16
14
  * @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,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAA9B;QACU,gBAAW,GAAa,EAAE,CAAC;QAE3B,kCAA6B,GAAW,CAAC,CAAC,CAAC;IA0DrD,CAAC;IAx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.\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;AA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,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","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"]}
@@ -11,9 +11,7 @@
11
11
  * @internal
12
12
  */
13
13
  export class PartitionGate {
14
- constructor() {
15
- this._partitions = new Set();
16
- }
14
+ _partitions = new Set();
17
15
  /**
18
16
  * Adds a partition, throwing an Error if there is a conflict with partitions (including "all")
19
17
  * 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,MAAM,OAAO,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","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,MAAM,OAAO,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","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"]}
@@ -14,10 +14,8 @@ import { getRandomName } from "./util/utils.js";
14
14
  * @internal
15
15
  */
16
16
  export class InMemoryCheckpointStore {
17
- constructor() {
18
- this._partitionOwnershipMap = new Map();
19
- this._committedCheckpoints = new Map();
20
- }
17
+ _partitionOwnershipMap = new Map();
18
+ _committedCheckpoints = new Map();
21
19
  /**
22
20
  * Get the list of all existing partition ownership from the underlying data store. Could return empty
23
21
  * results if there are is no existing ownership information.
@@ -31,7 +29,7 @@ export class InMemoryCheckpointStore {
31
29
  async listOwnership(_fullyQualifiedNamespace, _eventHubName, _consumerGroup) {
32
30
  const ownerships = [];
33
31
  for (const value of this._partitionOwnershipMap.values()) {
34
- ownerships.push(Object.assign({}, value));
32
+ ownerships.push({ ...value });
35
33
  }
36
34
  return ownerships;
37
35
  }
@@ -48,7 +46,11 @@ export class InMemoryCheckpointStore {
48
46
  if (!this._partitionOwnershipMap.has(ownership.partitionId) ||
49
47
  this._partitionOwnershipMap.get(ownership.partitionId).etag === ownership.etag) {
50
48
  const date = new Date();
51
- const newOwnership = Object.assign(Object.assign({}, ownership), { etag: getRandomName(), lastModifiedTimeInMs: date.getTime() });
49
+ const newOwnership = {
50
+ ...ownership,
51
+ etag: getRandomName(),
52
+ lastModifiedTimeInMs: date.getTime(),
53
+ };
52
54
  this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);
53
55
  claimedOwnerships.push(newOwnership);
54
56
  }
@@ -63,7 +65,7 @@ export class InMemoryCheckpointStore {
63
65
  async updateCheckpoint(checkpoint) {
64
66
  throwTypeErrorIfParameterMissing("", "updateCheckpoint", "sequenceNumber", checkpoint.sequenceNumber);
65
67
  throwTypeErrorIfParameterMissing("", "updateCheckpoint", "offset", checkpoint.offset);
66
- checkpoint = Object.assign({}, checkpoint);
68
+ checkpoint = { ...checkpoint };
67
69
  const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);
68
70
  if (partitionOwnership) {
69
71
  partitionOwnership.etag = getRandomName();
@@ -84,7 +86,7 @@ export class InMemoryCheckpointStore {
84
86
  }
85
87
  const checkpoints = [];
86
88
  for (const value of partitionMap.values()) {
87
- checkpoints.push(Object.assign({}, value));
89
+ checkpoints.push({ ...value });
88
90
  }
89
91
  return checkpoints;
90
92
  }
@@ -1 +1 @@
1
- {"version":3,"file":"inMemoryCheckpointStore.js","sourceRoot":"","sources":["../../src/inMemoryCheckpointStore.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,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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B,CAAC,IAAI,GAAG,aAAa,EAAE,CAAC;YAE1C,MAAM,GAAG,GAAG,GAAG,UAAU,CAAC,uBAAuB,IAAI,UAAU,CAAC,YAAY,IAAI,UAAU,CAAC,aAAa,EAAE,CAAC;YAC3G,IAAI,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAEvD,IAAI,YAAY,IAAI,IAAI,EAAE,CAAC;gBACzB,YAAY,GAAG,IAAI,GAAG,EAAE,CAAC;gBACzB,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;YACpD,CAAC;YAED,YAAY,CAAC,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,mBAAM,KAAK,EAAG,CAAC;QACjC,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;CACF","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,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;;;;;GAUG;AACH,MAAM,OAAO,uBAAuB;IAC1B,sBAAsB,GAAoC,IAAI,GAAG,EAAE,CAAC;IACpE,qBAAqB,GAAyC,IAAI,GAAG,EAAE,CAAC;IAEhF;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CACjB,wBAAgC,EAChC,a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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"]}
@@ -11,6 +11,7 @@ import { listAvailablePartitions } from "./loadBalancingStrategy.js";
11
11
  * @internal
12
12
  */
13
13
  export class BalancedLoadBalancingStrategy {
14
+ _partitionOwnershipExpirationIntervalInMs;
14
15
  /**
15
16
  * Creates an instance of BalancedLoadBalancingStrategy.
16
17
  *
@@ -1 +1 @@
1
- {"version":3,"file":"balancedStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/balancedStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;;;;;;;GAQG;AACH,MAAM,OAAO,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,uBAAuB,CACjD,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","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,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;;;;;;;GAQG;AACH,MAAM,OAAO,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,uBAAuB,CACjD,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","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"]}
@@ -5,6 +5,7 @@ import { listAvailablePartitions } from "./loadBalancingStrategy.js";
5
5
  * @internal
6
6
  */
7
7
  export class GreedyLoadBalancingStrategy {
8
+ _partitionOwnershipExpirationIntervalInMs;
8
9
  /**
9
10
  * Creates an instance of GreedyLoadBalancingStrategy.
10
11
  *
@@ -1 +1 @@
1
- {"version":3,"file":"greedyStrategy.js","sourceRoot":"","sources":["../../../src/loadBalancerStrategies/greedyStrategy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;GAEG;AACH,MAAM,OAAO,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,uBAAuB,CAC5B,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;IACJ,CAAC;CACF","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,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAGrE;;GAEG;AACH,MAAM,OAAO,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,uBAAuB,CAC5B,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,IAAI,CAAC,yCAAyC,CAC/C,CAAC;IACJ,CAAC;CACF","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"]}
@@ -14,6 +14,40 @@ import { getRandomName } from "./util/utils.js";
14
14
  * to the $management endpoint over AMQP connection.
15
15
  */
16
16
  export class ManagementClient {
17
+ managementLock = getRandomName(Constants.managementRequestKey);
18
+ /**
19
+ * The name/path of the entity (hub name) for which the management
20
+ * request needs to be made.
21
+ */
22
+ entityPath;
23
+ /**
24
+ * The reply to Guid for the management client.
25
+ */
26
+ replyTo = getRandomName();
27
+ /**
28
+ * $management sender, receiver on the same session.
29
+ */
30
+ _mgmtReqResLink;
31
+ /**
32
+ * The address in the following form:
33
+ * `"$management"`.
34
+ */
35
+ address;
36
+ /**
37
+ * The token audience in the following form:
38
+ * `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management"`.
39
+ */
40
+ audience;
41
+ /**
42
+ * Provides relevant information about the amqp connection,
43
+ * cbs and $management sessions, token provider, sender and receivers.
44
+ */
45
+ _context;
46
+ /**
47
+ * The authentication loop that keeps the token refreshed.
48
+ */
49
+ authLoop;
50
+ logger;
17
51
  /**
18
52
  * Instantiates the management client.
19
53
  * @param context - The connection context.
@@ -21,13 +55,8 @@ export class ManagementClient {
21
55
  * `/messages/events/$management`.
22
56
  */
23
57
  constructor(context, { address, audience } = {}) {
24
- this.managementLock = getRandomName(Constants.managementRequestKey);
25
- /**
26
- * The reply to Guid for the management client.
27
- */
28
- this.replyTo = getRandomName();
29
- this.address = address !== null && address !== void 0 ? address : Constants.management;
30
- this.audience = audience !== null && audience !== void 0 ? audience : context.config.getManagementAudience();
58
+ this.address = address ?? Constants.management;
59
+ this.audience = audience ?? context.config.getManagementAudience();
31
60
  this._context = context;
32
61
  const logPrefix = createManagementLogPrefix(this._context.connectionId);
33
62
  this.logger = createSimpleLogger(logger, logPrefix);
@@ -68,10 +97,13 @@ export class ManagementClient {
68
97
  operation: Constants.readOperation,
69
98
  name: this.entityPath,
70
99
  type: `${Constants.vendorString}:${Constants.eventHub}`,
71
- security_token: securityToken === null || securityToken === void 0 ? void 0 : securityToken.token,
100
+ security_token: securityToken?.token,
72
101
  },
73
102
  };
74
- const info = await this._makeManagementRequest(request, Object.assign(Object.assign({}, updatedOptions), { requestName: "getHubRuntimeInformation" }));
103
+ const info = await this._makeManagementRequest(request, {
104
+ ...updatedOptions,
105
+ requestName: "getHubRuntimeInformation",
106
+ });
75
107
  const runtimeInfo = {
76
108
  name: info.name,
77
109
  createdOn: new Date(info.created_at),
@@ -82,7 +114,7 @@ export class ManagementClient {
82
114
  return runtimeInfo;
83
115
  }
84
116
  catch (error) {
85
- 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}`);
117
+ logger.warning(`an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`);
86
118
  logErrorStackTrace(error);
87
119
  throw error;
88
120
  }
@@ -108,10 +140,13 @@ export class ManagementClient {
108
140
  name: this.entityPath,
109
141
  type: `${Constants.vendorString}:${Constants.partition}`,
110
142
  partition: `${partitionId}`,
111
- security_token: securityToken === null || securityToken === void 0 ? void 0 : securityToken.token,
143
+ security_token: securityToken?.token,
112
144
  },
113
145
  };
114
- const info = await this._makeManagementRequest(request, Object.assign(Object.assign({}, updatedOptions), { requestName: "getPartitionInformation" }));
146
+ const info = await this._makeManagementRequest(request, {
147
+ ...updatedOptions,
148
+ requestName: "getPartitionInformation",
149
+ });
115
150
  const partitionInfo = {
116
151
  beginningSequenceNumber: info.begin_sequence_number,
117
152
  eventHubName: info.name,
@@ -125,7 +160,7 @@ export class ManagementClient {
125
160
  return partitionInfo;
126
161
  }
127
162
  catch (error) {
128
- 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}`);
163
+ logger.warning(`an error occurred while getting the partition information: ${error?.name}: ${error?.message}`);
129
164
  logErrorStackTrace(error);
130
165
  throw error;
131
166
  }
@@ -136,10 +171,9 @@ export class ManagementClient {
136
171
  * returning a promise that will be resolved when disconnection is completed.
137
172
  */
138
173
  async close() {
139
- var _a;
140
174
  try {
141
175
  // Always stop the auth loop when closing the management link.
142
- (_a = this.authLoop) === null || _a === void 0 ? void 0 : _a.stop();
176
+ this.authLoop?.stop();
143
177
  if (this._isMgmtRequestResponseLinkOpen()) {
144
178
  const mgmtLink = this._mgmtReqResLink;
145
179
  this._mgmtReqResLink = undefined;
@@ -148,7 +182,7 @@ export class ManagementClient {
148
182
  }
149
183
  }
150
184
  catch (err) {
151
- 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}`;
185
+ const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;
152
186
  logger.warning(msg);
153
187
  logErrorStackTrace(err);
154
188
  throw new Error(msg);
@@ -189,7 +223,7 @@ export class ManagementClient {
189
223
  }
190
224
  catch (err) {
191
225
  const translatedError = translate(err);
192
- 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}`);
226
+ logger.warning(`an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`);
193
227
  logErrorStackTrace(translatedError);
194
228
  throw translatedError;
195
229
  }
@@ -219,7 +253,7 @@ export class ManagementClient {
219
253
  }
220
254
  catch (err) {
221
255
  const translatedError = translate(err);
222
- 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}`);
256
+ logger.warning("an error occurred while creating the link: %s", `${translatedError?.name}: ${translatedError?.message}`);
223
257
  logErrorStackTrace(translatedError);
224
258
  throw translatedError;
225
259
  }
@@ -259,7 +293,7 @@ export class ManagementClient {
259
293
  }
260
294
  catch (err) {
261
295
  const translatedError = translate(err);
262
- 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}`);
296
+ logger.warning("an error occurred during send on management request-response link with address: %s", `${translatedError?.name}: ${translatedError?.message}`);
263
297
  logErrorStackTrace(translatedError);
264
298
  throw translatedError;
265
299
  }