@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 +1 @@
1
- {"version":3,"file":"eventHubProducerClient.js","sourceRoot":"","sources":["../../src/eventHubProducerClient.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,iEAAoF;AAUpF,2DAA2F;AAI3F,gDAA6C;AAC7C,wDAAoD;AACpD,2CAAyD;AACzD,8CAMyB;AAGzB,2DAAqD;AAErD,yDAAwE;AACxE,iFAA2E;AAC3E,8CAAgD;AAEhD;;;;;;;;;;;GAWG;AACH,MAAa,sBAAsB;IA4BjC;;;OAGG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;IACzC,CAAC;IAED;;;;OAIG;IACH,IAAI,uBAAuB;QACzB,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;IACnC,CAAC;IA6DD,YACE,0CAAkD,EAClD,sBAAuD,EACvD,oBAIyB,EACzB,QAAgC;;QAEhC,IAAI,CAAC,QAAQ,GAAG,IAAA,8CAAuB,EACrC,0CAA0C,EAC1C,sBAAsB,EACtB,oBAAoB,EACpB,QAAQ,CACT,CAAC;QACF,IAAI,OAAO,sBAAsB,KAAK,QAAQ,EAAE,CAAC;YAC/C,IAAI,CAAC,cAAc,GAAG,sBAAsB,IAAI,EAAE,CAAC;QACrD,CAAC;aAAM,IAAI,CAAC,IAAA,4BAAY,EAAC,oBAAoB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CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,SAAS,mCAAmC,CAC1C,KAAqB,EACrB,OAAyB;IAEzB,MAAM,MAAM,GAA2D,EAAE,CAAC;IAC1E,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;IACtC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAExC,MAAM,EAAE,WAAW,EAAE,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,IAAA,qBAAS,EAAC,WAAW,CAAC,EAAE,CAAC;QAC3B,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,IAAA,qBAAS,EAAC,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,iEAAoF;AAUpF,2DAA2F;AAI3F,gDAA6C;AAC7C,wDAAoD;AACpD,2CAAyD;AACzD,8CAMyB;AAEzB,iDAAiF;AACjF,2DAAqD;AAErD,yDAAwE;AACxE,iFAA2E;AAC3E,8CAAgD;AAEhD;;;;;;;;;;;GAWG;AACH,MAAa,sBAAsB;IA4BjC;;;OAGG;IACH,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC;IACzC,CAAC;IAED;;;;OAIG;IACH,IAAI,uBAAuB;QACzB,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC;IACnC,CAAC;IA6DD,YACE,0CAAkD,EAClD,sBAAuD,EACvD,oBAIyB,EACzB,QAAgC;;QAEhC,IAAI,CAAC,QAAQ,GAAG,IAAA,8CAAuB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AO,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"]}
@@ -309,7 +309,7 @@ function createRheaOptions(consumerId, name, address, obj, state, queue, eventPo
309
309
  if (typeof ownerLevel === "number") {
310
310
  rheaOptions.properties[core_amqp_1.Constants.attachEpoch] = rhea_promise_1.types.wrap_long(ownerLevel);
311
311
  }
312
- rheaOptions.desired_capabilities = [core_amqp_1.Constants.geoReplication];
312
+ rheaOptions.desired_capabilities = [constants_js_1.geoReplication];
313
313
  if (options.trackLastEnqueuedEventProperties) {
314
314
  rheaOptions.desired_capabilities.push(core_amqp_1.Constants.enableRece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.\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/partitionReceiver.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAwGlC,wCAiLC;AAmBD,0CAiBC;AAYD,sCAmDC;AA1XD,8DAAsE;AACtE,gDAQ0B;AAC1B,+CAMsB;AACtB,iDAAuF;AACvF,yDAA2E;AAC3E,2CAOqB;AAGrB,kDAA+D;AAC/D,gDAA0D;AAE1D,8CAAgD;AAChD,+CAAyC;AACzC,sDAA6E;AAQ7E,MAAM,eAAe,GAAG,0CAA0C,CAAC;AACnE,sEAAsE;AACtE,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAyD7B,gBAAgB;AAChB,SAAgB,cAAc,CAC5B,GAAsB,EACtB,aAAqB,EACrB,UAAkB,EAClB,WAAmB,EACnB,aAA4B,EAC5B,UAAoC,EAAE;IAEtC,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IAC1E,MAAM,IAAI,GAAG,IAAA,wBAAa,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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 { 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"]}
@@ -8,7 +8,7 @@ exports.PENDING_PUBLISH_SEQ_NUM_SYMBOL = exports.geoReplication = exports.receiv
8
8
  */
9
9
  exports.packageJsonInfo = {
10
10
  name: "@azure/event-hubs",
11
- version: "5.13.0-beta.3",
11
+ version: "5.13.0",
12
12
  };
13
13
  /**
14
14
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/util/constants.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC;;GAEG;AACU,QAAA,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,eAAe;CACzB,CAAC;AAEF;;GAEG;AACU,QAAA,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AACH,QAAA,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AACH,QAAA,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACU,QAAA,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;AACU,QAAA,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,QAAQ;CAClB,CAAC;AAEF;;GAEG;AACU,QAAA,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AACH,QAAA,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AACH,QAAA,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACU,QAAA,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"]}
@@ -202,10 +202,21 @@ export interface EventData {
202
202
  [key: string]: any;
203
203
  };
204
204
  }
205
+ /**
206
+ * Asserts that the provided data conforms to the `EventData` interface.
207
+ *
208
+ * This function performs runtime checks on the `data` object to ensure it matches the expected
209
+ * structure and types defined in the `EventData` interface. If any of the checks fail, it throws
210
+ * an error with a descriptive message indicating the mismatch.
211
+ *
212
+ * @param data - The data object to validate as `EventData`.
213
+ * @throws \{Error\} Throws an error if the data does not conform to the `EventData` interface.
214
+ */
215
+ export declare function assertIsEventData(data: any): asserts data is EventData;
205
216
  /**
206
217
  * The interface that describes the structure of the event received from Event Hub.
207
218
  * Use this as a reference when creating the `processEvents` function to process the events
208
- * recieved from an Event Hub when using the `EventHubConsumerClient`.
219
+ * received from an Event Hub when using the `EventHubConsumerClient`.
209
220
  */
210
221
  export interface ReceivedEventData {
211
222
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"eventData.d.ts","sourceRoot":"","sources":["../../src/eventData.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAa,MAAM,kBAAkB,CAAC;AAEnE,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,OAAO,IAAI,WAAW,EAEvB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAEL,8BAA8B,EAC/B,MAAM,qBAAqB,CAAC;AAE7B;;;GAGG;AACH,MAAM,WAAW,2BAA4B,SAAQ,mBAAmB;IACtE;;OAEG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;OAEG;IACH,6BAA6B,CAAC,EAAE,MAAM,CAAC;IACvC;;OAEG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;OAEG;IACH,+BAA+B,CAAC,EAAE,MAAM,CAAC;IACzC;;OAEG;IACH,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA2B,SAAQ,kBAAkB;IACpE;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC;;OAEG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,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AAM,CAAC;IAErC;;OAEG;IACH,iBAAiB,IAAI,oBAAoB,CAAC;CAC3C;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,oBAAoB,CAK1F;AA2CD;;GAEG;AACH,MAAM,WAAW,8CAA8C;IAC7D,6BAA6B,EAAE,OAAO,CAAC;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;GAGG;AACH,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,WAAW,EACxB,EACE,6BAA6B,EAC7B,UAAU,EACV,eAAe,EACf,qBAAqB,GACtB,EAAE,8CAA8C,GAChD,IAAI,CAqBN"}
@@ -5,6 +5,7 @@ import { defaultDataTransformer } from "./dataTransformer.js";
5
5
  import { types, } from "rhea-promise";
6
6
  import { isDefined, isObjectWithProperties, objectHasProperty } from "@azure/core-util";
7
7
  import { idempotentProducerAmqpPropertyNames, PENDING_PUBLISH_SEQ_NUM_SYMBOL, } from "./util/constants.js";
8
+ import isBuffer from "is-buffer";
8
9
  const messagePropertiesMap = {
9
10
  message_id: "messageId",
10
11
  user_id: "userId",
@@ -114,7 +115,7 @@ export function toRheaMessage(data, partitionKey) {
114
115
  body: defaultDataTransformer.encode(data.body, bodyType),
115
116
  };
116
117
  // As per the AMQP 1.0 spec If the message-annotations or delivery-annotations section is omitted,
117
- // it is equivalent to a message-annotations section containing anempty map of annotations.
118
+ // it is equivalent to a message-annotations section containing empty map of annotations.
118
119
  rheaMessage.message_annotations = {};
119
120
  if (data.properties) {
120
121
  rheaMessage.application_properties = data.properties;
@@ -142,6 +143,39 @@ export function toRheaMessage(data, partitionKey) {
142
143
  }
143
144
  return rheaMessage;
144
145
  }
146
+ /**
147
+ * Asserts that the provided data conforms to the `EventData` interface.
148
+ *
149
+ * This function performs runtime checks on the `data` object to ensure it matches the expected
150
+ * structure and types defined in the `EventData` interface. If any of the checks fail, it throws
151
+ * an error with a descriptive message indicating the mismatch.
152
+ *
153
+ * @param data - The data object to validate as `EventData`.
154
+ * @throws \{Error\} Throws an error if the data does not conform to the `EventData` interface.
155
+ */
156
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
157
+ export function assertIsEventData(data) {
158
+ if (data.contentType != null && typeof data.contentType !== "string") {
159
+ throw new Error(`Invalid 'contentType': expected 'string' or 'undefined', but received '${typeof data.contentType}'.`);
160
+ }
161
+ if (data.correlationId != null &&
162
+ typeof data.correlationId !== "string" &&
163
+ typeof data.correlationId !== "number" &&
164
+ !isBuffer(data.correlationId)) {
165
+ throw new Error(`Invalid 'correlationId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.correlationId}'.`);
166
+ }
167
+ if (data.messageId != null &&
168
+ typeof data.messageId !== "string" &&
169
+ typeof data.messageId !== "number" &&
170
+ !isBuffer(data.messageId)) {
171
+ throw new Error(`Invalid 'messageId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.messageId}'.`);
172
+ }
173
+ if (data.properties !== undefined &&
174
+ (typeof data.properties !== "object" || Array.isArray(data.properties))) {
175
+ const actualType = Array.isArray(data.properties) ? "array" : typeof data.properties;
176
+ throw new Error(`Invalid 'properties': expected an object or 'undefined', but received '${actualType}'.`);
177
+ }
178
+ }
145
179
  /**
146
180
  * @internal
147
181
  */
@@ -1 +1 @@
1
- {"version":3,"file":"eventData.js","sourceRoot":"","sources":["../../src/eventData.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAa,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAIL,KAAK,GACN,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,C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WAAW,CAAC,mBAAmB,IAAI,EAAE,CAAC;IACjE,IAAI,CAAC,WAAW,CAAC,mBAAmB,EAAE,CAAC;QACrC,WAAW,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;IACvD,CAAC;IAED,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;QAC1B,kBAAkB,CAAC,mCAAmC,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,SAAS,CAAC,eAAe,CAAC,EAAE,CAAC;QAC/B,kBAAkB,CAAC,mCAAmC,CAAC,UAAU,CAAC;YAChE,KAAK,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;IACD,IAAI,SAAS,CAAC,qBAAqB,CAAC,EAAE,CAAC;QACrC,kBAAkB,CAAC,mCAAmC,CAAC,sBAAsB,CAAC;YAC5E,KAAK,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;IAC1C,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage, Constants } from \"@azure/core-amqp\";\nimport { BodyTypes, defaultDataTransformer } from \"./dataTransformer.js\";\nimport {\n DeliveryAnnotations,\n MessageAnnotations,\n Message as RheaMessage,\n types,\n} from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties, objectHasProperty } from \"@azure/core-util\";\nimport {\n idempotentProducerAmqpPropertyNames,\n PENDING_PUBLISH_SEQ_NUM_SYMBOL,\n} from \"./util/constants.js\";\n\n/**\n * Describes the delivery annotations.\n * @internal\n */\nexport interface EventHubDeliveryAnnotations extends DeliveryAnnotations {\n /**\n * The offset of the last event.\n */\n last_enqueued_offset?: string;\n /**\n * The sequence number of the last event.\n */\n last_enqueued_sequence_number?: number;\n /**\n * The enqueued time of the last event.\n */\n last_enqueued_time_utc?: number;\n /**\n * The retrieval time of the last event.\n */\n runtime_info_retrieval_time_utc?: number;\n /**\n * Any unknown delivery annotations.\n */\n [x: string]: any;\n}\n\n/**\n * Map containing message attributes that will be held in the message header.\n * @internal\n */\nexport interface EventHubMessageAnnotations extends MessageAnnotations {\n /**\n * Annotation for the partition key set for the event.\n */\n \"x-opt-partition-key\"?: string | null;\n /**\n * Annotation for the sequence number of the event.\n */\n \"x-opt-sequence-number\"?: number;\n /**\n * Annotation for the enqueued time of the event.\n */\n \"x-opt-enqueued-time\"?: number;\n /**\n * Annotation for the offset of the event.\n */\n \"x-opt-offset\"?: string;\n /**\n * Any other annotation that can be added to the message.\n */\n [x: string]: any;\n}\n\n/**\n * Describes the structure of an event to be sent or received from the EventHub.\n * @internal\n */\nexport interface EventDataInternal {\n /**\n * The message body that needs to be sent or is received.\n */\n body: any;\n /**\n * The enqueued time of the event.\n */\n enqueuedTimeUtc?: Date;\n /**\n * If specified EventHub will hash this to a partitionId.\n * It guarantees that messages end up in a specific partition on the event hub.\n */\n partitionKey?: string | null;\n /**\n * The offset of the event.\n */\n offset?: string;\n /**\n * The sequence number of the event.\n */\n sequenceNumber?: number;\n /**\n * The application specific properties.\n */\n properties?: { [property: string]: any };\n /**\n * The last sequence number of the event within the partition stream of the Event Hub.\n */\n lastSequenceNumber?: number;\n /**\n * The offset of the last enqueued event.\n */\n lastEnqueuedOffset?: string;\n /**\n * The enqueued UTC time of the last event.\n */\n lastEnqueuedTime?: Date;\n /**\n * The time when the runtime info was retrieved\n */\n retrievalTime?: Date;\n /**\n * The properties set by the service.\n */\n systemProperties?: { [property: string]: any };\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n *\n * Note: Numbers that are not whole integers are not allowed.\n */\n messageId?: string | number | Buffer;\n /**\n * Returns the underlying raw amqp message.\n */\n getRawAmqpMessage(): AmqpAnnotatedMessage;\n /**\n * The pending publish sequence number, set while the event\n * is being published with idempotent partitions enabled.\n */\n [PENDING_PUBLISH_SEQ_NUM_SYMBOL]?: number;\n /**\n * The sequence number the event was published with\n * when idempotent partitions are enabled.\n */\n _publishedSequenceNumber?: number;\n}\n\nconst messagePropertiesMap = {\n message_id: \"messageId\",\n user_id: \"userId\",\n to: \"to\",\n subject: \"subject\",\n reply_to: \"replyTo\",\n correlation_id: \"correlationId\",\n content_type: \"contentType\",\n content_encoding: \"contentEncoding\",\n absolute_expiry_time: \"absoluteExpiryTime\",\n creation_time: \"creationTime\",\n group_id: \"groupId\",\n group_sequence: \"groupSequence\",\n reply_to_group_id: \"replyToGroupId\",\n} as const;\n\n/**\n * Converts the AMQP message to an EventData.\n * @param msg - The AMQP message that needs to be converted to EventData.\n * @param skipParsingBodyAsJson - Boolean to skip running JSON.parse() on message body when body type is `content`.\n * @internal\n */\nexport function fromRheaMessage(\n msg: RheaMessage,\n skipParsingBodyAsJson: boolean,\n): EventDataInternal {\n const rawMessage = AmqpAnnotatedMessage.fromRheaMessage(msg);\n const { body, bodyType } = defaultDataTransformer.decode(msg.body, skipParsingBodyAsJson);\n rawMessage.bodyType = bodyType;\n\n const data: EventDataInternal = {\n body,\n getRawAmqpMessage() {\n return rawMessage;\n },\n };\n\n if (msg.message_annotations) {\n for (const annotationKey of Object.keys(msg.message_annotations)) {\n switch (annotationKey) {\n case Constants.partitionKey:\n data.partitionKey = msg.message_annotations[annotationKey];\n break;\n case Constants.sequenceNumber:\n data.sequenceNumber = msg.message_annotations[annotationKey];\n break;\n case Constants.enqueuedTime:\n data.enqueuedTimeUtc = new Date(msg.message_annotations[annotationKey]);\n break;\n case Constants.offset:\n data.offset = msg.message_annotations[annotationKey];\n break;\n default:\n if (!data.systemProperties) {\n data.systemProperties = {};\n }\n data.systemProperties[annotationKey] = convertDatesToNumbers(\n msg.message_annotations[annotationKey],\n );\n break;\n }\n }\n }\n if (msg.application_properties) {\n data.properties = convertDatesToNumbers(msg.application_properties);\n }\n if (msg.delivery_annotations) {\n data.lastEnqueuedOffset = msg.delivery_annotations.last_enqueued_offset;\n data.lastSequenceNumber = msg.delivery_annotations.last_enqueued_sequence_number;\n data.lastEnqueuedTime = new Date(msg.delivery_annotations.last_enqueued_time_utc as number);\n data.retrievalTime = new Date(\n msg.delivery_annotations.runtime_info_retrieval_time_utc as number,\n );\n }\n\n const messageProperties = Object.keys(messagePropertiesMap) as Array<\n keyof typeof messagePropertiesMap\n >;\n for (const messageProperty of messageProperties) {\n if (!data.systemProperties) {\n data.systemProperties = {};\n }\n if (msg[messageProperty] != null) {\n data.systemProperties[messagePropertiesMap[messageProperty]] = convertDatesToNumbers(\n msg[messageProperty],\n );\n }\n }\n\n if (msg.content_type != null) {\n data.contentType = msg.content_type;\n }\n if (msg.correlation_id != null) {\n data.correlationId = msg.correlation_id;\n }\n if (msg.message_id != null) {\n data.messageId = msg.message_id;\n }\n\n return data;\n}\n\n/**\n * Converts an EventData object to an AMQP message.\n * @param data - The EventData object that needs to be converted to an AMQP message.\n * @param partitionKey - An optional key to determine the partition that this event should land in.\n * @internal\n */\nexport function toRheaMessage(\n data: EventData | AmqpAnnotatedMessage,\n partitionKey?: string,\n): RheaMessage {\n let rheaMessage: RheaMessage;\n if (isAmqpAnnotatedMessage(data)) {\n rheaMessage = {\n ...AmqpAnnotatedMessage.toRheaMessage(data),\n body: defaultDataTransformer.encode(data.body, data.bodyType ?? \"data\"),\n };\n } else {\n let bodyType: BodyTypes = \"data\";\n if (typeof (data as EventDataInternal).getRawAmqpMessage === \"function\") {\n /*\n If the event is being round-tripped, then we respect the `bodyType` of the\n underlying AMQP message.\n */\n bodyType = (data as EventDataInternal).getRawAmqpMessage().bodyType ?? \"data\";\n }\n\n rheaMessage = {\n body: defaultDataTransformer.encode(data.body, bodyType),\n };\n // As per the AMQP 1.0 spec If the message-annotations or delivery-annotations section is omitted,\n // it is equivalent to a message-annotations section containing anempty map of annotations.\n rheaMessage.message_annotations = {};\n\n if (data.properties) {\n rheaMessage.application_properties = data.properties;\n }\n\n if (isDefined(partitionKey)) {\n rheaMessage.message_annotations[Constants.partitionKey] = partitionKey;\n // Event Hub service cannot route messages to a specific partition based on the partition key\n // if AMQP message header is an empty object. Hence we make sure that header is always present\n // with atleast one property. Setting durable to true, helps us achieve that.\n rheaMessage.durable = true;\n }\n\n if (data.contentType != null) {\n rheaMessage.content_type = data.contentType;\n }\n if (data.correlationId != null) {\n rheaMessage.correlation_id = data.correlationId;\n }\n if (data.messageId != null) {\n if (\n typeof data.messageId === \"string\" &&\n data.messageId.length > Constants.maxMessageIdLength\n ) {\n throw new Error(\n `Length of 'messageId' property on the event cannot be greater than ${Constants.maxMessageIdLength} characters.`,\n );\n }\n rheaMessage.message_id = data.messageId;\n }\n }\n\n return rheaMessage;\n}\n\n/**\n * The interface that describes the data to be sent to Event Hub.\n * Use this as a reference when creating the object to be sent when using the `EventHubProducerClient`.\n * For example, `{ body: \"your-data\" }` or\n * ```\n * {\n * body: \"your-data\",\n * properties: {\n * propertyName: \"property value\"\n * }\n * }\n * ```\n */\nexport interface EventData {\n /**\n * The message body that needs to be sent.\n * If the application reading the events is not using this SDK,\n * convert your body payload to a byte array or Buffer for better\n * cross-language compatibility.\n */\n body: any;\n\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n *\n * Note: Numbers that are not whole integers are not allowed.\n */\n messageId?: string | number | Buffer;\n\n /**\n * Set of key value pairs that can be used to set properties specific to user application.\n */\n properties?: {\n [key: string]: any;\n };\n}\n\n/**\n * The interface that describes the structure of the event received from Event Hub.\n * Use this as a reference when creating the `processEvents` function to process the events\n * recieved from an Event Hub when using the `EventHubConsumerClient`.\n */\nexport interface ReceivedEventData {\n /**\n * The message body that needs to be sent or is received.\n */\n body: any;\n /**\n * The application specific properties.\n */\n properties?: {\n [key: string]: any;\n };\n /**\n * The enqueued time of the event.\n */\n enqueuedTimeUtc: Date;\n /**\n * When specified Event Hub will hash this to a partitionId.\n * It guarantees that messages end up in a specific partition on the event hub.\n */\n partitionKey: string | null;\n /**\n * The offset of the event.\n */\n offset: string;\n /**\n * The sequence number of the event.\n */\n sequenceNumber: number;\n /**\n * The properties set by the service.\n */\n systemProperties?: {\n [key: string]: any;\n };\n\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n */\n messageId?: string | number | Buffer;\n\n /**\n * Returns the underlying raw amqp message.\n */\n getRawAmqpMessage(): AmqpAnnotatedMessage;\n}\n\n/**\n * @internal\n */\nexport function isAmqpAnnotatedMessage(possible: unknown): possible is AmqpAnnotatedMessage {\n return (\n isObjectWithProperties(possible, [\"body\", \"bodyType\"]) &&\n !objectHasProperty(possible, \"getRawAmqpMessage\")\n );\n}\n\n/**\n * Converts any Date objects into a number representing date.getTime().\n * Recursively checks for any Date objects in arrays and objects.\n * @internal\n */\nfunction convertDatesToNumbers<T = unknown>(thing: T): T {\n // fast exit\n if (!isDefined(thing)) return thing;\n\n // When 'thing' is a Date, return the number representation\n if (\n typeof thing === \"object\" &&\n objectHasProperty(thing, \"getTime\") &&\n typeof thing.getTime === \"function\"\n ) {\n return thing.getTime();\n }\n\n /*\n Examples:\n [0, 'foo', new Date(), { nested: new Date()}]\n */\n if (Array.isArray(thing)) {\n return thing.map(convertDatesToNumbers) as unknown as T;\n }\n\n /*\n Examples:\n { foo: new Date(), children: { nested: new Date() }}\n */\n if (typeof thing === \"object\" && isDefined<object>(thing)) {\n const thingShallowCopy = { ...thing };\n for (const key of Object.keys(thingShallowCopy)) {\n (thingShallowCopy as any)[key] = convertDatesToNumbers((thingShallowCopy as any)[key]);\n }\n return thingShallowCopy;\n }\n\n return thing;\n}\n\n/**\n * @internal\n */\nexport interface PopulateIdempotentMessageAnnotationsParameters {\n isIdempotentPublishingEnabled: boolean;\n ownerLevel?: number;\n producerGroupId?: number;\n publishSequenceNumber?: number;\n}\n\n/**\n * Populates a rhea message with idempotent producer properties.\n * @internal\n */\nexport function populateIdempotentMessageAnnotations(\n rheaMessage: RheaMessage,\n {\n isIdempotentPublishingEnabled,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber,\n }: PopulateIdempotentMessageAnnotationsParameters,\n): void {\n if (!isIdempotentPublishingEnabled) {\n return;\n }\n\n const messageAnnotations = rheaMessage.message_annotations || {};\n if (!rheaMessage.message_annotations) {\n rheaMessage.message_annotations = messageAnnotations;\n }\n\n if (isDefined(ownerLevel)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.epoch] = types.wrap_short(ownerLevel);\n }\n if (isDefined(producerGroupId)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.producerId] =\n types.wrap_long(producerGroupId);\n }\n if (isDefined(publishSequenceNumber)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.producerSequenceNumber] =\n types.wrap_int(publishSequenceNumber);\n }\n}\n"]}
1
+ {"version":3,"file":"eventData.js","sourceRoot":"","sources":["../../src/eventData.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAa,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAIL,KAAK,GACN,MAAM,cAAc,CAAC;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0B;IAEjD,IAAI,CAAC,6BAA6B,EAAE,CAAC;QACnC,OAAO;IACT,CAAC;IAED,MAAM,kBAAkB,GAAG,WAAW,CAAC,mBAAmB,IAAI,EAAE,CAAC;IACjE,IAAI,CAAC,WAAW,CAAC,mBAAmB,EAAE,CAAC;QACrC,WAAW,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;IACvD,CAAC;IAED,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;QAC1B,kBAAkB,CAAC,mCAAmC,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,SAAS,CAAC,eAAe,CAAC,EAAE,CAAC;QAC/B,kBAAkB,CAAC,mCAAmC,CAAC,UAAU,CAAC;YAChE,KAAK,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;IACD,IAAI,SAAS,CAAC,qBAAqB,CAAC,EAAE,CAAC;QACrC,kBAAkB,CAAC,mCAAmC,CAAC,sBAAsB,CAAC;YAC5E,KAAK,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;IAC1C,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage, Constants } from \"@azure/core-amqp\";\nimport { BodyTypes, defaultDataTransformer } from \"./dataTransformer.js\";\nimport {\n DeliveryAnnotations,\n MessageAnnotations,\n Message as RheaMessage,\n types,\n} from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties, objectHasProperty } from \"@azure/core-util\";\nimport {\n idempotentProducerAmqpPropertyNames,\n PENDING_PUBLISH_SEQ_NUM_SYMBOL,\n} from \"./util/constants.js\";\nimport isBuffer from \"is-buffer\";\n\n/**\n * Describes the delivery annotations.\n * @internal\n */\nexport interface EventHubDeliveryAnnotations extends DeliveryAnnotations {\n /**\n * The offset of the last event.\n */\n last_enqueued_offset?: string;\n /**\n * The sequence number of the last event.\n */\n last_enqueued_sequence_number?: number;\n /**\n * The enqueued time of the last event.\n */\n last_enqueued_time_utc?: number;\n /**\n * The retrieval time of the last event.\n */\n runtime_info_retrieval_time_utc?: number;\n /**\n * Any unknown delivery annotations.\n */\n [x: string]: any;\n}\n\n/**\n * Map containing message attributes that will be held in the message header.\n * @internal\n */\nexport interface EventHubMessageAnnotations extends MessageAnnotations {\n /**\n * Annotation for the partition key set for the event.\n */\n \"x-opt-partition-key\"?: string | null;\n /**\n * Annotation for the sequence number of the event.\n */\n \"x-opt-sequence-number\"?: number;\n /**\n * Annotation for the enqueued time of the event.\n */\n \"x-opt-enqueued-time\"?: number;\n /**\n * Annotation for the offset of the event.\n */\n \"x-opt-offset\"?: string;\n /**\n * Any other annotation that can be added to the message.\n */\n [x: string]: any;\n}\n\n/**\n * Describes the structure of an event to be sent or received from the EventHub.\n * @internal\n */\nexport interface EventDataInternal {\n /**\n * The message body that needs to be sent or is received.\n */\n body: any;\n /**\n * The enqueued time of the event.\n */\n enqueuedTimeUtc?: Date;\n /**\n * If specified EventHub will hash this to a partitionId.\n * It guarantees that messages end up in a specific partition on the event hub.\n */\n partitionKey?: string | null;\n /**\n * The offset of the event.\n */\n offset?: string;\n /**\n * The sequence number of the event.\n */\n sequenceNumber?: number;\n /**\n * The application specific properties.\n */\n properties?: { [property: string]: any };\n /**\n * The last sequence number of the event within the partition stream of the Event Hub.\n */\n lastSequenceNumber?: number;\n /**\n * The offset of the last enqueued event.\n */\n lastEnqueuedOffset?: string;\n /**\n * The enqueued UTC time of the last event.\n */\n lastEnqueuedTime?: Date;\n /**\n * The time when the runtime info was retrieved\n */\n retrievalTime?: Date;\n /**\n * The properties set by the service.\n */\n systemProperties?: { [property: string]: any };\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n *\n * Note: Numbers that are not whole integers are not allowed.\n */\n messageId?: string | number | Buffer;\n /**\n * Returns the underlying raw amqp message.\n */\n getRawAmqpMessage(): AmqpAnnotatedMessage;\n /**\n * The pending publish sequence number, set while the event\n * is being published with idempotent partitions enabled.\n */\n [PENDING_PUBLISH_SEQ_NUM_SYMBOL]?: number;\n /**\n * The sequence number the event was published with\n * when idempotent partitions are enabled.\n */\n _publishedSequenceNumber?: number;\n}\n\nconst messagePropertiesMap = {\n message_id: \"messageId\",\n user_id: \"userId\",\n to: \"to\",\n subject: \"subject\",\n reply_to: \"replyTo\",\n correlation_id: \"correlationId\",\n content_type: \"contentType\",\n content_encoding: \"contentEncoding\",\n absolute_expiry_time: \"absoluteExpiryTime\",\n creation_time: \"creationTime\",\n group_id: \"groupId\",\n group_sequence: \"groupSequence\",\n reply_to_group_id: \"replyToGroupId\",\n} as const;\n\n/**\n * Converts the AMQP message to an EventData.\n * @param msg - The AMQP message that needs to be converted to EventData.\n * @param skipParsingBodyAsJson - Boolean to skip running JSON.parse() on message body when body type is `content`.\n * @internal\n */\nexport function fromRheaMessage(\n msg: RheaMessage,\n skipParsingBodyAsJson: boolean,\n): EventDataInternal {\n const rawMessage = AmqpAnnotatedMessage.fromRheaMessage(msg);\n const { body, bodyType } = defaultDataTransformer.decode(msg.body, skipParsingBodyAsJson);\n rawMessage.bodyType = bodyType;\n\n const data: EventDataInternal = {\n body,\n getRawAmqpMessage() {\n return rawMessage;\n },\n };\n\n if (msg.message_annotations) {\n for (const annotationKey of Object.keys(msg.message_annotations)) {\n switch (annotationKey) {\n case Constants.partitionKey:\n data.partitionKey = msg.message_annotations[annotationKey];\n break;\n case Constants.sequenceNumber:\n data.sequenceNumber = msg.message_annotations[annotationKey];\n break;\n case Constants.enqueuedTime:\n data.enqueuedTimeUtc = new Date(msg.message_annotations[annotationKey]);\n break;\n case Constants.offset:\n data.offset = msg.message_annotations[annotationKey];\n break;\n default:\n if (!data.systemProperties) {\n data.systemProperties = {};\n }\n data.systemProperties[annotationKey] = convertDatesToNumbers(\n msg.message_annotations[annotationKey],\n );\n break;\n }\n }\n }\n if (msg.application_properties) {\n data.properties = convertDatesToNumbers(msg.application_properties);\n }\n if (msg.delivery_annotations) {\n data.lastEnqueuedOffset = msg.delivery_annotations.last_enqueued_offset;\n data.lastSequenceNumber = msg.delivery_annotations.last_enqueued_sequence_number;\n data.lastEnqueuedTime = new Date(msg.delivery_annotations.last_enqueued_time_utc as number);\n data.retrievalTime = new Date(\n msg.delivery_annotations.runtime_info_retrieval_time_utc as number,\n );\n }\n\n const messageProperties = Object.keys(messagePropertiesMap) as Array<\n keyof typeof messagePropertiesMap\n >;\n for (const messageProperty of messageProperties) {\n if (!data.systemProperties) {\n data.systemProperties = {};\n }\n if (msg[messageProperty] != null) {\n data.systemProperties[messagePropertiesMap[messageProperty]] = convertDatesToNumbers(\n msg[messageProperty],\n );\n }\n }\n\n if (msg.content_type != null) {\n data.contentType = msg.content_type;\n }\n if (msg.correlation_id != null) {\n data.correlationId = msg.correlation_id;\n }\n if (msg.message_id != null) {\n data.messageId = msg.message_id;\n }\n\n return data;\n}\n\n/**\n * Converts an EventData object to an AMQP message.\n * @param data - The EventData object that needs to be converted to an AMQP message.\n * @param partitionKey - An optional key to determine the partition that this event should land in.\n * @internal\n */\nexport function toRheaMessage(\n data: EventData | AmqpAnnotatedMessage,\n partitionKey?: string,\n): RheaMessage {\n let rheaMessage: RheaMessage;\n if (isAmqpAnnotatedMessage(data)) {\n rheaMessage = {\n ...AmqpAnnotatedMessage.toRheaMessage(data),\n body: defaultDataTransformer.encode(data.body, data.bodyType ?? \"data\"),\n };\n } else {\n let bodyType: BodyTypes = \"data\";\n if (typeof (data as EventDataInternal).getRawAmqpMessage === \"function\") {\n /*\n If the event is being round-tripped, then we respect the `bodyType` of the\n underlying AMQP message.\n */\n bodyType = (data as EventDataInternal).getRawAmqpMessage().bodyType ?? \"data\";\n }\n\n rheaMessage = {\n body: defaultDataTransformer.encode(data.body, bodyType),\n };\n // As per the AMQP 1.0 spec If the message-annotations or delivery-annotations section is omitted,\n // it is equivalent to a message-annotations section containing empty map of annotations.\n rheaMessage.message_annotations = {};\n\n if (data.properties) {\n rheaMessage.application_properties = data.properties;\n }\n\n if (isDefined(partitionKey)) {\n rheaMessage.message_annotations[Constants.partitionKey] = partitionKey;\n // Event Hub service cannot route messages to a specific partition based on the partition key\n // if AMQP message header is an empty object. Hence we make sure that header is always present\n // with atleast one property. Setting durable to true, helps us achieve that.\n rheaMessage.durable = true;\n }\n\n if (data.contentType != null) {\n rheaMessage.content_type = data.contentType;\n }\n if (data.correlationId != null) {\n rheaMessage.correlation_id = data.correlationId;\n }\n if (data.messageId != null) {\n if (\n typeof data.messageId === \"string\" &&\n data.messageId.length > Constants.maxMessageIdLength\n ) {\n throw new Error(\n `Length of 'messageId' property on the event cannot be greater than ${Constants.maxMessageIdLength} characters.`,\n );\n }\n rheaMessage.message_id = data.messageId;\n }\n }\n\n return rheaMessage;\n}\n\n/**\n * The interface that describes the data to be sent to Event Hub.\n * Use this as a reference when creating the object to be sent when using the `EventHubProducerClient`.\n * For example, `{ body: \"your-data\" }` or\n * ```\n * {\n * body: \"your-data\",\n * properties: {\n * propertyName: \"property value\"\n * }\n * }\n * ```\n */\nexport interface EventData {\n /**\n * The message body that needs to be sent.\n * If the application reading the events is not using this SDK,\n * convert your body payload to a byte array or Buffer for better\n * cross-language compatibility.\n */\n body: any;\n\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n *\n * Note: Numbers that are not whole integers are not allowed.\n */\n messageId?: string | number | Buffer;\n\n /**\n * Set of key value pairs that can be used to set properties specific to user application.\n */\n properties?: {\n [key: string]: any;\n };\n}\n\n/**\n * Asserts that the provided data conforms to the `EventData` interface.\n *\n * This function performs runtime checks on the `data` object to ensure it matches the expected\n * structure and types defined in the `EventData` interface. If any of the checks fail, it throws\n * an error with a descriptive message indicating the mismatch.\n *\n * @param data - The data object to validate as `EventData`.\n * @throws \\{Error\\} Throws an error if the data does not conform to the `EventData` interface.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function assertIsEventData(data: any): asserts data is EventData {\n if (data.contentType != null && typeof data.contentType !== \"string\") {\n throw new Error(\n `Invalid 'contentType': expected 'string' or 'undefined', but received '${typeof data.contentType}'.`,\n );\n }\n\n if (\n data.correlationId != null &&\n typeof data.correlationId !== \"string\" &&\n typeof data.correlationId !== \"number\" &&\n !isBuffer(data.correlationId)\n ) {\n throw new Error(\n `Invalid 'correlationId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.correlationId}'.`,\n );\n }\n\n if (\n data.messageId != null &&\n typeof data.messageId !== \"string\" &&\n typeof data.messageId !== \"number\" &&\n !isBuffer(data.messageId)\n ) {\n throw new Error(\n `Invalid 'messageId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.messageId}'.`,\n );\n }\n\n if (\n data.properties !== undefined &&\n (typeof data.properties !== \"object\" || Array.isArray(data.properties))\n ) {\n const actualType = Array.isArray(data.properties) ? \"array\" : typeof data.properties;\n throw new Error(\n `Invalid 'properties': expected an object or 'undefined', but received '${actualType}'.`,\n );\n }\n}\n\n/**\n * The interface that describes the structure of the event received from Event Hub.\n * Use this as a reference when creating the `processEvents` function to process the events\n * received from an Event Hub when using the `EventHubConsumerClient`.\n */\nexport interface ReceivedEventData {\n /**\n * The message body that needs to be sent or is received.\n */\n body: any;\n /**\n * The application specific properties.\n */\n properties?: {\n [key: string]: any;\n };\n /**\n * The enqueued time of the event.\n */\n enqueuedTimeUtc: Date;\n /**\n * When specified Event Hub will hash this to a partitionId.\n * It guarantees that messages end up in a specific partition on the event hub.\n */\n partitionKey: string | null;\n /**\n * The offset of the event.\n */\n offset: string;\n /**\n * The sequence number of the event.\n */\n sequenceNumber: number;\n /**\n * The properties set by the service.\n */\n systemProperties?: {\n [key: string]: any;\n };\n\n /**\n * The content type of the message. Optionally describes\n * the payload of the message, with a descriptor following the format of RFC2045, Section 5, for\n * example \"application/json\".\n */\n contentType?: string;\n\n /**\n * The correlation identifier that allows an\n * application to specify a context for the message for the purposes of correlation, for example\n * reflecting the MessageId of a message that is being replied to.\n */\n correlationId?: string | number | Buffer;\n\n /**\n * The message identifier is an\n * application-defined value that uniquely identifies the message and its payload.\n */\n messageId?: string | number | Buffer;\n\n /**\n * Returns the underlying raw amqp message.\n */\n getRawAmqpMessage(): AmqpAnnotatedMessage;\n}\n\n/**\n * @internal\n */\nexport function isAmqpAnnotatedMessage(possible: unknown): possible is AmqpAnnotatedMessage {\n return (\n isObjectWithProperties(possible, [\"body\", \"bodyType\"]) &&\n !objectHasProperty(possible, \"getRawAmqpMessage\")\n );\n}\n\n/**\n * Converts any Date objects into a number representing date.getTime().\n * Recursively checks for any Date objects in arrays and objects.\n * @internal\n */\nfunction convertDatesToNumbers<T = unknown>(thing: T): T {\n // fast exit\n if (!isDefined(thing)) return thing;\n\n // When 'thing' is a Date, return the number representation\n if (\n typeof thing === \"object\" &&\n objectHasProperty(thing, \"getTime\") &&\n typeof thing.getTime === \"function\"\n ) {\n return thing.getTime();\n }\n\n /*\n Examples:\n [0, 'foo', new Date(), { nested: new Date()}]\n */\n if (Array.isArray(thing)) {\n return thing.map(convertDatesToNumbers) as unknown as T;\n }\n\n /*\n Examples:\n { foo: new Date(), children: { nested: new Date() }}\n */\n if (typeof thing === \"object\" && isDefined<object>(thing)) {\n const thingShallowCopy = { ...thing };\n for (const key of Object.keys(thingShallowCopy)) {\n (thingShallowCopy as any)[key] = convertDatesToNumbers((thingShallowCopy as any)[key]);\n }\n return thingShallowCopy;\n }\n\n return thing;\n}\n\n/**\n * @internal\n */\nexport interface PopulateIdempotentMessageAnnotationsParameters {\n isIdempotentPublishingEnabled: boolean;\n ownerLevel?: number;\n producerGroupId?: number;\n publishSequenceNumber?: number;\n}\n\n/**\n * Populates a rhea message with idempotent producer properties.\n * @internal\n */\nexport function populateIdempotentMessageAnnotations(\n rheaMessage: RheaMessage,\n {\n isIdempotentPublishingEnabled,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber,\n }: PopulateIdempotentMessageAnnotationsParameters,\n): void {\n if (!isIdempotentPublishingEnabled) {\n return;\n }\n\n const messageAnnotations = rheaMessage.message_annotations || {};\n if (!rheaMessage.message_annotations) {\n rheaMessage.message_annotations = messageAnnotations;\n }\n\n if (isDefined(ownerLevel)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.epoch] = types.wrap_short(ownerLevel);\n }\n if (isDefined(producerGroupId)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.producerId] =\n types.wrap_long(producerGroupId);\n }\n if (isDefined(publishSequenceNumber)) {\n messageAnnotations[idempotentProducerAmqpPropertyNames.producerSequenceNumber] =\n types.wrap_int(publishSequenceNumber);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"eventDataBatch.d.ts","sourceRoot":"","sources":["../../src/eventDataBatch.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAuD,MAAM,gBAAgB,CAAC;AAChG,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG3D,OAAO,EAAE,uBAAuB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG9E,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAepE;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,OAAO,GAAG,cAAc,IAAI,cAAc,CAO1F;AAED;;GAEG;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