@azure/event-hubs 5.13.0-alpha.20241008.6 → 5.13.0-alpha.20241015.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 (44) hide show
  1. package/dist/browser/eventData.d.ts +12 -1
  2. package/dist/browser/eventData.d.ts.map +1 -1
  3. package/dist/browser/eventData.js +35 -1
  4. package/dist/browser/eventData.js.map +1 -1
  5. package/dist/browser/eventDataBatch.d.ts.map +1 -1
  6. package/dist/browser/eventDataBatch.js +4 -1
  7. package/dist/browser/eventDataBatch.js.map +1 -1
  8. package/dist/browser/eventHubProducerClient.d.ts.map +1 -1
  9. package/dist/browser/eventHubProducerClient.js +2 -0
  10. package/dist/browser/eventHubProducerClient.js.map +1 -1
  11. package/dist/browser/partitionReceiver.js +2 -2
  12. package/dist/browser/partitionReceiver.js.map +1 -1
  13. package/dist/browser/util/constants.js +1 -1
  14. package/dist/browser/util/constants.js.map +1 -1
  15. package/dist/commonjs/eventData.d.ts +12 -1
  16. package/dist/commonjs/eventData.d.ts.map +1 -1
  17. package/dist/commonjs/eventData.js +37 -1
  18. package/dist/commonjs/eventData.js.map +1 -1
  19. package/dist/commonjs/eventDataBatch.d.ts.map +1 -1
  20. package/dist/commonjs/eventDataBatch.js +3 -0
  21. package/dist/commonjs/eventDataBatch.js.map +1 -1
  22. package/dist/commonjs/eventHubProducerClient.d.ts.map +1 -1
  23. package/dist/commonjs/eventHubProducerClient.js +2 -0
  24. package/dist/commonjs/eventHubProducerClient.js.map +1 -1
  25. package/dist/commonjs/partitionReceiver.js +1 -1
  26. package/dist/commonjs/partitionReceiver.js.map +1 -1
  27. package/dist/commonjs/util/constants.js +1 -1
  28. package/dist/commonjs/util/constants.js.map +1 -1
  29. package/dist/esm/eventData.d.ts +12 -1
  30. package/dist/esm/eventData.d.ts.map +1 -1
  31. package/dist/esm/eventData.js +35 -1
  32. package/dist/esm/eventData.js.map +1 -1
  33. package/dist/esm/eventDataBatch.d.ts.map +1 -1
  34. package/dist/esm/eventDataBatch.js +4 -1
  35. package/dist/esm/eventDataBatch.js.map +1 -1
  36. package/dist/esm/eventHubProducerClient.d.ts.map +1 -1
  37. package/dist/esm/eventHubProducerClient.js +2 -0
  38. package/dist/esm/eventHubProducerClient.js.map +1 -1
  39. package/dist/esm/partitionReceiver.js +2 -2
  40. package/dist/esm/partitionReceiver.js.map +1 -1
  41. package/dist/esm/util/constants.js +1 -1
  42. package/dist/esm/util/constants.js.map +1 -1
  43. package/dist/event-hubs.d.ts +1 -1
  44. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
- import { populateIdempotentMessageAnnotations, toRheaMessage } from "./eventData.js";
3
+ import { assertIsEventData, isAmqpAnnotatedMessage, populateIdempotentMessageAnnotations, toRheaMessage, } from "./eventData.js";
4
4
  import { message } from "rhea-promise";
5
5
  import { isDefined, isObjectWithProperties } from "@azure/core-util";
6
6
  import { instrumentEventData } from "./diagnostics/instrumentEventData.js";
@@ -206,6 +206,9 @@ export class EventDataBatchImpl {
206
206
  */
207
207
  tryAdd(eventData, options = {}) {
208
208
  throwTypeErrorIfParameterMissing(this._context.connectionId, "tryAdd", "eventData", eventData);
209
+ if (!isAmqpAnnotatedMessage(eventData)) {
210
+ assertIsEventData(eventData);
211
+ }
209
212
  const { entityPath, host } = this._context.config;
210
213
  const { event: instrumentedEvent, spanContext } = instrumentEventData(eventData, options, entityPath, host);
211
214
  // Convert EventData to RheaMessage.
@@ -1 +1 @@
1
- {"version":3,"file":"eventDataBatch.js","sourceRoot":"","sources":["../../src/eventDataBatch.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAa,oCAAoC,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEhG,OAAO,EAAsB,OAAO,EAA0B,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,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I,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC;QACxE,CAAC;QAED,MAAM,WAAW,GAAG,cAAc,CAAC,MAAM,CAAC;QAC1C,MAAM,eAAe,GACnB,WAAW,IAAI,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC;QACpF,WAAW,IAAI,WAAW,GAAG,eAAe,CAAC;QAE7C,kEAAkE;QAClE,mCAAmC;QACnC,IAAI,WAAW,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,kEAAkE;QAClE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC3C,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,CAAC;QAED,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { EventData, populateIdempotentMessageAnnotations, toRheaMessage } from \"./eventData.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { MessageAnnotations, message, Message as RheaMessage } from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties } from \"@azure/core-util\";\nimport { OperationTracingOptions, TracingContext } from \"@azure/core-tracing\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { PartitionPublishingProperties } from \"./models/private.js\";\n\n/**\n * The amount of bytes to reserve as overhead for a small message.\n */\nconst smallMessageOverhead = 5;\n/**\n * The amount of bytes to reserve as overhead for a large message.\n */\nconst largeMessageOverhead = 8;\n/**\n * The maximum number of bytes that a message may be to be considered small.\n */\nconst smallMessageMaxBytes = 255;\n\n/**\n * Checks if the provided eventDataBatch is an instance of `EventDataBatch`.\n * @param eventDataBatch - The instance of `EventDataBatch` to verify.\n * @internal\n */\nexport function isEventDataBatch(eventDataBatch: unknown): eventDataBatch is EventDataBatch {\n return (\n isObjectWithProperties(eventDataBatch, [\"count\", \"sizeInBytes\", \"tryAdd\"]) &&\n typeof eventDataBatch.tryAdd === \"function\" &&\n typeof eventDataBatch.count === \"number\" &&\n typeof eventDataBatch.sizeInBytes === \"number\"\n );\n}\n\n/**\n * Options to configure the behavior of the `tryAdd` method on the `EventDataBatch` class.\n */\nexport interface TryAddOptions {\n /**\n * The options to use when creating Spans for tracing.\n */\n tracingOptions?: OperationTracingOptions;\n}\n\n/**\n * An interface representing a batch of events which can be used to send events to Event Hub.\n *\n * To create the batch, use the `createBatch()` method on the `EventHubProducerClient`.\n * To send the batch, use the `sendBatch()` method on the same client.\n * To fill the batch, use the `tryAdd()` method on the batch itself.\n *\n */\nexport interface EventDataBatch {\n /**\n * A value that is hashed and used by the Azure Event Hubs service to determine the partition to\n * which the events are sent. Use the `createBatch()` method on the `EventHubProducerClient` to\n * set the partitionKey.\n * @readonly\n * @internal\n */\n readonly partitionKey?: string;\n\n /**\n * Id of the partition to which the batch of events are sent. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the partitionId.\n * @readonly\n * @internal\n */\n readonly partitionId?: string;\n\n /**\n * Size of the batch in bytes after the events added to it have been encoded into a single AMQP\n * message.\n * @readonly\n */\n readonly sizeInBytes: number;\n\n /**\n * Number of events added to the batch.\n * @readonly\n */\n readonly count: number;\n\n /**\n * The maximum size of the batch, in bytes. The `tryAdd` function on the batch will return `false`\n * if the event being added causes the size of the batch to exceed this limit. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the maxSizeInBytes.\n * @readonly\n */\n readonly maxSizeInBytes: number;\n\n /**\n * Adds an event to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object or AmqpAnnotatedMessage.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n tryAdd(eventData: EventData | AmqpAnnotatedMessage, options?: TryAddOptions): boolean;\n}\n\n/**\n * An internal class representing a batch of events which can be used to send events to Event Hub.\n *\n * @internal\n */\nexport class EventDataBatchImpl implements EventDataBatch {\n /**\n * Describes the amqp connection context for the Client.\n */\n private _context: ConnectionContext;\n /**\n * The Id of the partition to which the batch is expected to be sent to.\n * Specifying this will throw an error if the batch was created using a `partitionKey`.\n */\n private _partitionId?: string;\n /**\n * A value that is hashed to produce a partition assignment.\n * It guarantees that messages with the same partitionKey end up in the same partition.\n * Specifying this will throw an error if the batch was created using a `partitionId`.\n */\n private _partitionKey?: string;\n /**\n * The maximum size allowed for the batch.\n */\n private _maxSizeInBytes: number;\n /**\n * Current size of the batch in bytes.\n */\n private _sizeInBytes: number;\n /**\n * Encoded amqp messages.\n */\n private _encodedMessages: Buffer[] = [];\n /**\n * Number of events in the batch.\n */\n private _count: number;\n /**\n * List of 'message' span contexts.\n */\n private _spanContexts: TracingContext[] = [];\n /**\n * The message annotations to apply on the batch envelope.\n * This will reflect the message annotations on the first event\n * that was added to the batch.\n * A common annotation is the partition key.\n */\n private _batchAnnotations?: MessageAnnotations;\n /**\n * Indicates that the batch should be treated as idempotent.\n */\n private _isIdempotent: boolean;\n /**\n * The sequence number assigned to the first event in the batch while\n * the batch is being sent to the service.\n */\n private _pendingStartingSequenceNumber?: number;\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n private _startingPublishSequenceNumber?: number;\n\n /**\n * EventDataBatch should not be constructed using `new EventDataBatch()`\n * Use the `createBatch()` method on your `EventHubProducer` instead.\n * @internal\n */\n constructor(\n context: ConnectionContext,\n maxSizeInBytes: number,\n isIdempotent: boolean,\n partitionKey?: string,\n partitionId?: string,\n ) {\n this._context = context;\n this._maxSizeInBytes = maxSizeInBytes;\n this._isIdempotent = isIdempotent;\n this._partitionKey = isDefined(partitionKey) ? String(partitionKey) : partitionKey;\n this._partitionId = isDefined(partitionId) ? String(partitionId) : partitionId;\n this._sizeInBytes = 0;\n this._count = 0;\n }\n\n /**\n * The maximum size of the batch, in bytes.\n * @readonly\n */\n get maxSizeInBytes(): number {\n return this._maxSizeInBytes;\n }\n\n /**\n * The partitionKey set during `EventDataBatch` creation. This value is hashed to\n * produce a partition assignment when the producer is created without a `partitionId`\n * @readonly\n */\n get partitionKey(): string | undefined {\n return this._partitionKey;\n }\n\n /**\n * The partitionId set during `EventDataBatch` creation.\n * If this value is set then partitionKey can not be set.\n * @readonly\n */\n get partitionId(): string | undefined {\n return this._partitionId;\n }\n\n /**\n * Size of the `EventDataBatch` instance after the events added to it have been\n * encoded into a single AMQP message.\n * @readonly\n */\n get sizeInBytes(): number {\n return this._sizeInBytes;\n }\n\n /**\n * Number of events in the `EventDataBatch` instance.\n * @readonly\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n get startingPublishedSequenceNumber(): number | undefined {\n return this._startingPublishSequenceNumber;\n }\n\n /**\n * Gets the \"message\" span contexts that were created when adding events to the batch.\n * @internal\n */\n get _messageSpanContexts(): TracingContext[] {\n return this._spanContexts;\n }\n\n /**\n * Generates an AMQP message that contains the provided encoded events and annotations.\n * @param encodedEvents - The already encoded events to include in the AMQP batch.\n * @param annotations - The message annotations to set on the batch.\n * @param publishingProps - Idempotent publishing properties used to decorate the events in the batch while sending.\n */\n private _generateBatch(\n encodedEvents: Buffer[],\n annotations: MessageAnnotations | undefined,\n publishingProps?: PartitionPublishingProperties,\n ): Buffer {\n if (this._isIdempotent && publishingProps) {\n // We need to decode the encoded events, add the idempotent annotations, and re-encode them.\n // We can't lazily encode the events because we rely on `message.encode` to capture the\n // byte length of anything not in `event.body`.\n // Events can't be decorated ahead of time because the publishing properties aren't known\n // until the events are being sent to the service.\n const decodedEvents = encodedEvents.map(message.decode) as unknown as RheaMessage[];\n const decoratedEvents = this._decorateRheaMessagesWithPublishingProps(\n decodedEvents,\n publishingProps,\n );\n encodedEvents = decoratedEvents.map(message.encode);\n }\n\n const batchEnvelope: RheaMessage = {\n body: message.data_sections(encodedEvents),\n };\n if (annotations) {\n batchEnvelope.message_annotations = annotations;\n }\n return message.encode(batchEnvelope);\n }\n\n /**\n * Uses the publishingProps to add idempotent properties as message annotations to rhea messages.\n */\n private _decorateRheaMessagesWithPublishingProps(\n events: RheaMessage[],\n publishingProps: PartitionPublishingProperties,\n ): RheaMessage[] {\n if (!this._isIdempotent) {\n return events;\n }\n\n const { lastPublishedSequenceNumber = 0, ownerLevel, producerGroupId } = publishingProps;\n const startingSequenceNumber = lastPublishedSequenceNumber + 1;\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber: startingSequenceNumber + i,\n });\n }\n\n this._pendingStartingSequenceNumber = startingSequenceNumber;\n return events;\n }\n\n /**\n * Annotates a rhea message with placeholder idempotent properties if the batch is idempotent.\n * This is necessary so that we can accurately calculate the size of the batch while adding events.\n * Placeholder values are used because real values won't be known until we attempt to send the batch.\n */\n private _decorateRheaMessageWithPlaceholderIdempotencyProps(event: RheaMessage): RheaMessage {\n if (!this._isIdempotent) {\n return event;\n }\n\n if (!event.message_annotations) {\n event.message_annotations = {};\n }\n\n // Set placeholder values for these annotations.\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel: 0,\n publishSequenceNumber: 0,\n producerGroupId: 0,\n });\n\n return event;\n }\n\n /**\n * Generates the single AMQP message which is the result of encoding all the events\n * added into the `EventDataBatch` instance.\n *\n * This is not meant for the user to use directly.\n *\n * When the `EventDataBatch` instance is passed to the `send()` method on the `EventHubProducer`,\n * this single batched AMQP message is what gets sent over the wire to the service.\n * @readonly\n */\n _generateMessage(publishingProps?: PartitionPublishingProperties): Buffer {\n return this._generateBatch(this._encodedMessages, this._batchAnnotations, publishingProps);\n }\n\n /**\n * Sets startingPublishSequenceNumber to the pending publish sequence number.\n */\n _commitPublish(): void {\n this._startingPublishSequenceNumber = this._pendingStartingSequenceNumber;\n }\n\n /**\n * Tries to add an event data to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n public tryAdd(eventData: EventData | AmqpAnnotatedMessage, options: TryAddOptions = {}): boolean {\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"tryAdd\", \"eventData\", eventData);\n\n const { entityPath, host } = this._context.config;\n const { event: instrumentedEvent, spanContext } = instrumentEventData(\n eventData,\n options,\n entityPath,\n host,\n );\n\n // Convert EventData to RheaMessage.\n const amqpMessage = toRheaMessage(instrumentedEvent, this._partitionKey);\n const originalAnnotations = amqpMessage.message_annotations && {\n ...amqpMessage.message_annotations,\n };\n this._decorateRheaMessageWithPlaceholderIdempotencyProps(amqpMessage);\n const encodedMessage = message.encode(amqpMessage);\n\n let currentSize = this._sizeInBytes;\n // The first time an event is added, we need to calculate\n // the overhead of creating an AMQP batch, including the\n // message_annotations that are taken from the 1st message.\n if (this.count === 0) {\n if (originalAnnotations) {\n this._batchAnnotations = originalAnnotations;\n }\n\n // Figure out the overhead of creating a batch by generating an empty batch\n // with the expected batch annotations.\n currentSize += this._generateBatch([], this._batchAnnotations).length;\n }\n\n const messageSize = encodedMessage.length;\n const messageOverhead =\n messageSize <= smallMessageMaxBytes ? smallMessageOverhead : largeMessageOverhead;\n currentSize += messageSize + messageOverhead;\n\n // Check if the size of the batch exceeds the maximum allowed size\n // once we add the new event to it.\n if (currentSize > this._maxSizeInBytes) {\n return false;\n }\n\n // The event will fit in the batch, so it is now safe to store it.\n this._encodedMessages.push(encodedMessage);\n if (spanContext) {\n this._spanContexts.push(spanContext);\n }\n\n this._sizeInBytes = currentSize;\n this._count++;\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"eventDataBatch.js","sourceRoot":"","sources":["../../src/eventDataBatch.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EACL,iBAAiB,EAEjB,sBAAsB,EACtB,oCAAoC,EACpC,aAAa,GACd,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAsB,OAAO,EAA0B,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAErE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAC;AAGnE;;GAEG;AACH,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B;;GAEG;AACH,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B;;GAEG;AACH,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,cAAuB;IACtD,OAAO,CACL,sBAAsB,CAAC,cAAc,EAAE,CAAC,OAAO,EAAE,aAAa,EAAE,QAAQ,CAAC,CAAC;QAC1E,OAAO,cAAc,CAAC,MAAM,KAAK,UAAU;QAC3C,OAAO,cAAc,CAAC,KAAK,KAAK,QAAQ;QACxC,OAAO,cAAc,CAAC,WAAW,KAAK,QAAQ,CAC/C,CAAC;AACJ,CAAC;AAsED;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IA4D7B;;;;OAIG;IACH,YACE,OAA0B,EAC1B,cAAsB,EACtB,YAAqB,EACrB,YAAqB,EACrB,WAAoB;QA9CtB;;WAEG;QACK,qBAAgB,GAAa,EAAE,CAAC;QAKxC;;WAEG;Q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copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport {\n assertIsEventData,\n EventData,\n isAmqpAnnotatedMessage,\n populateIdempotentMessageAnnotations,\n toRheaMessage,\n} from \"./eventData.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { MessageAnnotations, message, Message as RheaMessage } from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties } from \"@azure/core-util\";\nimport { OperationTracingOptions, TracingContext } from \"@azure/core-tracing\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { PartitionPublishingProperties } from \"./models/private.js\";\n\n/**\n * The amount of bytes to reserve as overhead for a small message.\n */\nconst smallMessageOverhead = 5;\n/**\n * The amount of bytes to reserve as overhead for a large message.\n */\nconst largeMessageOverhead = 8;\n/**\n * The maximum number of bytes that a message may be to be considered small.\n */\nconst smallMessageMaxBytes = 255;\n\n/**\n * Checks if the provided eventDataBatch is an instance of `EventDataBatch`.\n * @param eventDataBatch - The instance of `EventDataBatch` to verify.\n * @internal\n */\nexport function isEventDataBatch(eventDataBatch: unknown): eventDataBatch is EventDataBatch {\n return (\n isObjectWithProperties(eventDataBatch, [\"count\", \"sizeInBytes\", \"tryAdd\"]) &&\n typeof eventDataBatch.tryAdd === \"function\" &&\n typeof eventDataBatch.count === \"number\" &&\n typeof eventDataBatch.sizeInBytes === \"number\"\n );\n}\n\n/**\n * Options to configure the behavior of the `tryAdd` method on the `EventDataBatch` class.\n */\nexport interface TryAddOptions {\n /**\n * The options to use when creating Spans for tracing.\n */\n tracingOptions?: OperationTracingOptions;\n}\n\n/**\n * An interface representing a batch of events which can be used to send events to Event Hub.\n *\n * To create the batch, use the `createBatch()` method on the `EventHubProducerClient`.\n * To send the batch, use the `sendBatch()` method on the same client.\n * To fill the batch, use the `tryAdd()` method on the batch itself.\n *\n */\nexport interface EventDataBatch {\n /**\n * A value that is hashed and used by the Azure Event Hubs service to determine the partition to\n * which the events are sent. Use the `createBatch()` method on the `EventHubProducerClient` to\n * set the partitionKey.\n * @readonly\n * @internal\n */\n readonly partitionKey?: string;\n\n /**\n * Id of the partition to which the batch of events are sent. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the partitionId.\n * @readonly\n * @internal\n */\n readonly partitionId?: string;\n\n /**\n * Size of the batch in bytes after the events added to it have been encoded into a single AMQP\n * message.\n * @readonly\n */\n readonly sizeInBytes: number;\n\n /**\n * Number of events added to the batch.\n * @readonly\n */\n readonly count: number;\n\n /**\n * The maximum size of the batch, in bytes. The `tryAdd` function on the batch will return `false`\n * if the event being added causes the size of the batch to exceed this limit. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the maxSizeInBytes.\n * @readonly\n */\n readonly maxSizeInBytes: number;\n\n /**\n * Adds an event to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object or AmqpAnnotatedMessage.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n tryAdd(eventData: EventData | AmqpAnnotatedMessage, options?: TryAddOptions): boolean;\n}\n\n/**\n * An internal class representing a batch of events which can be used to send events to Event Hub.\n *\n * @internal\n */\nexport class EventDataBatchImpl implements EventDataBatch {\n /**\n * Describes the amqp connection context for the Client.\n */\n private _context: ConnectionContext;\n /**\n * The Id of the partition to which the batch is expected to be sent to.\n * Specifying this will throw an error if the batch was created using a `partitionKey`.\n */\n private _partitionId?: string;\n /**\n * A value that is hashed to produce a partition assignment.\n * It guarantees that messages with the same partitionKey end up in the same partition.\n * Specifying this will throw an error if the batch was created using a `partitionId`.\n */\n private _partitionKey?: string;\n /**\n * The maximum size allowed for the batch.\n */\n private _maxSizeInBytes: number;\n /**\n * Current size of the batch in bytes.\n */\n private _sizeInBytes: number;\n /**\n * Encoded amqp messages.\n */\n private _encodedMessages: Buffer[] = [];\n /**\n * Number of events in the batch.\n */\n private _count: number;\n /**\n * List of 'message' span contexts.\n */\n private _spanContexts: TracingContext[] = [];\n /**\n * The message annotations to apply on the batch envelope.\n * This will reflect the message annotations on the first event\n * that was added to the batch.\n * A common annotation is the partition key.\n */\n private _batchAnnotations?: MessageAnnotations;\n /**\n * Indicates that the batch should be treated as idempotent.\n */\n private _isIdempotent: boolean;\n /**\n * The sequence number assigned to the first event in the batch while\n * the batch is being sent to the service.\n */\n private _pendingStartingSequenceNumber?: number;\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n private _startingPublishSequenceNumber?: number;\n\n /**\n * EventDataBatch should not be constructed using `new EventDataBatch()`\n * Use the `createBatch()` method on your `EventHubProducer` instead.\n * @internal\n */\n constructor(\n context: ConnectionContext,\n maxSizeInBytes: number,\n isIdempotent: boolean,\n partitionKey?: string,\n partitionId?: string,\n ) {\n this._context = context;\n this._maxSizeInBytes = maxSizeInBytes;\n this._isIdempotent = isIdempotent;\n this._partitionKey = isDefined(partitionKey) ? String(partitionKey) : partitionKey;\n this._partitionId = isDefined(partitionId) ? String(partitionId) : partitionId;\n this._sizeInBytes = 0;\n this._count = 0;\n }\n\n /**\n * The maximum size of the batch, in bytes.\n * @readonly\n */\n get maxSizeInBytes(): number {\n return this._maxSizeInBytes;\n }\n\n /**\n * The partitionKey set during `EventDataBatch` creation. This value is hashed to\n * produce a partition assignment when the producer is created without a `partitionId`\n * @readonly\n */\n get partitionKey(): string | undefined {\n return this._partitionKey;\n }\n\n /**\n * The partitionId set during `EventDataBatch` creation.\n * If this value is set then partitionKey can not be set.\n * @readonly\n */\n get partitionId(): string | undefined {\n return this._partitionId;\n }\n\n /**\n * Size of the `EventDataBatch` instance after the events added to it have been\n * encoded into a single AMQP message.\n * @readonly\n */\n get sizeInBytes(): number {\n return this._sizeInBytes;\n }\n\n /**\n * Number of events in the `EventDataBatch` instance.\n * @readonly\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n get startingPublishedSequenceNumber(): number | undefined {\n return this._startingPublishSequenceNumber;\n }\n\n /**\n * Gets the \"message\" span contexts that were created when adding events to the batch.\n * @internal\n */\n get _messageSpanContexts(): TracingContext[] {\n return this._spanContexts;\n }\n\n /**\n * Generates an AMQP message that contains the provided encoded events and annotations.\n * @param encodedEvents - The already encoded events to include in the AMQP batch.\n * @param annotations - The message annotations to set on the batch.\n * @param publishingProps - Idempotent publishing properties used to decorate the events in the batch while sending.\n */\n private _generateBatch(\n encodedEvents: Buffer[],\n annotations: MessageAnnotations | undefined,\n publishingProps?: PartitionPublishingProperties,\n ): Buffer {\n if (this._isIdempotent && publishingProps) {\n // We need to decode the encoded events, add the idempotent annotations, and re-encode them.\n // We can't lazily encode the events because we rely on `message.encode` to capture the\n // byte length of anything not in `event.body`.\n // Events can't be decorated ahead of time because the publishing properties aren't known\n // until the events are being sent to the service.\n const decodedEvents = encodedEvents.map(message.decode) as unknown as RheaMessage[];\n const decoratedEvents = this._decorateRheaMessagesWithPublishingProps(\n decodedEvents,\n publishingProps,\n );\n encodedEvents = decoratedEvents.map(message.encode);\n }\n\n const batchEnvelope: RheaMessage = {\n body: message.data_sections(encodedEvents),\n };\n if (annotations) {\n batchEnvelope.message_annotations = annotations;\n }\n return message.encode(batchEnvelope);\n }\n\n /**\n * Uses the publishingProps to add idempotent properties as message annotations to rhea messages.\n */\n private _decorateRheaMessagesWithPublishingProps(\n events: RheaMessage[],\n publishingProps: PartitionPublishingProperties,\n ): RheaMessage[] {\n if (!this._isIdempotent) {\n return events;\n }\n\n const { lastPublishedSequenceNumber = 0, ownerLevel, producerGroupId } = publishingProps;\n const startingSequenceNumber = lastPublishedSequenceNumber + 1;\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber: startingSequenceNumber + i,\n });\n }\n\n this._pendingStartingSequenceNumber = startingSequenceNumber;\n return events;\n }\n\n /**\n * Annotates a rhea message with placeholder idempotent properties if the batch is idempotent.\n * This is necessary so that we can accurately calculate the size of the batch while adding events.\n * Placeholder values are used because real values won't be known until we attempt to send the batch.\n */\n private _decorateRheaMessageWithPlaceholderIdempotencyProps(event: RheaMessage): RheaMessage {\n if (!this._isIdempotent) {\n return event;\n }\n\n if (!event.message_annotations) {\n event.message_annotations = {};\n }\n\n // Set placeholder values for these annotations.\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel: 0,\n publishSequenceNumber: 0,\n producerGroupId: 0,\n });\n\n return event;\n }\n\n /**\n * Generates the single AMQP message which is the result of encoding all the events\n * added into the `EventDataBatch` instance.\n *\n * This is not meant for the user to use directly.\n *\n * When the `EventDataBatch` instance is passed to the `send()` method on the `EventHubProducer`,\n * this single batched AMQP message is what gets sent over the wire to the service.\n * @readonly\n */\n _generateMessage(publishingProps?: PartitionPublishingProperties): Buffer {\n return this._generateBatch(this._encodedMessages, this._batchAnnotations, publishingProps);\n }\n\n /**\n * Sets startingPublishSequenceNumber to the pending publish sequence number.\n */\n _commitPublish(): void {\n this._startingPublishSequenceNumber = this._pendingStartingSequenceNumber;\n }\n\n /**\n * Tries to add an event data to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n public tryAdd(eventData: EventData | AmqpAnnotatedMessage, options: TryAddOptions = {}): boolean {\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"tryAdd\", \"eventData\", eventData);\n if (!isAmqpAnnotatedMessage(eventData)) {\n assertIsEventData(eventData);\n }\n\n const { entityPath, host } = this._context.config;\n const { event: instrumentedEvent, spanContext } = instrumentEventData(\n eventData,\n options,\n entityPath,\n host,\n );\n\n // Convert EventData to RheaMessage.\n const amqpMessage = toRheaMessage(instrumentedEvent, this._partitionKey);\n const originalAnnotations = amqpMessage.message_annotations && {\n ...amqpMessage.message_annotations,\n };\n this._decorateRheaMessageWithPlaceholderIdempotencyProps(amqpMessage);\n const encodedMessage = message.encode(amqpMessage);\n\n let currentSize = this._sizeInBytes;\n // The first time an event is added, we need to calculate\n // the overhead of creating an AMQP batch, including the\n // message_annotations that are taken from the 1st message.\n if (this.count === 0) {\n if (originalAnnotations) {\n this._batchAnnotations = originalAnnotations;\n }\n\n // Figure out the overhead of creating a batch by generating an empty batch\n // with the expected batch annotations.\n currentSize += this._generateBatch([], this._batchAnnotations).length;\n }\n\n const messageSize = encodedMessage.length;\n const messageOverhead =\n messageSize <= smallMessageMaxBytes ? smallMessageOverhead : largeMessageOverhead;\n currentSize += messageSize + messageOverhead;\n\n // Check if the size of the batch exceeds the maximum allowed size\n // once we add the new event to it.\n if (currentSize > this._maxSizeInBytes) {\n return false;\n }\n\n // The event will fit in the batch, so it is now safe to store it.\n this._encodedMessages.push(encodedMessage);\n if (spanContext) {\n this._spanContexts.push(spanContext);\n }\n\n this._sizeInBytes = currentSize;\n this._count++;\n return true;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"eventHubProducerClient.d.ts","sourceRoot":"","sources":["../../src/eventHubProducerClient.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,4BAA4B,EAC5B,sBAAsB,EACtB,6BAA6B,EAC7B,gBAAgB,EACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAwC,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,kBAAkB,C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,OAAO,CAAC,IAAI,CAAC;IA8FjF;;;;;OAKG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAS5B;;;;;;OAMG;IACH,qBAAqB,CAAC,OAAO,GAAE,4BAAiC,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAO9F;;;;;;;OAOG;IACH,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAW7E;;;;;;;OAOG;IACH,sBAAsB,CACpB,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE,6BAAkC,GAC1C,OAAO,CAAC,mBAAmB,CAAC;CAMhC"}
@@ -6,6 +6,7 @@ import { isDefined } from "@azure/core-util";
6
6
  import { isCredential } from "./util/typeGuards.js";
7
7
  import { logErrorStackTrace, logger } from "./logger.js";
8
8
  import { idempotentAlreadyPublished, idempotentSomeAlreadyPublished, throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing, validateProducerPartitionSettings, } from "./util/error.js";
9
+ import { assertIsEventData } from "./eventData.js";
9
10
  import { EventHubSender } from "./eventHubSender.js";
10
11
  import { toSpanOptions, tracingClient } from "./diagnostics/tracing.js";
11
12
  import { instrumentEventData } from "./diagnostics/instrumentEventData.js";
@@ -188,6 +189,7 @@ export class EventHubProducerClient {
188
189
  if (!Array.isArray(batch)) {
189
190
  batch = [batch];
190
191
  }
192
+ batch.forEach(assertIsEventData);
191
193
  if (batch.some((event) => isDefined(event._publishedSequenceNumber))) {
192
194
  throw new Error(idempotentSomeAlreadyPublished);
193
195
  }
@@ -1 +1 @@
1
- {"version":3,"file":"eventHubProducerClient.js","sourceRoot":"","sources":["../../src/eventHubProducerClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAqB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAUpF,OAAO,EAAkB,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAI3F,OAAO,E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E,qBAAqB,EAAE,YAAY,EAAE,sBAAsB,EAAE,GAChF,qCAAqC,CAAC,OAAO,CAAC,CAAC;IACjD,IAAI,sBAAsB,IAAI,YAAY,KAAK,sBAAsB,EAAE,CAAC;QACtE,MAAM,IAAI,KAAK,CACb,qBAAqB,sBAAsB,uDAAuD,YAAY,gCAAgC,CAC/I,CAAC;IACJ,CAAC;IACD,IAAI,qBAAqB,IAAI,qBAAqB,KAAK,WAAW,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CACb,oBAAoB,qBAAqB,sDAAsD,WAAW,gCAAgC,CAC3I,CAAC;IACJ,CAAC;IAED,IAAI,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC;QAC3B,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC;QAC5B,MAAM,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ConnectionContext, createConnectionContext } from \"./connectionContext.js\";\nimport {\n CreateBatchOptions,\n EventHubClientOptions,\n GetEventHubPropertiesOptions,\n GetPartitionIdsOptions,\n GetPartitionPropertiesOptions,\n SendBatchOptions,\n} from \"./models/public.js\";\nimport { PartitionPublishingOptions, PartitionPublishingProperties } from \"./models/private.js\";\nimport { EventDataBatch, EventDataBatchImpl, isEventDataBatch } from \"./eventDataBatch.js\";\nimport { EventHubProperties, PartitionProperties } from \"./managementClient.js\";\nimport { TracingContext, TracingSpanLink } from \"@azure/core-tracing\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport { isDefined } from \"@azure/core-util\";\nimport { isCredential } from \"./util/typeGuards.js\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport {\n idempotentAlreadyPublished,\n idempotentSomeAlreadyPublished,\n throwErrorIfConnectionClosed,\n throwTypeErrorIfParameterMissing,\n validateProducerPartitionSettings,\n} from \"./util/error.js\";\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { EventData, EventDataInternal } from \"./eventData.js\";\nimport { EventHubSender } from \"./eventHubSender.js\";\nimport { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n *\n * There are multiple ways to create an `EventHubProducerClient`\n * - Use the connection string from the SAS policy created for your Event Hub instance.\n * - Use the connection string from the SAS policy created for your Event Hub namespace,\n * and the name of the Event Hub instance\n * - Use the full namespace like `<yournamespace>.servicebus.windows.net`, and a credentials object.\n *\n * Optionally, you can also pass an options bag to configure the retry policy or proxy settings.\n *\n */\nexport class EventHubProducerClient {\n /**\n * Describes the amqp connection context for the client.\n */\n private _context: ConnectionContext;\n\n /**\n * The options passed by the user when creating the EventHubClient instance.\n */\n private _clientOptions: EventHubClientOptions;\n /**\n * Map of partitionId to senders\n */\n private _sendersMap: Map<string, EventHubSender>;\n /**\n * Indicates whether or not the EventHubProducerClient should enable idempotent publishing to Event Hub partitions.\n * If enabled, the producer will only be able to publish directly to partitions;\n * it will not be able to publish to the Event Hubs gateway for automatic partition routing\n * nor will it be able to use a partition key.\n * Default: false\n */\n private _enableIdempotentRetries?: boolean;\n /**\n * The set of options that can be specified to influence publishing behavior specific to the configured Event Hub partition.\n * These options are not necessary in the majority of scenarios and are intended for use with specialized scenarios,\n * such as when recovering the state used for idempotent publishing.\n */\n private _partitionOptions?: Record<string, PartitionPublishingOptions>;\n /**\n * @readonly\n * The name of the Event Hub instance for which this client is created.\n */\n get eventHubName(): string {\n return this._context.config.entityPath;\n }\n\n /**\n * @readonly\n * The fully qualified namespace of the Event Hub instance for which this client is created.\n * This is likely to be similar to <yournamespace>.servicebus.windows.net.\n */\n get fullyQualifiedNamespace(): string {\n return this._context.config.host;\n }\n\n /**\n * The name used to identify this EventHubProducerClient.\n * If not specified or empty, a random unique one will be generated.\n */\n public readonly identifier: string;\n\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, eventHubName: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n options?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n );\n constructor(\n fullyQualifiedNamespaceOrConnectionString1: string,\n eventHubNameOrOptions2?: string | EventHubClientOptions,\n credentialOrOptions3?:\n | TokenCredential\n | NamedKeyCredential\n | SASCredential\n | EventHubClientOptions,\n options4?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n ) {\n this._context = createConnectionContext(\n fullyQualifiedNamespaceOrConnectionString1,\n eventHubNameOrOptions2,\n credentialOrOptions3,\n options4,\n );\n if (typeof eventHubNameOrOptions2 !== \"string\") {\n this._clientOptions = eventHubNameOrOptions2 || {};\n } else if (!isCredential(credentialOrOptions3)) {\n this._clientOptions = credentialOrOptions3 || {};\n } else {\n this._clientOptions = options4 || {};\n }\n this.identifier = this._clientOptions.identifier ?? getRandomName();\n this._sendersMap = new Map();\n }\n\n /**\n * Creates an instance of `EventDataBatch` to which one can add events until the maximum supported size is reached.\n * The batch can be passed to the {@link sendBatch} method of the `EventHubProducerClient` to be sent to Azure Event Hubs.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n *\n * @param options - Configures the behavior of the batch.\n * - `partitionKey` : A value that is hashed and used by the Azure Event Hubs service to determine the partition to which\n * the events need to be sent.\n * - `partitionId` : Id of the partition to which the batch of events need to be sent.\n * - `maxSizeInBytes`: The upper limit for the size of batch. The `tryAdd` function will return `false` after this limit is reached.\n * - `abortSignal` : A signal the request to cancel the operation.\n * @returns Promise<EventDataBatch>\n * @throws Error if both `partitionId` and `partitionKey` are set in the options.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal in the options.\n */\n async createBatch(options: CreateBatchOptions = {}): Promise<EventDataBatch> {\n throwErrorIfConnectionClosed(this._context);\n\n const partitionId = isDefined(options.partitionId) ? String(options.partitionId) : undefined;\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey: options.partitionKey,\n });\n\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n let maxMessageSize = await sender.getMaxMessageSize({\n retryOptions: this._clientOptions.retryOptions,\n abortSignal: options.abortSignal,\n });\n\n if (options.maxSizeInBytes) {\n if (options.maxSizeInBytes > maxMessageSize) {\n const error = new Error(\n `Max message size (${options.maxSizeInBytes} bytes) is greater than maximum message size (${maxMessageSize} bytes) on the AMQP sender link.`,\n );\n logger.warning(`[${this._context.connectionId}] ${error.message}`);\n logErrorStackTrace(error);\n throw error;\n }\n maxMessageSize = options.maxSizeInBytes;\n }\n return new EventDataBatchImpl(\n this._context,\n maxMessageSize,\n Boolean(this._enableIdempotentRetries),\n options.partitionKey,\n partitionId,\n );\n }\n\n /**\n * Get the information about the state of publishing for a partition as observed by the `EventHubProducerClient`.\n * This data can always be read, but will only be populated with information relevant to the active features\n * for the producer client.\n *\n * @param partitionId - Id of the partition from which to retrieve publishing properties.\n * @param options - The set of options to apply to the operation call.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore this is called in EventHubBufferedProducerClient via cast-to-any workaround\n private async getPartitionPublishingProperties(\n partitionId: string,\n options: OperationOptions = {},\n ): Promise<PartitionPublishingProperties> {\n if (!isDefined(partitionId)) {\n throw new TypeError(\n `getPartitionPublishingProperties called without required argument \"partitionId\"`,\n );\n }\n\n if (typeof partitionId === \"number\") {\n partitionId = String(partitionId);\n }\n\n let sender = this._sendersMap.get(partitionId);\n if (!sender) {\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions: this._partitionOptions?.[partitionId],\n });\n this._sendersMap.set(partitionId, sender);\n }\n\n return sender.getPartitionPublishingProperties(options);\n }\n\n /**\n * Sends an array of events as a batch to the associated Event Hub.\n *\n * Azure Event Hubs has a limit on the size of the batch that can be sent which if exceeded\n * will result in an error with code `MessageTooLargeError`.\n * To safely send within batch size limits, use `EventHubProducerClient.createBatch()` or\n * `EventHubBufferedProducerClient` instead.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * await client.sendBatch(messages);\n * ```\n *\n * @param batch - An array of {@link EventData} or `AmqpAnnotatedMessage`.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * - `partitionId` : The partition this batch will be sent to. If set, `partitionKey` can not be set.\n * - `partitionKey` : A value that is hashed to produce a partition assignment. If set, `partitionId` can not be set.\n *\n * @returns Promise<void>\n * @throws MessageTooLargeError if all the events in the input array cannot be fit into a batch.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(\n batch: EventData[] | AmqpAnnotatedMessage[],\n options?: SendBatchOptions,\n ): Promise<void>;\n /**\n * Sends a batch of events created using `EventHubProducerClient.createBatch()` to the associated Event Hub.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n * @param batch - A batch of events that you can create using the {@link createBatch} method.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n *\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(batch: EventDataBatch, options?: OperationOptions): Promise<void>; // eslint-disable-line @azure/azure-sdk/ts-naming-options\n async sendBatch(\n batch: EventDataBatch | EventData[],\n options: SendBatchOptions | OperationOptions = {},\n ): Promise<void> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"sendBatch\", \"batch\", batch);\n\n let partitionId: string | undefined;\n let partitionKey: string | undefined;\n\n // Holds an EventData properties object containing tracing properties.\n // This lets us avoid cloning batch when it is EventData[], which is\n // important as the idempotent EventHubSender needs to decorate the\n // original EventData passed through.\n const eventDataTracingProperties: Array<EventData[\"properties\"]> = [];\n\n // link message span contexts\n let spanContextsToLink: TracingContext[] = [];\n\n if (isEventDataBatch(batch)) {\n if (\n this._enableIdempotentRetries &&\n isDefined((batch as EventDataBatchImpl).startingPublishedSequenceNumber)\n ) {\n throw new Error(idempotentAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromBatch(batch, options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n spanContextsToLink = (batch as EventDataBatchImpl)._messageSpanContexts;\n } else {\n if (!Array.isArray(batch)) {\n batch = [batch];\n }\n if (batch.some((event) => isDefined((event as EventDataInternal)._publishedSequenceNumber))) {\n throw new Error(idempotentSomeAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromOptions(options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n\n for (let i = 0; i < batch.length; i++) {\n batch[i] = instrumentEventData(\n batch[i],\n options,\n this._context.config.entityPath,\n this._context.config.host,\n \"publish\",\n ).event;\n eventDataTracingProperties[i] = batch[i].properties;\n }\n }\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey,\n });\n\n return tracingClient.withSpan(\n `${EventHubProducerClient.name}.${this.sendBatch.name}`,\n options,\n (updatedOptions) => {\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n return sender.send(batch, {\n ...updatedOptions,\n partitionId,\n partitionKey,\n retryOptions: this._clientOptions.retryOptions,\n });\n },\n {\n spanLinks: spanContextsToLink.map<TracingSpanLink>((tracingContext) => {\n return { tracingContext };\n }),\n ...toSpanOptions(this._context.config, \"publish\", \"client\"),\n },\n );\n }\n\n /**\n * Closes the AMQP connection to the Event Hub instance,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns Promise<void>\n * @throws Error if the underlying connection encounters an error while closing.\n */\n async close(): Promise<void> {\n await this._context.close();\n\n for (const pair of this._sendersMap) {\n await pair[1].close();\n }\n this._sendersMap.clear();\n }\n\n /**\n * Provides the Event Hub runtime information.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the Event Hub instance.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getEventHubProperties(options: GetEventHubPropertiesOptions = {}): Promise<EventHubProperties> {\n return this._context.managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n\n /**\n * Provides the id for each partition associated with the Event Hub.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with an Array of strings representing the id for\n * each partition associated with the Event Hub.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionIds(options: GetPartitionIdsOptions = {}): Promise<Array<string>> {\n return this._context\n .managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n })\n .then((eventHubProperties) => {\n return eventHubProperties.partitionIds;\n });\n }\n\n /**\n * Provides information about the state of the specified partition.\n * @param partitionId - The id of the partition for which information is required.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the state of the partition .\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionProperties(\n partitionId: string,\n options: GetPartitionPropertiesOptions = {},\n ): Promise<PartitionProperties> {\n return this._context.managementSession!.getPartitionProperties(partitionId, {\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromOptions(options: SendBatchOptions = {}): {\n partitionKey?: string;\n partitionId?: string;\n} {\n const result: ReturnType<typeof extractPartitionAssignmentFromOptions> = {};\n const { partitionId, partitionKey } = options;\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromBatch(\n batch: EventDataBatch,\n options: SendBatchOptions,\n): { partitionKey?: string; partitionId?: string } {\n const result: ReturnType<typeof extractPartitionAssignmentFromBatch> = {};\n const partitionId = batch.partitionId;\n const partitionKey = batch.partitionKey;\n\n const { partitionId: unexpectedPartitionId, partitionKey: unexpectedPartitionKey } =\n extractPartitionAssignmentFromOptions(options);\n if (unexpectedPartitionKey && partitionKey !== unexpectedPartitionKey) {\n throw new Error(\n `The partitionKey (${unexpectedPartitionKey}) set on sendBatch does not match the partitionKey (${partitionKey}) set when creating the batch.`,\n );\n }\n if (unexpectedPartitionId && unexpectedPartitionId !== partitionId) {\n throw new Error(\n `The partitionId (${unexpectedPartitionId}) set on sendBatch does not match the partitionId (${partitionId}) set when creating the batch.`,\n );\n }\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n"]}
1
+ {"version":3,"file":"eventHubProducerClient.js","sourceRoot":"","sources":["../../src/eventHubProducerClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAqB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAUpF,OAAO,EAAkB,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAI3F,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,4BAA4B,EAC5B,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,iBAAiB,EAAgC,MAAM,gBAAgB,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,sBAAsB;IA4BjC;;;OAGG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;IACzC,CAAC;IAED;;;;OA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AY,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ConnectionContext, createConnectionContext } from \"./connectionContext.js\";\nimport {\n CreateBatchOptions,\n EventHubClientOptions,\n GetEventHubPropertiesOptions,\n GetPartitionIdsOptions,\n GetPartitionPropertiesOptions,\n SendBatchOptions,\n} from \"./models/public.js\";\nimport { PartitionPublishingOptions, PartitionPublishingProperties } from \"./models/private.js\";\nimport { EventDataBatch, EventDataBatchImpl, isEventDataBatch } from \"./eventDataBatch.js\";\nimport { EventHubProperties, PartitionProperties } from \"./managementClient.js\";\nimport { TracingContext, TracingSpanLink } from \"@azure/core-tracing\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport { isDefined } from \"@azure/core-util\";\nimport { isCredential } from \"./util/typeGuards.js\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport {\n idempotentAlreadyPublished,\n idempotentSomeAlreadyPublished,\n throwErrorIfConnectionClosed,\n throwTypeErrorIfParameterMissing,\n validateProducerPartitionSettings,\n} from \"./util/error.js\";\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { assertIsEventData, EventData, EventDataInternal } from \"./eventData.js\";\nimport { EventHubSender } from \"./eventHubSender.js\";\nimport { OperationOptions } from \"./util/operationOptions.js\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing.js\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { getRandomName } from \"./util/utils.js\";\n\n/**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n *\n * There are multiple ways to create an `EventHubProducerClient`\n * - Use the connection string from the SAS policy created for your Event Hub instance.\n * - Use the connection string from the SAS policy created for your Event Hub namespace,\n * and the name of the Event Hub instance\n * - Use the full namespace like `<yournamespace>.servicebus.windows.net`, and a credentials object.\n *\n * Optionally, you can also pass an options bag to configure the retry policy or proxy settings.\n *\n */\nexport class EventHubProducerClient {\n /**\n * Describes the amqp connection context for the client.\n */\n private _context: ConnectionContext;\n\n /**\n * The options passed by the user when creating the EventHubClient instance.\n */\n private _clientOptions: EventHubClientOptions;\n /**\n * Map of partitionId to senders\n */\n private _sendersMap: Map<string, EventHubSender>;\n /**\n * Indicates whether or not the EventHubProducerClient should enable idempotent publishing to Event Hub partitions.\n * If enabled, the producer will only be able to publish directly to partitions;\n * it will not be able to publish to the Event Hubs gateway for automatic partition routing\n * nor will it be able to use a partition key.\n * Default: false\n */\n private _enableIdempotentRetries?: boolean;\n /**\n * The set of options that can be specified to influence publishing behavior specific to the configured Event Hub partition.\n * These options are not necessary in the majority of scenarios and are intended for use with specialized scenarios,\n * such as when recovering the state used for idempotent publishing.\n */\n private _partitionOptions?: Record<string, PartitionPublishingOptions>;\n /**\n * @readonly\n * The name of the Event Hub instance for which this client is created.\n */\n get eventHubName(): string {\n return this._context.config.entityPath;\n }\n\n /**\n * @readonly\n * The fully qualified namespace of the Event Hub instance for which this client is created.\n * This is likely to be similar to <yournamespace>.servicebus.windows.net.\n */\n get fullyQualifiedNamespace(): string {\n return this._context.config.host;\n }\n\n /**\n * The name used to identify this EventHubProducerClient.\n * If not specified or empty, a random unique one will be generated.\n */\n public readonly identifier: string;\n\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, eventHubName: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n options?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n );\n constructor(\n fullyQualifiedNamespaceOrConnectionString1: string,\n eventHubNameOrOptions2?: string | EventHubClientOptions,\n credentialOrOptions3?:\n | TokenCredential\n | NamedKeyCredential\n | SASCredential\n | EventHubClientOptions,\n options4?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n ) {\n this._context = createConnectionContext(\n fullyQualifiedNamespaceOrConnectionString1,\n eventHubNameOrOptions2,\n credentialOrOptions3,\n options4,\n );\n if (typeof eventHubNameOrOptions2 !== \"string\") {\n this._clientOptions = eventHubNameOrOptions2 || {};\n } else if (!isCredential(credentialOrOptions3)) {\n this._clientOptions = credentialOrOptions3 || {};\n } else {\n this._clientOptions = options4 || {};\n }\n this.identifier = this._clientOptions.identifier ?? getRandomName();\n this._sendersMap = new Map();\n }\n\n /**\n * Creates an instance of `EventDataBatch` to which one can add events until the maximum supported size is reached.\n * The batch can be passed to the {@link sendBatch} method of the `EventHubProducerClient` to be sent to Azure Event Hubs.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n *\n * @param options - Configures the behavior of the batch.\n * - `partitionKey` : A value that is hashed and used by the Azure Event Hubs service to determine the partition to which\n * the events need to be sent.\n * - `partitionId` : Id of the partition to which the batch of events need to be sent.\n * - `maxSizeInBytes`: The upper limit for the size of batch. The `tryAdd` function will return `false` after this limit is reached.\n * - `abortSignal` : A signal the request to cancel the operation.\n * @returns Promise<EventDataBatch>\n * @throws Error if both `partitionId` and `partitionKey` are set in the options.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal in the options.\n */\n async createBatch(options: CreateBatchOptions = {}): Promise<EventDataBatch> {\n throwErrorIfConnectionClosed(this._context);\n\n const partitionId = isDefined(options.partitionId) ? String(options.partitionId) : undefined;\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey: options.partitionKey,\n });\n\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n let maxMessageSize = await sender.getMaxMessageSize({\n retryOptions: this._clientOptions.retryOptions,\n abortSignal: options.abortSignal,\n });\n\n if (options.maxSizeInBytes) {\n if (options.maxSizeInBytes > maxMessageSize) {\n const error = new Error(\n `Max message size (${options.maxSizeInBytes} bytes) is greater than maximum message size (${maxMessageSize} bytes) on the AMQP sender link.`,\n );\n logger.warning(`[${this._context.connectionId}] ${error.message}`);\n logErrorStackTrace(error);\n throw error;\n }\n maxMessageSize = options.maxSizeInBytes;\n }\n return new EventDataBatchImpl(\n this._context,\n maxMessageSize,\n Boolean(this._enableIdempotentRetries),\n options.partitionKey,\n partitionId,\n );\n }\n\n /**\n * Get the information about the state of publishing for a partition as observed by the `EventHubProducerClient`.\n * This data can always be read, but will only be populated with information relevant to the active features\n * for the producer client.\n *\n * @param partitionId - Id of the partition from which to retrieve publishing properties.\n * @param options - The set of options to apply to the operation call.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore this is called in EventHubBufferedProducerClient via cast-to-any workaround\n private async getPartitionPublishingProperties(\n partitionId: string,\n options: OperationOptions = {},\n ): Promise<PartitionPublishingProperties> {\n if (!isDefined(partitionId)) {\n throw new TypeError(\n `getPartitionPublishingProperties called without required argument \"partitionId\"`,\n );\n }\n\n if (typeof partitionId === \"number\") {\n partitionId = String(partitionId);\n }\n\n let sender = this._sendersMap.get(partitionId);\n if (!sender) {\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions: this._partitionOptions?.[partitionId],\n });\n this._sendersMap.set(partitionId, sender);\n }\n\n return sender.getPartitionPublishingProperties(options);\n }\n\n /**\n * Sends an array of events as a batch to the associated Event Hub.\n *\n * Azure Event Hubs has a limit on the size of the batch that can be sent which if exceeded\n * will result in an error with code `MessageTooLargeError`.\n * To safely send within batch size limits, use `EventHubProducerClient.createBatch()` or\n * `EventHubBufferedProducerClient` instead.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * await client.sendBatch(messages);\n * ```\n *\n * @param batch - An array of {@link EventData} or `AmqpAnnotatedMessage`.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * - `partitionId` : The partition this batch will be sent to. If set, `partitionKey` can not be set.\n * - `partitionKey` : A value that is hashed to produce a partition assignment. If set, `partitionId` can not be set.\n *\n * @returns Promise<void>\n * @throws MessageTooLargeError if all the events in the input array cannot be fit into a batch.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(\n batch: EventData[] | AmqpAnnotatedMessage[],\n options?: SendBatchOptions,\n ): Promise<void>;\n /**\n * Sends a batch of events created using `EventHubProducerClient.createBatch()` to the associated Event Hub.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n * @param batch - A batch of events that you can create using the {@link createBatch} method.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n *\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(batch: EventDataBatch, options?: OperationOptions): Promise<void>; // eslint-disable-line @azure/azure-sdk/ts-naming-options\n async sendBatch(\n batch: EventDataBatch | EventData[],\n options: SendBatchOptions | OperationOptions = {},\n ): Promise<void> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"sendBatch\", \"batch\", batch);\n\n let partitionId: string | undefined;\n let partitionKey: string | undefined;\n\n // Holds an EventData properties object containing tracing properties.\n // This lets us avoid cloning batch when it is EventData[], which is\n // important as the idempotent EventHubSender needs to decorate the\n // original EventData passed through.\n const eventDataTracingProperties: Array<EventData[\"properties\"]> = [];\n\n // link message span contexts\n let spanContextsToLink: TracingContext[] = [];\n\n if (isEventDataBatch(batch)) {\n if (\n this._enableIdempotentRetries &&\n isDefined((batch as EventDataBatchImpl).startingPublishedSequenceNumber)\n ) {\n throw new Error(idempotentAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromBatch(batch, options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n spanContextsToLink = (batch as EventDataBatchImpl)._messageSpanContexts;\n } else {\n if (!Array.isArray(batch)) {\n batch = [batch];\n }\n batch.forEach(assertIsEventData);\n if (batch.some((event) => isDefined((event as EventDataInternal)._publishedSequenceNumber))) {\n throw new Error(idempotentSomeAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromOptions(options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n\n for (let i = 0; i < batch.length; i++) {\n batch[i] = instrumentEventData(\n batch[i],\n options,\n this._context.config.entityPath,\n this._context.config.host,\n \"publish\",\n ).event;\n eventDataTracingProperties[i] = batch[i].properties;\n }\n }\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey,\n });\n\n return tracingClient.withSpan(\n `${EventHubProducerClient.name}.${this.sendBatch.name}`,\n options,\n (updatedOptions) => {\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n return sender.send(batch, {\n ...updatedOptions,\n partitionId,\n partitionKey,\n retryOptions: this._clientOptions.retryOptions,\n });\n },\n {\n spanLinks: spanContextsToLink.map<TracingSpanLink>((tracingContext) => {\n return { tracingContext };\n }),\n ...toSpanOptions(this._context.config, \"publish\", \"client\"),\n },\n );\n }\n\n /**\n * Closes the AMQP connection to the Event Hub instance,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns Promise<void>\n * @throws Error if the underlying connection encounters an error while closing.\n */\n async close(): Promise<void> {\n await this._context.close();\n\n for (const pair of this._sendersMap) {\n await pair[1].close();\n }\n this._sendersMap.clear();\n }\n\n /**\n * Provides the Event Hub runtime information.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the Event Hub instance.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getEventHubProperties(options: GetEventHubPropertiesOptions = {}): Promise<EventHubProperties> {\n return this._context.managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n\n /**\n * Provides the id for each partition associated with the Event Hub.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with an Array of strings representing the id for\n * each partition associated with the Event Hub.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionIds(options: GetPartitionIdsOptions = {}): Promise<Array<string>> {\n return this._context\n .managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n })\n .then((eventHubProperties) => {\n return eventHubProperties.partitionIds;\n });\n }\n\n /**\n * Provides information about the state of the specified partition.\n * @param partitionId - The id of the partition for which information is required.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the state of the partition .\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionProperties(\n partitionId: string,\n options: GetPartitionPropertiesOptions = {},\n ): Promise<PartitionProperties> {\n return this._context.managementSession!.getPartitionProperties(partitionId, {\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromOptions(options: SendBatchOptions = {}): {\n partitionKey?: string;\n partitionId?: string;\n} {\n const result: ReturnType<typeof extractPartitionAssignmentFromOptions> = {};\n const { partitionId, partitionKey } = options;\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromBatch(\n batch: EventDataBatch,\n options: SendBatchOptions,\n): { partitionKey?: string; partitionId?: string } {\n const result: ReturnType<typeof extractPartitionAssignmentFromBatch> = {};\n const partitionId = batch.partitionId;\n const partitionKey = batch.partitionKey;\n\n const { partitionId: unexpectedPartitionId, partitionKey: unexpectedPartitionKey } =\n extractPartitionAssignmentFromOptions(options);\n if (unexpectedPartitionKey && partitionKey !== unexpectedPartitionKey) {\n throw new Error(\n `The partitionKey (${unexpectedPartitionKey}) set on sendBatch does not match the partitionKey (${partitionKey}) set when creating the batch.`,\n );\n }\n if (unexpectedPartitionId && unexpectedPartitionId !== partitionId) {\n throw new Error(\n `The partitionId (${unexpectedPartitionId}) set on sendBatch does not match the partitionId (${partitionId}) set when creating the batch.`,\n );\n }\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n"]}
@@ -10,7 +10,7 @@ import { getRetryAttemptTimeoutInMs } from "./util/retries.js";
10
10
  import { createAbortablePromise } from "@azure/core-util";
11
11
  import { getRandomName } from "./util/utils.js";
12
12
  import { withAuth } from "./withAuth.js";
13
- import { receiverIdPropertyName } from "./util/constants.js";
13
+ import { geoReplication, receiverIdPropertyName } from "./util/constants.js";
14
14
  const abortLogMessage = "operation has been cancelled by the user";
15
15
  /** The time to wait in ms before attempting to read from the queue */
16
16
  const qReadIntervalInMs = 20;
@@ -304,7 +304,7 @@ function createRheaOptions(consumerId, name, address, obj, state, queue, eventPo
304
304
  if (typeof ownerLevel === "number") {
305
305
  rheaOptions.properties[Constants.attachEpoch] = types.wrap_long(ownerLevel);
306
306
  }
307
- rheaOptions.desired_capabilities = [Constants.geoReplication];
307
+ rheaOptions.desired_capabilities = [geoReplication];
308
308
  if (options.trackLastEnqueuedEventProperties) {
309
309
  rheaOptions.desired_capabilities.push(Constants.enableReceiverRuntimeMetricName);
310
310
  }
@@ -1 +1 @@
1
- {"version":3,"file":"partitionReceiver.js","sourceRoot":"","sources":["../../src/partitionReceiver.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAmB,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACL,SAAS,EAET,kBAAkB,EAClB,oBAAoB,EACpB,KAAK,EACL,SAAS,GAEV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAKL,KAAK,GACN,MAAM,cAAc,CAAC;AACtB,OAAO,EAAwC,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,EAAiB,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,MAAM,EACN,MAAM,IAAI,WAAW,EAErB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAQ7D,MAAM,eAAe,GAAG,0CAA0C,CAAC;AACnE,sEAAsE;AACtE,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAyD7B,gBAAgB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K,EACL,KAAK,EACL,aAAa,EACb,MAAM,EACN,OAAO,CACR,CAAC;IACF,MAAM,CAAC,OAAO,CAAC,qCAAqC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC3E,KAAK,CAAC,IAAI,GAAG,MAAM,GAAG,CAAC,UAAU,CAAC,cAAc,iCAC3C,WAAW,KACd,WAAW,IACX,CAAC;IACH,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC;IAC3B,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC1C,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AAC5B,CAAC;AAED,SAAS,UAAU,CAAC,QAA0B,EAAE,YAAoB;IAClE,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport {\n Constants,\n MessagingError,\n RetryOperationType,\n StandardAbortMessage,\n retry,\n translate,\n RetryConfig,\n} from \"@azure/core-amqp\";\nimport {\n EventContext,\n Receiver as Link,\n ReceiverOptions as RheaReceiverOptions,\n Source,\n types,\n} from \"rhea-promise\";\nimport { EventDataInternal, ReceivedEventData, fromRheaMessage } from \"./eventData.js\";\nimport { EventPosition, getEventPositionFilter } from \"./eventPosition.js\";\nimport {\n createSimpleLogger,\n logErrorStackTrace,\n logObj,\n logger as azureLogger,\n SimpleLogger,\n createReceiverLogPrefix,\n} from \"./logger.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { PartitionReceiverOptions } from \"./models/private.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport { createAbortablePromise } from \"@azure/core-util\";\nimport { TimerLoop } from \"./util/timerLoop.js\";\nimport { getRandomName } from \"./util/utils.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { receiverIdPropertyName } from \"./util/constants.js\";\n\ntype Writable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n/** @internal */\nexport type WritableReceiver = Writable<PartitionReceiver>;\n\nconst abortLogMessage = \"operation has been cancelled by the user\";\n/** The time to wait in ms before attempting to read from the queue */\nconst qReadIntervalInMs = 20;\n\n/**\n * A set of information about the last enqueued event of a partition, as observed by the consumer as\n * events are received from the Event Hubs service\n */\nexport interface LastEnqueuedEventProperties {\n /**\n * The sequence number of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n sequenceNumber?: number;\n /**\n * The date and time, in UTC, that the last event was enqueued into the Event Hub partition from\n * which this event was received.\n */\n enqueuedOn?: Date;\n /**\n * The offset of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n offset?: string;\n /**\n * The date and time, in UTC, that the last event was retrieved from the Event Hub partition.\n */\n retrievedOn?: Date;\n}\n\n/** @internal */\nexport interface PartitionReceiver {\n readonly checkpoint: number;\n readonly lastEnqueuedEventProperties: LastEnqueuedEventProperties;\n readonly isClosed: boolean;\n readonly close: () => Promise<void>;\n readonly abort: () => Promise<void>;\n readonly isOpen: () => boolean;\n readonly receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds?: number,\n abortSignal?: AbortSignalLike,\n ) => Promise<ReceivedEventData[]>;\n /** Needed for tests only */\n readonly _onError?: (error: MessagingError | Error) => void;\n readonly connect: (options: ConnectOptions) => Promise<void>;\n}\n\ninterface ConnectOptions {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n}\n\ninterface ReceiverState {\n link?: Link;\n authLoop?: TimerLoop;\n isConnecting: boolean;\n}\n\n/** @internal */\nexport function createReceiver(\n ctx: ConnectionContext,\n consumerGroup: string,\n consumerId: string,\n partitionId: string,\n eventPosition: EventPosition,\n options: PartitionReceiverOptions = {},\n): PartitionReceiver {\n const address = ctx.config.getReceiverAddress(partitionId, consumerGroup);\n const name = getRandomName(address);\n const audience = ctx.config.getReceiverAudience(partitionId, consumerGroup);\n const logPrefix = createReceiverLogPrefix(consumerId, ctx.connectionId, partitionId);\n const logger = createSimpleLogger(azureLogger, logPrefix);\n const queue: ReceivedEventData[] = [];\n const state: ReceiverState = {\n isConnecting: false,\n };\n\n const obj: WritableReceiver = {\n _onError: undefined,\n checkpoint: -1,\n lastEnqueuedEventProperties: {},\n isClosed: false,\n close: async () => {\n clearHandlers(obj);\n delete ctx.receivers[name];\n logger.verbose(\"deleted the receiver from the client cache\");\n state.authLoop?.stop();\n return state.link\n ?.close()\n .catch((err) => {\n logger.warning(`an error occurred while closing: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n throw err;\n })\n .finally(() => {\n obj.isClosed = true;\n logger.verbose(\"is closed\");\n state.link = undefined;\n state.authLoop = undefined;\n });\n },\n abort: () => {\n obj._onError?.(new AbortError(StandardAbortMessage));\n logger.info(abortLogMessage);\n return obj.close();\n },\n isOpen: () => {\n const isOpen = !!state.link?.isOpen();\n logger.verbose(`is open? -> ${isOpen}`);\n return isOpen;\n },\n async connect({ abortSignal, timeoutInMs }: ConnectOptions): Promise<void> {\n if (state.isConnecting || obj.isOpen()) {\n return;\n }\n state.isConnecting = true;\n logger.verbose(\"is trying to connect\");\n try {\n await ctx.readyToOpenLink({ abortSignal });\n state.authLoop = await withAuth(\n () =>\n setupLink(\n consumerId,\n ctx,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n abortSignal,\n ),\n ctx,\n audience,\n timeoutInMs,\n logger,\n {\n abortSignal,\n },\n );\n } catch (err) {\n state.isConnecting = false;\n const error = translate(err);\n logger.error(\n `an error occurred while creating the receiver: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(err);\n throw error;\n }\n },\n receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds: number = 60,\n abortSignal?: AbortSignalLike,\n ) => {\n const prefetchCount = options.prefetchCount ?? maxMessageCount * 3;\n const cleanupBeforeAbort = (): Promise<void> => {\n logger.info(abortLogMessage);\n return obj.close();\n };\n const retrieveEvents = (): Promise<ReceivedEventData[]> => {\n const eventsToRetrieveCount = Math.max(maxMessageCount - queue.length, 0);\n logger.verbose(\n `already has ${queue.length} events and wants to receive ${eventsToRetrieveCount} more events`,\n );\n if (abortSignal?.aborted) {\n cleanupBeforeAbort();\n return Promise.reject(new AbortError(StandardAbortMessage));\n }\n return obj.isClosed || ctx.wasConnectionCloseCalled || eventsToRetrieveCount === 0\n ? Promise.resolve(queue.splice(0, maxMessageCount))\n : new Promise<void>((resolve, reject) => {\n obj._onError = reject;\n obj // eslint-disable-line promise/catch-or-return\n .connect({\n abortSignal,\n timeoutInMs: getRetryAttemptTimeoutInMs(options.retryOptions),\n })\n .then(() => {\n addCredits(state.link, Math.max(prefetchCount, maxMessageCount) - queue.length);\n logger.verbose(`setting the max wait time to ${maxWaitTimeInSeconds} seconds`);\n return waitForEvents(\n maxMessageCount,\n maxWaitTimeInSeconds * 1000,\n qReadIntervalInMs,\n queue,\n {\n abortSignal,\n cleanupBeforeAbort,\n receivedAfterWait: () =>\n logger.info(\n `${Math.min(\n maxMessageCount,\n queue.length,\n )} messages received within ${maxWaitTimeInSeconds} seconds`,\n ),\n receivedAlready: () =>\n logger.info(`${maxMessageCount} messages already received`),\n receivedNone: () =>\n logger.info(\n `no messages received when max wait time in seconds ${maxWaitTimeInSeconds} is over`,\n ),\n },\n );\n })\n .catch(reject)\n .then(resolve);\n })\n .then(() => queue.splice(0, maxMessageCount))\n .finally(() => clearHandlers(obj));\n };\n return retry(\n Object.defineProperties(\n {\n operation: retrieveEvents,\n operationType: RetryOperationType.receiveMessage,\n abortSignal: abortSignal,\n retryOptions: options.retryOptions ?? {},\n },\n {\n connectionId: {\n enumerable: true,\n get: () => ctx.connectionId,\n },\n connectionHost: {\n enumerable: true,\n get: () => ctx.config.host,\n },\n },\n ) as RetryConfig<ReceivedEventData[]>,\n );\n },\n };\n return obj;\n}\n\nfunction delay(\n waitTimeInMs: number,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setTimeout>;\n return createAbortablePromise<void>((resolve) => {\n token = setTimeout(resolve, waitTimeInMs);\n }, options).finally(() => clearTimeout(token));\n}\n\n/**\n * @internal\n */\nexport function checkOnInterval(\n waitTimeInMs: number,\n check: () => boolean,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setInterval>;\n return createAbortablePromise<void>((resolve) => {\n token = setInterval(() => {\n if (check()) {\n resolve();\n }\n }, waitTimeInMs);\n }, options).finally(() => clearInterval(token));\n}\n\n/**\n * Returns a promise that will resolve when it is time to read from the queue\n * @param maxEventCount - The maximum number of events to receive.\n * @param maxWaitTimeInMs - The maximum time to wait in ms for the queue to contain any events.\n * @param readIntervalWaitTimeInMs - The time interval to wait in ms before checking the queue.\n * @param queue - The queue to read from.\n * @param options - The options bag.\n * @returns a promise that will resolve when it is time to read from the queue\n * @internal\n */\nexport function waitForEvents(\n maxEventCount: number,\n maxWaitTimeInMs: number,\n readIntervalWaitTimeInMs: number,\n queue: unknown[],\n options: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n receivedAfterWait?: () => void;\n receivedAlready?: () => void;\n receivedNone?: () => void;\n } = {},\n): Promise<void> {\n const {\n abortSignal: clientAbortSignal,\n cleanupBeforeAbort,\n receivedNone,\n receivedAfterWait,\n receivedAlready,\n } = options;\n\n if (queue.length >= maxEventCount) {\n return Promise.resolve().then(receivedAlready);\n }\n\n const aborter = new AbortController();\n const abortListener = () => {\n aborter.abort();\n };\n clientAbortSignal?.addEventListener(\"abort\", abortListener);\n let cleanupBeforeAbortCalled = false;\n\n const updatedOptions = {\n abortSignal: aborter.signal,\n abortErrorMsg: StandardAbortMessage,\n cleanupBeforeAbort: () => {\n if (clientAbortSignal?.aborted && !cleanupBeforeAbortCalled) {\n cleanupBeforeAbort?.();\n cleanupBeforeAbortCalled = true;\n }\n },\n };\n return Promise.race([\n checkOnInterval(readIntervalWaitTimeInMs, () => queue.length > 0, updatedOptions)\n .then(() => delay(readIntervalWaitTimeInMs, updatedOptions))\n .then(receivedAfterWait),\n delay(maxWaitTimeInMs, updatedOptions).then(receivedNone),\n ]).finally(() => {\n aborter.abort();\n clientAbortSignal?.removeEventListener(\"abort\", abortListener);\n });\n}\n\nfunction convertAMQPMesage(data: EventDataInternal): ReceivedEventData {\n const rawMessage = data.getRawAmqpMessage();\n const receivedEventData: ReceivedEventData = {\n body: data.body,\n properties: data.properties,\n offset: data.offset!,\n sequenceNumber: data.sequenceNumber!,\n enqueuedTimeUtc: data.enqueuedTimeUtc!,\n partitionKey: data.partitionKey!,\n systemProperties: data.systemProperties,\n getRawAmqpMessage() {\n return rawMessage;\n },\n };\n if (data.correlationId != null) {\n receivedEventData.correlationId = data.correlationId;\n }\n if (data.contentType != null) {\n receivedEventData.contentType = data.contentType;\n }\n if (data.messageId != null) {\n receivedEventData.messageId = data.messageId;\n }\n return receivedEventData;\n}\n\nfunction setEventProps(eventProps: LastEnqueuedEventProperties, data: EventDataInternal): void {\n eventProps.sequenceNumber = data.lastSequenceNumber;\n eventProps.enqueuedOn = data.lastEnqueuedTime;\n eventProps.offset = data.lastEnqueuedOffset;\n eventProps.retrievedOn = data.retrievalTime;\n}\n\nfunction clearHandlers(obj: WritableReceiver): void {\n obj._onError = undefined;\n}\n\nfunction onMessage(\n context: EventContext,\n obj: WritableReceiver,\n queue: ReceivedEventData[],\n options: PartitionReceiverOptions,\n): void {\n if (!context.message) {\n return;\n }\n const data = fromRheaMessage(context.message, !!options.skipParsingBodyAsJson);\n const receivedEventData = convertAMQPMesage(data);\n obj.checkpoint = receivedEventData.sequenceNumber;\n if (options.trackLastEnqueuedEventProperties) {\n setEventProps(obj.lastEnqueuedEventProperties, data);\n }\n queue.push(receivedEventData);\n}\n\nfunction onError(\n context: EventContext,\n obj: PartitionReceiver,\n receiver: Link | undefined,\n logger: SimpleLogger,\n): void {\n const rheaReceiver = receiver || context.receiver;\n const amqpError = rheaReceiver?.error;\n logger.verbose(`'receiver_error' event occurred: ${logObj(amqpError)}`);\n if (obj._onError && amqpError) {\n const error = translate(amqpError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nfunction onSessionError(context: EventContext, obj: PartitionReceiver, logger: SimpleLogger): void {\n const sessionError = context.session?.error;\n logger.verbose(`'session_error' event occurred: ${logObj(sessionError)}`);\n if (obj._onError && sessionError) {\n const error = translate(sessionError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nasync function onClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'receiver_close' event occurred. Value for isItselfClosed on the receiver is: '${rheaReceiver\n ?.isItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'receiver_close' event: ${logObj(err)}`);\n });\n }\n}\n\nasync function onSessionClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'session_close' event occurred. Value for isSessionItselfClosed on the session is: '${rheaReceiver\n ?.isSessionItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'session_close' event: ${logObj(err)}`);\n });\n }\n}\n\nfunction createRheaOptions(\n consumerId: string,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n): RheaReceiverOptions {\n const rheaOptions: RheaReceiverOptions & { source: Source; properties: Record<string, any> } = {\n name,\n autoaccept: true,\n target: consumerId,\n source: {\n address,\n },\n credit_window: 0,\n properties: {\n [receiverIdPropertyName]: consumerId,\n },\n onClose: (context) => onClose(context, state, logger),\n onSessionClose: (context) => onSessionClose(context, state, logger),\n onError: (context) => onError(context, obj, state.link, logger),\n onMessage: (context) => onMessage(context, obj, queue, options),\n onSessionError: (context) => onSessionError(context, obj, logger),\n };\n const ownerLevel = options.ownerLevel;\n if (typeof ownerLevel === \"number\") {\n rheaOptions.properties[Constants.attachEpoch] = types.wrap_long(ownerLevel);\n }\n rheaOptions.desired_capabilities = [Constants.geoReplication];\n if (options.trackLastEnqueuedEventProperties) {\n rheaOptions.desired_capabilities.push(Constants.enableReceiverRuntimeMetricName);\n }\n const filterClause = getEventPositionFilter(\n obj.checkpoint > -1 ? { sequenceNumber: obj.checkpoint } : eventPosition,\n );\n rheaOptions.source.filter = {\n \"apache.org:selector-filter:string\": types.wrap_described(filterClause, 0x468c00000004),\n };\n return rheaOptions;\n}\n\nasync function setupLink(\n consumerId: string,\n ctx: ConnectionContext,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n abortSignal?: AbortSignalLike,\n): Promise<void> {\n const rheaOptions = createRheaOptions(\n consumerId,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n );\n logger.verbose(`trying to be created with options ${logObj(rheaOptions)}`);\n state.link = await ctx.connection.createReceiver({\n ...rheaOptions,\n abortSignal,\n });\n state.isConnecting = false;\n logger.verbose(\"is created successfully\");\n ctx.receivers[name] = obj;\n}\n\nfunction addCredits(receiver: Link | undefined, creditsToAdd: number): void {\n if (creditsToAdd > 0) {\n receiver?.addCredit(creditsToAdd);\n }\n}\n"]}
1
+ {"version":3,"file":"partitionReceiver.js","sourceRoot":"","sources":["../../src/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G,CAAC;AAC5B,CAAC;AAED,SAAS,UAAU,CAAC,QAA0B,EAAE,YAAoB;IAClE,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport {\n Constants,\n MessagingError,\n RetryOperationType,\n StandardAbortMessage,\n retry,\n translate,\n RetryConfig,\n} from \"@azure/core-amqp\";\nimport {\n EventContext,\n Receiver as Link,\n ReceiverOptions as RheaReceiverOptions,\n Source,\n types,\n} from \"rhea-promise\";\nimport { EventDataInternal, ReceivedEventData, fromRheaMessage } from \"./eventData.js\";\nimport { EventPosition, getEventPositionFilter } from \"./eventPosition.js\";\nimport {\n createSimpleLogger,\n logErrorStackTrace,\n logObj,\n logger as azureLogger,\n SimpleLogger,\n createReceiverLogPrefix,\n} from \"./logger.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { PartitionReceiverOptions } from \"./models/private.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport { createAbortablePromise } from \"@azure/core-util\";\nimport { TimerLoop } from \"./util/timerLoop.js\";\nimport { getRandomName } from \"./util/utils.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { geoReplication, receiverIdPropertyName } from \"./util/constants.js\";\n\ntype Writable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n/** @internal */\nexport type WritableReceiver = Writable<PartitionReceiver>;\n\nconst abortLogMessage = \"operation has been cancelled by the user\";\n/** The time to wait in ms before attempting to read from the queue */\nconst qReadIntervalInMs = 20;\n\n/**\n * A set of information about the last enqueued event of a partition, as observed by the consumer as\n * events are received from the Event Hubs service\n */\nexport interface LastEnqueuedEventProperties {\n /**\n * The sequence number of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n sequenceNumber?: number;\n /**\n * The date and time, in UTC, that the last event was enqueued into the Event Hub partition from\n * which this event was received.\n */\n enqueuedOn?: Date;\n /**\n * The offset of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n offset?: string;\n /**\n * The date and time, in UTC, that the last event was retrieved from the Event Hub partition.\n */\n retrievedOn?: Date;\n}\n\n/** @internal */\nexport interface PartitionReceiver {\n readonly checkpoint: number;\n readonly lastEnqueuedEventProperties: LastEnqueuedEventProperties;\n readonly isClosed: boolean;\n readonly close: () => Promise<void>;\n readonly abort: () => Promise<void>;\n readonly isOpen: () => boolean;\n readonly receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds?: number,\n abortSignal?: AbortSignalLike,\n ) => Promise<ReceivedEventData[]>;\n /** Needed for tests only */\n readonly _onError?: (error: MessagingError | Error) => void;\n readonly connect: (options: ConnectOptions) => Promise<void>;\n}\n\ninterface ConnectOptions {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n}\n\ninterface ReceiverState {\n link?: Link;\n authLoop?: TimerLoop;\n isConnecting: boolean;\n}\n\n/** @internal */\nexport function createReceiver(\n ctx: ConnectionContext,\n consumerGroup: string,\n consumerId: string,\n partitionId: string,\n eventPosition: EventPosition,\n options: PartitionReceiverOptions = {},\n): PartitionReceiver {\n const address = ctx.config.getReceiverAddress(partitionId, consumerGroup);\n const name = getRandomName(address);\n const audience = ctx.config.getReceiverAudience(partitionId, consumerGroup);\n const logPrefix = createReceiverLogPrefix(consumerId, ctx.connectionId, partitionId);\n const logger = createSimpleLogger(azureLogger, logPrefix);\n const queue: ReceivedEventData[] = [];\n const state: ReceiverState = {\n isConnecting: false,\n };\n\n const obj: WritableReceiver = {\n _onError: undefined,\n checkpoint: -1,\n lastEnqueuedEventProperties: {},\n isClosed: false,\n close: async () => {\n clearHandlers(obj);\n delete ctx.receivers[name];\n logger.verbose(\"deleted the receiver from the client cache\");\n state.authLoop?.stop();\n return state.link\n ?.close()\n .catch((err) => {\n logger.warning(`an error occurred while closing: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n throw err;\n })\n .finally(() => {\n obj.isClosed = true;\n logger.verbose(\"is closed\");\n state.link = undefined;\n state.authLoop = undefined;\n });\n },\n abort: () => {\n obj._onError?.(new AbortError(StandardAbortMessage));\n logger.info(abortLogMessage);\n return obj.close();\n },\n isOpen: () => {\n const isOpen = !!state.link?.isOpen();\n logger.verbose(`is open? -> ${isOpen}`);\n return isOpen;\n },\n async connect({ abortSignal, timeoutInMs }: ConnectOptions): Promise<void> {\n if (state.isConnecting || obj.isOpen()) {\n return;\n }\n state.isConnecting = true;\n logger.verbose(\"is trying to connect\");\n try {\n await ctx.readyToOpenLink({ abortSignal });\n state.authLoop = await withAuth(\n () =>\n setupLink(\n consumerId,\n ctx,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n abortSignal,\n ),\n ctx,\n audience,\n timeoutInMs,\n logger,\n {\n abortSignal,\n },\n );\n } catch (err) {\n state.isConnecting = false;\n const error = translate(err);\n logger.error(\n `an error occurred while creating the receiver: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(err);\n throw error;\n }\n },\n receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds: number = 60,\n abortSignal?: AbortSignalLike,\n ) => {\n const prefetchCount = options.prefetchCount ?? maxMessageCount * 3;\n const cleanupBeforeAbort = (): Promise<void> => {\n logger.info(abortLogMessage);\n return obj.close();\n };\n const retrieveEvents = (): Promise<ReceivedEventData[]> => {\n const eventsToRetrieveCount = Math.max(maxMessageCount - queue.length, 0);\n logger.verbose(\n `already has ${queue.length} events and wants to receive ${eventsToRetrieveCount} more events`,\n );\n if (abortSignal?.aborted) {\n cleanupBeforeAbort();\n return Promise.reject(new AbortError(StandardAbortMessage));\n }\n return obj.isClosed || ctx.wasConnectionCloseCalled || eventsToRetrieveCount === 0\n ? Promise.resolve(queue.splice(0, maxMessageCount))\n : new Promise<void>((resolve, reject) => {\n obj._onError = reject;\n obj // eslint-disable-line promise/catch-or-return\n .connect({\n abortSignal,\n timeoutInMs: getRetryAttemptTimeoutInMs(options.retryOptions),\n })\n .then(() => {\n addCredits(state.link, Math.max(prefetchCount, maxMessageCount) - queue.length);\n logger.verbose(`setting the max wait time to ${maxWaitTimeInSeconds} seconds`);\n return waitForEvents(\n maxMessageCount,\n maxWaitTimeInSeconds * 1000,\n qReadIntervalInMs,\n queue,\n {\n abortSignal,\n cleanupBeforeAbort,\n receivedAfterWait: () =>\n logger.info(\n `${Math.min(\n maxMessageCount,\n queue.length,\n )} messages received within ${maxWaitTimeInSeconds} seconds`,\n ),\n receivedAlready: () =>\n logger.info(`${maxMessageCount} messages already received`),\n receivedNone: () =>\n logger.info(\n `no messages received when max wait time in seconds ${maxWaitTimeInSeconds} is over`,\n ),\n },\n );\n })\n .catch(reject)\n .then(resolve);\n })\n .then(() => queue.splice(0, maxMessageCount))\n .finally(() => clearHandlers(obj));\n };\n return retry(\n Object.defineProperties(\n {\n operation: retrieveEvents,\n operationType: RetryOperationType.receiveMessage,\n abortSignal: abortSignal,\n retryOptions: options.retryOptions ?? {},\n },\n {\n connectionId: {\n enumerable: true,\n get: () => ctx.connectionId,\n },\n connectionHost: {\n enumerable: true,\n get: () => ctx.config.host,\n },\n },\n ) as RetryConfig<ReceivedEventData[]>,\n );\n },\n };\n return obj;\n}\n\nfunction delay(\n waitTimeInMs: number,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setTimeout>;\n return createAbortablePromise<void>((resolve) => {\n token = setTimeout(resolve, waitTimeInMs);\n }, options).finally(() => clearTimeout(token));\n}\n\n/**\n * @internal\n */\nexport function checkOnInterval(\n waitTimeInMs: number,\n check: () => boolean,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setInterval>;\n return createAbortablePromise<void>((resolve) => {\n token = setInterval(() => {\n if (check()) {\n resolve();\n }\n }, waitTimeInMs);\n }, options).finally(() => clearInterval(token));\n}\n\n/**\n * Returns a promise that will resolve when it is time to read from the queue\n * @param maxEventCount - The maximum number of events to receive.\n * @param maxWaitTimeInMs - The maximum time to wait in ms for the queue to contain any events.\n * @param readIntervalWaitTimeInMs - The time interval to wait in ms before checking the queue.\n * @param queue - The queue to read from.\n * @param options - The options bag.\n * @returns a promise that will resolve when it is time to read from the queue\n * @internal\n */\nexport function waitForEvents(\n maxEventCount: number,\n maxWaitTimeInMs: number,\n readIntervalWaitTimeInMs: number,\n queue: unknown[],\n options: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n receivedAfterWait?: () => void;\n receivedAlready?: () => void;\n receivedNone?: () => void;\n } = {},\n): Promise<void> {\n const {\n abortSignal: clientAbortSignal,\n cleanupBeforeAbort,\n receivedNone,\n receivedAfterWait,\n receivedAlready,\n } = options;\n\n if (queue.length >= maxEventCount) {\n return Promise.resolve().then(receivedAlready);\n }\n\n const aborter = new AbortController();\n const abortListener = () => {\n aborter.abort();\n };\n clientAbortSignal?.addEventListener(\"abort\", abortListener);\n let cleanupBeforeAbortCalled = false;\n\n const updatedOptions = {\n abortSignal: aborter.signal,\n abortErrorMsg: StandardAbortMessage,\n cleanupBeforeAbort: () => {\n if (clientAbortSignal?.aborted && !cleanupBeforeAbortCalled) {\n cleanupBeforeAbort?.();\n cleanupBeforeAbortCalled = true;\n }\n },\n };\n return Promise.race([\n checkOnInterval(readIntervalWaitTimeInMs, () => queue.length > 0, updatedOptions)\n .then(() => delay(readIntervalWaitTimeInMs, updatedOptions))\n .then(receivedAfterWait),\n delay(maxWaitTimeInMs, updatedOptions).then(receivedNone),\n ]).finally(() => {\n aborter.abort();\n clientAbortSignal?.removeEventListener(\"abort\", abortListener);\n });\n}\n\nfunction convertAMQPMesage(data: EventDataInternal): ReceivedEventData {\n const rawMessage = data.getRawAmqpMessage();\n const receivedEventData: ReceivedEventData = {\n body: data.body,\n properties: data.properties,\n offset: data.offset!,\n sequenceNumber: data.sequenceNumber!,\n enqueuedTimeUtc: data.enqueuedTimeUtc!,\n partitionKey: data.partitionKey!,\n systemProperties: data.systemProperties,\n getRawAmqpMessage() {\n return rawMessage;\n },\n };\n if (data.correlationId != null) {\n receivedEventData.correlationId = data.correlationId;\n }\n if (data.contentType != null) {\n receivedEventData.contentType = data.contentType;\n }\n if (data.messageId != null) {\n receivedEventData.messageId = data.messageId;\n }\n return receivedEventData;\n}\n\nfunction setEventProps(eventProps: LastEnqueuedEventProperties, data: EventDataInternal): void {\n eventProps.sequenceNumber = data.lastSequenceNumber;\n eventProps.enqueuedOn = data.lastEnqueuedTime;\n eventProps.offset = data.lastEnqueuedOffset;\n eventProps.retrievedOn = data.retrievalTime;\n}\n\nfunction clearHandlers(obj: WritableReceiver): void {\n obj._onError = undefined;\n}\n\nfunction onMessage(\n context: EventContext,\n obj: WritableReceiver,\n queue: ReceivedEventData[],\n options: PartitionReceiverOptions,\n): void {\n if (!context.message) {\n return;\n }\n const data = fromRheaMessage(context.message, !!options.skipParsingBodyAsJson);\n const receivedEventData = convertAMQPMesage(data);\n obj.checkpoint = receivedEventData.sequenceNumber;\n if (options.trackLastEnqueuedEventProperties) {\n setEventProps(obj.lastEnqueuedEventProperties, data);\n }\n queue.push(receivedEventData);\n}\n\nfunction onError(\n context: EventContext,\n obj: PartitionReceiver,\n receiver: Link | undefined,\n logger: SimpleLogger,\n): void {\n const rheaReceiver = receiver || context.receiver;\n const amqpError = rheaReceiver?.error;\n logger.verbose(`'receiver_error' event occurred: ${logObj(amqpError)}`);\n if (obj._onError && amqpError) {\n const error = translate(amqpError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nfunction onSessionError(context: EventContext, obj: PartitionReceiver, logger: SimpleLogger): void {\n const sessionError = context.session?.error;\n logger.verbose(`'session_error' event occurred: ${logObj(sessionError)}`);\n if (obj._onError && sessionError) {\n const error = translate(sessionError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nasync function onClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'receiver_close' event occurred. Value for isItselfClosed on the receiver is: '${rheaReceiver\n ?.isItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'receiver_close' event: ${logObj(err)}`);\n });\n }\n}\n\nasync function onSessionClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'session_close' event occurred. Value for isSessionItselfClosed on the session is: '${rheaReceiver\n ?.isSessionItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'session_close' event: ${logObj(err)}`);\n });\n }\n}\n\nfunction createRheaOptions(\n consumerId: string,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n): RheaReceiverOptions {\n const rheaOptions: RheaReceiverOptions & { source: Source; properties: Record<string, any> } = {\n name,\n autoaccept: true,\n target: consumerId,\n source: {\n address,\n },\n credit_window: 0,\n properties: {\n [receiverIdPropertyName]: consumerId,\n },\n onClose: (context) => onClose(context, state, logger),\n onSessionClose: (context) => onSessionClose(context, state, logger),\n onError: (context) => onError(context, obj, state.link, logger),\n onMessage: (context) => onMessage(context, obj, queue, options),\n onSessionError: (context) => onSessionError(context, obj, logger),\n };\n const ownerLevel = options.ownerLevel;\n if (typeof ownerLevel === \"number\") {\n rheaOptions.properties[Constants.attachEpoch] = types.wrap_long(ownerLevel);\n }\n rheaOptions.desired_capabilities = [geoReplication];\n if (options.trackLastEnqueuedEventProperties) {\n rheaOptions.desired_capabilities.push(Constants.enableReceiverRuntimeMetricName);\n }\n const filterClause = getEventPositionFilter(\n obj.checkpoint > -1 ? { sequenceNumber: obj.checkpoint } : eventPosition,\n );\n rheaOptions.source.filter = {\n \"apache.org:selector-filter:string\": types.wrap_described(filterClause, 0x468c00000004),\n };\n return rheaOptions;\n}\n\nasync function setupLink(\n consumerId: string,\n ctx: ConnectionContext,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n abortSignal?: AbortSignalLike,\n): Promise<void> {\n const rheaOptions = createRheaOptions(\n consumerId,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n );\n logger.verbose(`trying to be created with options ${logObj(rheaOptions)}`);\n state.link = await ctx.connection.createReceiver({\n ...rheaOptions,\n abortSignal,\n });\n state.isConnecting = false;\n logger.verbose(\"is created successfully\");\n ctx.receivers[name] = obj;\n}\n\nfunction addCredits(receiver: Link | undefined, creditsToAdd: number): void {\n if (creditsToAdd > 0) {\n receiver?.addCredit(creditsToAdd);\n }\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  */
6
6
  export const packageJsonInfo = {
7
7
  name: "@azure/event-hubs",
8
- version: "5.13.0-beta.3",
8
+ version: "5.13.0",
9
9
  };
10
10
  /**
11
11
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/util/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,eAAe;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AAChB,MAAM,CAAC,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AAChB,MAAM,CAAC,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,MAAM,CAAC,GAAG,CACtD,gDAAgD,CACjD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @internal\n */\nexport const packageJsonInfo = {\n name: \"@azure/event-hubs\",\n version: \"5.13.0-beta.3\",\n};\n\n/**\n * @internal\n */\nexport const idempotentProducerAmqpPropertyNames = {\n capability: \"com.microsoft:idempotent-producer\",\n epoch: \"com.microsoft:producer-epoch\",\n producerId: \"com.microsoft:producer-id\",\n producerSequenceNumber: \"com.microsoft:producer-sequence-number\",\n} as const;\n\n/** @internal */\nexport const receiverIdPropertyName = \"com.microsoft:receiver-name\";\n\n/** @internal */\nexport const geoReplication = \"com.microsoft:georeplication\";\n\n/**\n * @internal\n */\nexport const PENDING_PUBLISH_SEQ_NUM_SYMBOL = Symbol.for(\n \"@azure/event-hubs.pendingPublishSequenceNumber\",\n);\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/util/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,QAAQ;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AAChB,MAAM,CAAC,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AAChB,MAAM,CAAC,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,MAAM,CAAC,GAAG,CACtD,gDAAgD,CACjD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @internal\n */\nexport const packageJsonInfo = {\n name: \"@azure/event-hubs\",\n version: \"5.13.0\",\n};\n\n/**\n * @internal\n */\nexport const idempotentProducerAmqpPropertyNames = {\n capability: \"com.microsoft:idempotent-producer\",\n epoch: \"com.microsoft:producer-epoch\",\n producerId: \"com.microsoft:producer-id\",\n producerSequenceNumber: \"com.microsoft:producer-sequence-number\",\n} as const;\n\n/** @internal */\nexport const receiverIdPropertyName = \"com.microsoft:receiver-name\";\n\n/** @internal */\nexport const geoReplication = \"com.microsoft:georeplication\";\n\n/**\n * @internal\n */\nexport const PENDING_PUBLISH_SEQ_NUM_SYMBOL = Symbol.for(\n \"@azure/event-hubs.pendingPublishSequenceNumber\",\n);\n"]}
@@ -1638,7 +1638,7 @@ export declare type ProcessInitializeHandler = (context: PartitionContext) => Pr
1638
1638
  /**
1639
1639
  * The interface that describes the structure of the event received from Event Hub.
1640
1640
  * Use this as a reference when creating the `processEvents` function to process the events
1641
- * recieved from an Event Hub when using the `EventHubConsumerClient`.
1641
+ * received from an Event Hub when using the `EventHubConsumerClient`.
1642
1642
  */
1643
1643
  export declare interface ReceivedEventData {
1644
1644
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@azure/event-hubs",
3
3
  "sdk-type": "client",
4
- "version": "5.13.0-alpha.20241008.6",
4
+ "version": "5.13.0-alpha.20241015.1",
5
5
  "description": "Azure Event Hubs SDK for JS.",
6
6
  "author": "Microsoft Corporation",
7
7
  "license": "MIT",
@@ -103,7 +103,7 @@
103
103
  },
104
104
  "dependencies": {
105
105
  "@azure/abort-controller": "^2.1.2",
106
- "@azure/core-amqp": "4.4.0-beta.1",
106
+ "@azure/core-amqp": "^4.3.2",
107
107
  "@azure/core-auth": "^1.3.0",
108
108
  "@azure/core-tracing": "^1.1.2",
109
109
  "@azure/core-util": "^1.9.1",