@azure/event-hubs 5.13.0-alpha.20241008.6 → 5.13.0-alpha.20241011.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":"partitionReceiver.js","sourceRoot":"","sources":["../../src/partitionReceiver.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAmB,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACL,SAAS,EAET,kBAAkB,EAClB,oBAAoB,EACpB,KAAK,EACL,SAAS,GAEV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAKL,KAAK,GACN,MAAM,cAAc,CAAC;AACtB,OAAO,EAAwC,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,EAAiB,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,MAAM,EACN,MAAM,IAAI,WAAW,EAErB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAQ7D,MAAM,eAAe,GAAG,0CAA0C,CAAC;AACnE,sEAAsE;AACtE,MAAM,iBAAiB,G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,EACJ,OAAO,EACP,GAAG,EACH,KAAK,EACL,KAAK,EACL,aAAa,EACb,MAAM,EACN,OAAO,CACR,CAAC;IACF,MAAM,CAAC,OAAO,CAAC,qCAAqC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC3E,KAAK,CAAC,IAAI,GAAG,MAAM,GAAG,CAAC,UAAU,CAAC,cAAc,iCAC3C,WAAW,KACd,WAAW,IACX,CAAC;IACH,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC;IAC3B,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC1C,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AAC5B,CAAC;AAED,SAAS,UAAU,CAAC,QAA0B,EAAE,YAAoB;IAClE,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport {\n Constants,\n MessagingError,\n RetryOperationType,\n StandardAbortMessage,\n retry,\n translate,\n RetryConfig,\n} from \"@azure/core-amqp\";\nimport {\n EventContext,\n Receiver as Link,\n ReceiverOptions as RheaReceiverOptions,\n Source,\n types,\n} from \"rhea-promise\";\nimport { EventDataInternal, ReceivedEventData, fromRheaMessage } from \"./eventData.js\";\nimport { EventPosition, getEventPositionFilter } from \"./eventPosition.js\";\nimport {\n createSimpleLogger,\n logErrorStackTrace,\n logObj,\n logger as azureLogger,\n SimpleLogger,\n createReceiverLogPrefix,\n} from \"./logger.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { PartitionReceiverOptions } from \"./models/private.js\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries.js\";\nimport { createAbortablePromise } from \"@azure/core-util\";\nimport { TimerLoop } from \"./util/timerLoop.js\";\nimport { getRandomName } from \"./util/utils.js\";\nimport { withAuth } from \"./withAuth.js\";\nimport { receiverIdPropertyName } from \"./util/constants.js\";\n\ntype Writable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n/** @internal */\nexport type WritableReceiver = Writable<PartitionReceiver>;\n\nconst abortLogMessage = \"operation has been cancelled by the user\";\n/** The time to wait in ms before attempting to read from the queue */\nconst qReadIntervalInMs = 20;\n\n/**\n * A set of information about the last enqueued event of a partition, as observed by the consumer as\n * events are received from the Event Hubs service\n */\nexport interface LastEnqueuedEventProperties {\n /**\n * The sequence number of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n sequenceNumber?: number;\n /**\n * The date and time, in UTC, that the last event was enqueued into the Event Hub partition from\n * which this event was received.\n */\n enqueuedOn?: Date;\n /**\n * The offset of the event that was last enqueued into the Event Hub partition from which\n * this event was received.\n */\n offset?: string;\n /**\n * The date and time, in UTC, that the last event was retrieved from the Event Hub partition.\n */\n retrievedOn?: Date;\n}\n\n/** @internal */\nexport interface PartitionReceiver {\n readonly checkpoint: number;\n readonly lastEnqueuedEventProperties: LastEnqueuedEventProperties;\n readonly isClosed: boolean;\n readonly close: () => Promise<void>;\n readonly abort: () => Promise<void>;\n readonly isOpen: () => boolean;\n readonly receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds?: number,\n abortSignal?: AbortSignalLike,\n ) => Promise<ReceivedEventData[]>;\n /** Needed for tests only */\n readonly _onError?: (error: MessagingError | Error) => void;\n readonly connect: (options: ConnectOptions) => Promise<void>;\n}\n\ninterface ConnectOptions {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n}\n\ninterface ReceiverState {\n link?: Link;\n authLoop?: TimerLoop;\n isConnecting: boolean;\n}\n\n/** @internal */\nexport function createReceiver(\n ctx: ConnectionContext,\n consumerGroup: string,\n consumerId: string,\n partitionId: string,\n eventPosition: EventPosition,\n options: PartitionReceiverOptions = {},\n): PartitionReceiver {\n const address = ctx.config.getReceiverAddress(partitionId, consumerGroup);\n const name = getRandomName(address);\n const audience = ctx.config.getReceiverAudience(partitionId, consumerGroup);\n const logPrefix = createReceiverLogPrefix(consumerId, ctx.connectionId, partitionId);\n const logger = createSimpleLogger(azureLogger, logPrefix);\n const queue: ReceivedEventData[] = [];\n const state: ReceiverState = {\n isConnecting: false,\n };\n\n const obj: WritableReceiver = {\n _onError: undefined,\n checkpoint: -1,\n lastEnqueuedEventProperties: {},\n isClosed: false,\n close: async () => {\n clearHandlers(obj);\n delete ctx.receivers[name];\n logger.verbose(\"deleted the receiver from the client cache\");\n state.authLoop?.stop();\n return state.link\n ?.close()\n .catch((err) => {\n logger.warning(`an error occurred while closing: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n throw err;\n })\n .finally(() => {\n obj.isClosed = true;\n logger.verbose(\"is closed\");\n state.link = undefined;\n state.authLoop = undefined;\n });\n },\n abort: () => {\n obj._onError?.(new AbortError(StandardAbortMessage));\n logger.info(abortLogMessage);\n return obj.close();\n },\n isOpen: () => {\n const isOpen = !!state.link?.isOpen();\n logger.verbose(`is open? -> ${isOpen}`);\n return isOpen;\n },\n async connect({ abortSignal, timeoutInMs }: ConnectOptions): Promise<void> {\n if (state.isConnecting || obj.isOpen()) {\n return;\n }\n state.isConnecting = true;\n logger.verbose(\"is trying to connect\");\n try {\n await ctx.readyToOpenLink({ abortSignal });\n state.authLoop = await withAuth(\n () =>\n setupLink(\n consumerId,\n ctx,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n abortSignal,\n ),\n ctx,\n audience,\n timeoutInMs,\n logger,\n {\n abortSignal,\n },\n );\n } catch (err) {\n state.isConnecting = false;\n const error = translate(err);\n logger.error(\n `an error occurred while creating the receiver: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(err);\n throw error;\n }\n },\n receiveBatch: (\n maxMessageCount: number,\n maxWaitTimeInSeconds: number = 60,\n abortSignal?: AbortSignalLike,\n ) => {\n const prefetchCount = options.prefetchCount ?? maxMessageCount * 3;\n const cleanupBeforeAbort = (): Promise<void> => {\n logger.info(abortLogMessage);\n return obj.close();\n };\n const retrieveEvents = (): Promise<ReceivedEventData[]> => {\n const eventsToRetrieveCount = Math.max(maxMessageCount - queue.length, 0);\n logger.verbose(\n `already has ${queue.length} events and wants to receive ${eventsToRetrieveCount} more events`,\n );\n if (abortSignal?.aborted) {\n cleanupBeforeAbort();\n return Promise.reject(new AbortError(StandardAbortMessage));\n }\n return obj.isClosed || ctx.wasConnectionCloseCalled || eventsToRetrieveCount === 0\n ? Promise.resolve(queue.splice(0, maxMessageCount))\n : new Promise<void>((resolve, reject) => {\n obj._onError = reject;\n obj // eslint-disable-line promise/catch-or-return\n .connect({\n abortSignal,\n timeoutInMs: getRetryAttemptTimeoutInMs(options.retryOptions),\n })\n .then(() => {\n addCredits(state.link, Math.max(prefetchCount, maxMessageCount) - queue.length);\n logger.verbose(`setting the max wait time to ${maxWaitTimeInSeconds} seconds`);\n return waitForEvents(\n maxMessageCount,\n maxWaitTimeInSeconds * 1000,\n qReadIntervalInMs,\n queue,\n {\n abortSignal,\n cleanupBeforeAbort,\n receivedAfterWait: () =>\n logger.info(\n `${Math.min(\n maxMessageCount,\n queue.length,\n )} messages received within ${maxWaitTimeInSeconds} seconds`,\n ),\n receivedAlready: () =>\n logger.info(`${maxMessageCount} messages already received`),\n receivedNone: () =>\n logger.info(\n `no messages received when max wait time in seconds ${maxWaitTimeInSeconds} is over`,\n ),\n },\n );\n })\n .catch(reject)\n .then(resolve);\n })\n .then(() => queue.splice(0, maxMessageCount))\n .finally(() => clearHandlers(obj));\n };\n return retry(\n Object.defineProperties(\n {\n operation: retrieveEvents,\n operationType: RetryOperationType.receiveMessage,\n abortSignal: abortSignal,\n retryOptions: options.retryOptions ?? {},\n },\n {\n connectionId: {\n enumerable: true,\n get: () => ctx.connectionId,\n },\n connectionHost: {\n enumerable: true,\n get: () => ctx.config.host,\n },\n },\n ) as RetryConfig<ReceivedEventData[]>,\n );\n },\n };\n return obj;\n}\n\nfunction delay(\n waitTimeInMs: number,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setTimeout>;\n return createAbortablePromise<void>((resolve) => {\n token = setTimeout(resolve, waitTimeInMs);\n }, options).finally(() => clearTimeout(token));\n}\n\n/**\n * @internal\n */\nexport function checkOnInterval(\n waitTimeInMs: number,\n check: () => boolean,\n options?: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n abortErrorMsg?: string;\n },\n): Promise<void> {\n let token: ReturnType<typeof setInterval>;\n return createAbortablePromise<void>((resolve) => {\n token = setInterval(() => {\n if (check()) {\n resolve();\n }\n }, waitTimeInMs);\n }, options).finally(() => clearInterval(token));\n}\n\n/**\n * Returns a promise that will resolve when it is time to read from the queue\n * @param maxEventCount - The maximum number of events to receive.\n * @param maxWaitTimeInMs - The maximum time to wait in ms for the queue to contain any events.\n * @param readIntervalWaitTimeInMs - The time interval to wait in ms before checking the queue.\n * @param queue - The queue to read from.\n * @param options - The options bag.\n * @returns a promise that will resolve when it is time to read from the queue\n * @internal\n */\nexport function waitForEvents(\n maxEventCount: number,\n maxWaitTimeInMs: number,\n readIntervalWaitTimeInMs: number,\n queue: unknown[],\n options: {\n abortSignal?: AbortSignalLike;\n cleanupBeforeAbort?: () => void;\n receivedAfterWait?: () => void;\n receivedAlready?: () => void;\n receivedNone?: () => void;\n } = {},\n): Promise<void> {\n const {\n abortSignal: clientAbortSignal,\n cleanupBeforeAbort,\n receivedNone,\n receivedAfterWait,\n receivedAlready,\n } = options;\n\n if (queue.length >= maxEventCount) {\n return Promise.resolve().then(receivedAlready);\n }\n\n const aborter = new AbortController();\n const abortListener = () => {\n aborter.abort();\n };\n clientAbortSignal?.addEventListener(\"abort\", abortListener);\n let cleanupBeforeAbortCalled = false;\n\n const updatedOptions = {\n abortSignal: aborter.signal,\n abortErrorMsg: StandardAbortMessage,\n cleanupBeforeAbort: () => {\n if (clientAbortSignal?.aborted && !cleanupBeforeAbortCalled) {\n cleanupBeforeAbort?.();\n cleanupBeforeAbortCalled = true;\n }\n },\n };\n return Promise.race([\n checkOnInterval(readIntervalWaitTimeInMs, () => queue.length > 0, updatedOptions)\n .then(() => delay(readIntervalWaitTimeInMs, updatedOptions))\n .then(receivedAfterWait),\n delay(maxWaitTimeInMs, updatedOptions).then(receivedNone),\n ]).finally(() => {\n aborter.abort();\n clientAbortSignal?.removeEventListener(\"abort\", abortListener);\n });\n}\n\nfunction convertAMQPMesage(data: EventDataInternal): ReceivedEventData {\n const rawMessage = data.getRawAmqpMessage();\n const receivedEventData: ReceivedEventData = {\n body: data.body,\n properties: data.properties,\n offset: data.offset!,\n sequenceNumber: data.sequenceNumber!,\n enqueuedTimeUtc: data.enqueuedTimeUtc!,\n partitionKey: data.partitionKey!,\n systemProperties: data.systemProperties,\n getRawAmqpMessage() {\n return rawMessage;\n },\n };\n if (data.correlationId != null) {\n receivedEventData.correlationId = data.correlationId;\n }\n if (data.contentType != null) {\n receivedEventData.contentType = data.contentType;\n }\n if (data.messageId != null) {\n receivedEventData.messageId = data.messageId;\n }\n return receivedEventData;\n}\n\nfunction setEventProps(eventProps: LastEnqueuedEventProperties, data: EventDataInternal): void {\n eventProps.sequenceNumber = data.lastSequenceNumber;\n eventProps.enqueuedOn = data.lastEnqueuedTime;\n eventProps.offset = data.lastEnqueuedOffset;\n eventProps.retrievedOn = data.retrievalTime;\n}\n\nfunction clearHandlers(obj: WritableReceiver): void {\n obj._onError = undefined;\n}\n\nfunction onMessage(\n context: EventContext,\n obj: WritableReceiver,\n queue: ReceivedEventData[],\n options: PartitionReceiverOptions,\n): void {\n if (!context.message) {\n return;\n }\n const data = fromRheaMessage(context.message, !!options.skipParsingBodyAsJson);\n const receivedEventData = convertAMQPMesage(data);\n obj.checkpoint = receivedEventData.sequenceNumber;\n if (options.trackLastEnqueuedEventProperties) {\n setEventProps(obj.lastEnqueuedEventProperties, data);\n }\n queue.push(receivedEventData);\n}\n\nfunction onError(\n context: EventContext,\n obj: PartitionReceiver,\n receiver: Link | undefined,\n logger: SimpleLogger,\n): void {\n const rheaReceiver = receiver || context.receiver;\n const amqpError = rheaReceiver?.error;\n logger.verbose(`'receiver_error' event occurred: ${logObj(amqpError)}`);\n if (obj._onError && amqpError) {\n const error = translate(amqpError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nfunction onSessionError(context: EventContext, obj: PartitionReceiver, logger: SimpleLogger): void {\n const sessionError = context.session?.error;\n logger.verbose(`'session_error' event occurred: ${logObj(sessionError)}`);\n if (obj._onError && sessionError) {\n const error = translate(sessionError);\n logErrorStackTrace(error);\n obj._onError(error);\n }\n}\n\nasync function onClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'receiver_close' event occurred. Value for isItselfClosed on the receiver is: '${rheaReceiver\n ?.isItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'receiver_close' event: ${logObj(err)}`);\n });\n }\n}\n\nasync function onSessionClose(\n context: EventContext,\n state: ReceiverState,\n logger: SimpleLogger,\n): Promise<void> {\n const rheaReceiver = state.link || context.receiver;\n logger.verbose(\n `'session_close' event occurred. Value for isSessionItselfClosed on the session is: '${rheaReceiver\n ?.isSessionItselfClosed()\n .toString()}' Value for isConnecting on the session is: '${state.isConnecting}'`,\n );\n if (rheaReceiver && !state.isConnecting) {\n return rheaReceiver.close().catch((err) => {\n logger.verbose(`error when closing after 'session_close' event: ${logObj(err)}`);\n });\n }\n}\n\nfunction createRheaOptions(\n consumerId: string,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n): RheaReceiverOptions {\n const rheaOptions: RheaReceiverOptions & { source: Source; properties: Record<string, any> } = {\n name,\n autoaccept: true,\n target: consumerId,\n source: {\n address,\n },\n credit_window: 0,\n properties: {\n [receiverIdPropertyName]: consumerId,\n },\n onClose: (context) => onClose(context, state, logger),\n onSessionClose: (context) => onSessionClose(context, state, logger),\n onError: (context) => onError(context, obj, state.link, logger),\n onMessage: (context) => onMessage(context, obj, queue, options),\n onSessionError: (context) => onSessionError(context, obj, logger),\n };\n const ownerLevel = options.ownerLevel;\n if (typeof ownerLevel === \"number\") {\n rheaOptions.properties[Constants.attachEpoch] = types.wrap_long(ownerLevel);\n }\n rheaOptions.desired_capabilities = [Constants.geoReplication];\n if (options.trackLastEnqueuedEventProperties) {\n rheaOptions.desired_capabilities.push(Constants.enableReceiverRuntimeMetricName);\n }\n const filterClause = getEventPositionFilter(\n obj.checkpoint > -1 ? { sequenceNumber: obj.checkpoint } : eventPosition,\n );\n rheaOptions.source.filter = {\n \"apache.org:selector-filter:string\": types.wrap_described(filterClause, 0x468c00000004),\n };\n return rheaOptions;\n}\n\nasync function setupLink(\n consumerId: string,\n ctx: ConnectionContext,\n name: string,\n address: string,\n obj: PartitionReceiver,\n state: ReceiverState,\n queue: ReceivedEventData[],\n eventPosition: EventPosition,\n logger: SimpleLogger,\n options: PartitionReceiverOptions,\n abortSignal?: AbortSignalLike,\n): Promise<void> {\n const rheaOptions = createRheaOptions(\n consumerId,\n name,\n address,\n obj,\n state,\n queue,\n eventPosition,\n logger,\n options,\n );\n logger.verbose(`trying to be created with options ${logObj(rheaOptions)}`);\n state.link = await ctx.connection.createReceiver({\n ...rheaOptions,\n abortSignal,\n });\n state.isConnecting = false;\n logger.verbose(\"is created successfully\");\n ctx.receivers[name] = obj;\n}\n\nfunction addCredits(receiver: Link | undefined, creditsToAdd: number): void {\n if (creditsToAdd > 0) {\n receiver?.addCredit(creditsToAdd);\n }\n}\n"]}
1
+ {"version":3,"file":"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AAS,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"]}
@@ -5,7 +5,7 @@
5
5
  */
6
6
  export const packageJsonInfo = {
7
7
  name: "@azure/event-hubs",
8
- version: "5.13.0-beta.3",
8
+ version: "5.13.0",
9
9
  };
10
10
  /**
11
11
  * @internal
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/util/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,eAAe;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AAChB,MAAM,CAAC,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AAChB,MAAM,CAAC,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,MAAM,CAAC,GAAG,CACtD,gDAAgD,CACjD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @internal\n */\nexport const packageJsonInfo = {\n name: \"@azure/event-hubs\",\n version: \"5.13.0-beta.3\",\n};\n\n/**\n * @internal\n */\nexport const idempotentProducerAmqpPropertyNames = {\n capability: \"com.microsoft:idempotent-producer\",\n epoch: \"com.microsoft:producer-epoch\",\n producerId: \"com.microsoft:producer-id\",\n producerSequenceNumber: \"com.microsoft:producer-sequence-number\",\n} as const;\n\n/** @internal */\nexport const receiverIdPropertyName = \"com.microsoft:receiver-name\";\n\n/** @internal */\nexport const geoReplication = \"com.microsoft:georeplication\";\n\n/**\n * @internal\n */\nexport const PENDING_PUBLISH_SEQ_NUM_SYMBOL = Symbol.for(\n \"@azure/event-hubs.pendingPublishSequenceNumber\",\n);\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/util/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,mBAAmB;IACzB,OAAO,EAAE,QAAQ;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG;IACjD,UAAU,EAAE,mCAAmC;IAC/C,KAAK,EAAE,8BAA8B;IACrC,UAAU,EAAE,2BAA2B;IACvC,sBAAsB,EAAE,wCAAwC;CACxD,CAAC;AAEX,gBAAgB;AAChB,MAAM,CAAC,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEpE,gBAAgB;AAChB,MAAM,CAAC,MAAM,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,MAAM,CAAC,GAAG,CACtD,gDAAgD,CACjD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @internal\n */\nexport const packageJsonInfo = {\n name: \"@azure/event-hubs\",\n version: \"5.13.0\",\n};\n\n/**\n * @internal\n */\nexport const idempotentProducerAmqpPropertyNames = {\n capability: \"com.microsoft:idempotent-producer\",\n epoch: \"com.microsoft:producer-epoch\",\n producerId: \"com.microsoft:producer-id\",\n producerSequenceNumber: \"com.microsoft:producer-sequence-number\",\n} as const;\n\n/** @internal */\nexport const receiverIdPropertyName = \"com.microsoft:receiver-name\";\n\n/** @internal */\nexport const geoReplication = \"com.microsoft:georeplication\";\n\n/**\n * @internal\n */\nexport const PENDING_PUBLISH_SEQ_NUM_SYMBOL = Symbol.for(\n \"@azure/event-hubs.pendingPublishSequenceNumber\",\n);\n"]}
@@ -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,IAAI,EAAE,GAAG,CAAC;IACV;;OAEG;IACH,eAAe,CAAC,EAAE,IAAI,CAAC;IACvB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CA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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"}
@@ -4,13 +4,16 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.fromRheaMessage = fromRheaMessage;
6
6
  exports.toRheaMessage = toRheaMessage;
7
+ exports.assertIsEventData = assertIsEventData;
7
8
  exports.isAmqpAnnotatedMessage = isAmqpAnnotatedMessage;
8
9
  exports.populateIdempotentMessageAnnotations = populateIdempotentMessageAnnotations;
10
+ const tslib_1 = require("tslib");
9
11
  const core_amqp_1 = require("@azure/core-amqp");
10
12
  const dataTransformer_js_1 = require("./dataTransformer.js");
11
13
  const rhea_promise_1 = require("rhea-promise");
12
14
  const core_util_1 = require("@azure/core-util");
13
15
  const constants_js_1 = require("./util/constants.js");
16
+ const is_buffer_1 = tslib_1.__importDefault(require("is-buffer"));
14
17
  const messagePropertiesMap = {
15
18
  message_id: "messageId",
16
19
  user_id: "userId",
@@ -120,7 +123,7 @@ function toRheaMessage(data, partitionKey) {
120
123
  body: dataTransformer_js_1.defaultDataTransformer.encode(data.body, bodyType),
121
124
  };
122
125
  // As per the AMQP 1.0 spec If the message-annotations or delivery-annotations section is omitted,
123
- // it is equivalent to a message-annotations section containing anempty map of annotations.
126
+ // it is equivalent to a message-annotations section containing empty map of annotations.
124
127
  rheaMessage.message_annotations = {};
125
128
  if (data.properties) {
126
129
  rheaMessage.application_properties = data.properties;
@@ -148,6 +151,39 @@ function toRheaMessage(data, partitionKey) {
148
151
  }
149
152
  return rheaMessage;
150
153
  }
154
+ /**
155
+ * Asserts that the provided data conforms to the `EventData` interface.
156
+ *
157
+ * This function performs runtime checks on the `data` object to ensure it matches the expected
158
+ * structure and types defined in the `EventData` interface. If any of the checks fail, it throws
159
+ * an error with a descriptive message indicating the mismatch.
160
+ *
161
+ * @param data - The data object to validate as `EventData`.
162
+ * @throws \{Error\} Throws an error if the data does not conform to the `EventData` interface.
163
+ */
164
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
165
+ function assertIsEventData(data) {
166
+ if (data.contentType != null && typeof data.contentType !== "string") {
167
+ throw new Error(`Invalid 'contentType': expected 'string' or 'undefined', but received '${typeof data.contentType}'.`);
168
+ }
169
+ if (data.correlationId != null &&
170
+ typeof data.correlationId !== "string" &&
171
+ typeof data.correlationId !== "number" &&
172
+ !(0, is_buffer_1.default)(data.correlationId)) {
173
+ throw new Error(`Invalid 'correlationId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.correlationId}'.`);
174
+ }
175
+ if (data.messageId != null &&
176
+ typeof data.messageId !== "string" &&
177
+ typeof data.messageId !== "number" &&
178
+ !(0, is_buffer_1.default)(data.messageId)) {
179
+ throw new Error(`Invalid 'messageId': expected 'string', 'number', 'Buffer', or 'undefined', but received '${typeof data.messageId}'.`);
180
+ }
181
+ if (data.properties !== undefined &&
182
+ (typeof data.properties !== "object" || Array.isArray(data.properties))) {
183
+ const actualType = Array.isArray(data.properties) ? "array" : typeof data.properties;
184
+ throw new Error(`Invalid 'properties': expected an object or 'undefined', but received '${actualType}'.`);
185
+ }
186
+ }
151
187
  /**
152
188
  * @internal
153
189
  */
@@ -1 +1 @@
1
- {"version":3,"file":"eventData.js","sourceRoot":"","sources":["../../src/eventData.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAmLlC,0CA8EC;AAQD,sCA2DC;AA2HD,wDAKC;AAyDD,oFA6BC;AAxhBD,gDAAmE;AACnE,6DAAyE;AACzE,+CAKsB;AACtB,gDAAwF;AACxF,sDAG6B;AA+I7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,CAAC,WAAW,CAAC,mBAAmB,EAAE,CAAC;QACrC,WAAW,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;IACvD,CAAC;IAED,IAAI,IAAA,qBAAS,EAAC,UAAU,CAAC,EAAE,CAAC;QAC1B,kBAAkB,CAAC,kDAAmC,CAAC,KAAK,CAAC,GAAG,oBAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,IAAA,qBAAS,EAAC,eAAe,CAAC,EAAE,CAAC;QAC/B,kBAAkB,CAAC,kDAAmC,CAAC,UAAU,CAAC;YAChE,oBAAK,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;IACD,IAAI,IAAA,qBAAS,EAAC,qBAAqB,CAAC,EAAE,CAAC;QACrC,kBAAkB,CAAC,kDAAmC,CAAC,sBAAsB,CAAC;YAC5E,oBAAK,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;;AAoLlC,0CA8EC;AAQD,sCA2DC;AAiED,8CAsCC;AAuED,wDAKC;AAyDD,oFA6BC;;AA5kBD,gDAAmE;AACnE,6DAAyE;AACzE,+CAKsB;AACtB,gDAAwF;AACxF,sDAG6B;AAC7B,kEAAiC;AA+IjC,MAAM,oBAAoB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EAAE,CAAC;QACrC,WAAW,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;IACvD,CAAC;IAED,IAAI,IAAA,qBAAS,EAAC,UAAU,CAAC,EAAE,CAAC;QAC1B,kBAAkB,CAAC,kDAAmC,CAAC,KAAK,CAAC,GAAG,oBAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,IAAA,qBAAS,EAAC,eAAe,CAAC,EAAE,CAAC;QAC/B,kBAAkB,CAAC,kDAAmC,CAAC,UAAU,CAAC;YAChE,oBAAK,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;IACD,IAAI,IAAA,qBAAS,EAAC,qBAAqB,CAAC,EAAE,CAAC;QACrC,kBAAkB,CAAC,kDAAmC,CAAC,sBAAsB,CAAC;YAC5E,oBAAK,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;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,cAAc,CAAC,EAAE,uBAAuB,CAAC;CAC1C;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;OAMG;I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EACrB,WAAW,CAAC,EAAE,MAAM;IAWtB;;;OAGG;IACH,IAAI,cAAc,IAAI,MAAM,CAE3B;IAED;;;;OAIG;IACH,IAAI,YAAY,IAAI,MAAM,GAAG,SAAS,CAErC;IAED;;;;OAIG;IACH,IAAI,WAAW,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED;;;;OAIG;IACH,IAAI,WAAW,IAAI,MAAM,CAExB;IAED;;;OAGG;IACH,IAAI,KAAK,IAAI,MAAM,CAElB;IAED;;;;;OAKG;IACH,IAAI,+BAA+B,IAAI,MAAM,GAAG,SAAS,CAExD;IAED;;;OAGG;IACH,IAAI,oBAAoB,IAAI,cAAc,EAAE,CAE3C;IAED;;;;;OAKG;IACH,OAAO,CAAC,cAAc;IA4BtB;;OAEG;IACH,OAAO,CAAC,wCAAwC;IAwBhD;;;;OAIG;IACH,OAAO,CAAC,mDAAmD;IAoB3D;;;;;;;;;OASG;IACH,gBAAgB,CAAC,eAAe,CAAC,EAAE,6BAA6B,GAAG,MAAM;IAIzE;;OAEG;IACH,cAAc,IAAI,IAAI;IAItB;;;;;;;OAOG;IACI,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,oBAAoB,EAAE,OAAO,GAAE,aAAkB,GAAG,OAAO;CAyDjG"}
@@ -210,6 +210,9 @@ class EventDataBatchImpl {
210
210
  */
211
211
  tryAdd(eventData, options = {}) {
212
212
  (0, error_js_1.throwTypeErrorIfParameterMissing)(this._context.connectionId, "tryAdd", "eventData", eventData);
213
+ if (!(0, eventData_js_1.isAmqpAnnotatedMessage)(eventData)) {
214
+ (0, eventData_js_1.assertIsEventData)(eventData);
215
+ }
213
216
  const { entityPath, host } = this._context.config;
214
217
  const { event: instrumentedEvent, spanContext } = (0, instrumentEventData_js_1.instrumentEventData)(eventData, options, entityPath, host);
215
218
  // Convert EventData to RheaMessage.
@@ -1 +1 @@
1
- {"version":3,"file":"eventDataBatch.js","sourceRoot":"","sources":["../../src/eventDataBatch.ts"],"names":[],"mappings":";A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,IAAI,CAAC,cAAc,CAAC,EAAE,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC;QACxE,CAAC;QAED,MAAM,WAAW,GAAG,cAAc,CAAC,MAAM,CAAC;QAC1C,MAAM,eAAe,GACnB,WAAW,IAAI,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC;QACpF,WAAW,IAAI,WAAW,GAAG,eAAe,CAAC;QAE7C,kEAAkE;QAClE,mCAAmC;QACnC,IAAI,WAAW,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,kEAAkE;QAClE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC3C,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,CAAC;QAED,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAvTD,gDAuTC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { EventData, populateIdempotentMessageAnnotations, toRheaMessage } from \"./eventData.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { MessageAnnotations, message, Message as RheaMessage } from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties } from \"@azure/core-util\";\nimport { OperationTracingOptions, TracingContext } from \"@azure/core-tracing\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { PartitionPublishingProperties } from \"./models/private.js\";\n\n/**\n * The amount of bytes to reserve as overhead for a small message.\n */\nconst smallMessageOverhead = 5;\n/**\n * The amount of bytes to reserve as overhead for a large message.\n */\nconst largeMessageOverhead = 8;\n/**\n * The maximum number of bytes that a message may be to be considered small.\n */\nconst smallMessageMaxBytes = 255;\n\n/**\n * Checks if the provided eventDataBatch is an instance of `EventDataBatch`.\n * @param eventDataBatch - The instance of `EventDataBatch` to verify.\n * @internal\n */\nexport function isEventDataBatch(eventDataBatch: unknown): eventDataBatch is EventDataBatch {\n return (\n isObjectWithProperties(eventDataBatch, [\"count\", \"sizeInBytes\", \"tryAdd\"]) &&\n typeof eventDataBatch.tryAdd === \"function\" &&\n typeof eventDataBatch.count === \"number\" &&\n typeof eventDataBatch.sizeInBytes === \"number\"\n );\n}\n\n/**\n * Options to configure the behavior of the `tryAdd` method on the `EventDataBatch` class.\n */\nexport interface TryAddOptions {\n /**\n * The options to use when creating Spans for tracing.\n */\n tracingOptions?: OperationTracingOptions;\n}\n\n/**\n * An interface representing a batch of events which can be used to send events to Event Hub.\n *\n * To create the batch, use the `createBatch()` method on the `EventHubProducerClient`.\n * To send the batch, use the `sendBatch()` method on the same client.\n * To fill the batch, use the `tryAdd()` method on the batch itself.\n *\n */\nexport interface EventDataBatch {\n /**\n * A value that is hashed and used by the Azure Event Hubs service to determine the partition to\n * which the events are sent. Use the `createBatch()` method on the `EventHubProducerClient` to\n * set the partitionKey.\n * @readonly\n * @internal\n */\n readonly partitionKey?: string;\n\n /**\n * Id of the partition to which the batch of events are sent. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the partitionId.\n * @readonly\n * @internal\n */\n readonly partitionId?: string;\n\n /**\n * Size of the batch in bytes after the events added to it have been encoded into a single AMQP\n * message.\n * @readonly\n */\n readonly sizeInBytes: number;\n\n /**\n * Number of events added to the batch.\n * @readonly\n */\n readonly count: number;\n\n /**\n * The maximum size of the batch, in bytes. The `tryAdd` function on the batch will return `false`\n * if the event being added causes the size of the batch to exceed this limit. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the maxSizeInBytes.\n * @readonly\n */\n readonly maxSizeInBytes: number;\n\n /**\n * Adds an event to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object or AmqpAnnotatedMessage.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n tryAdd(eventData: EventData | AmqpAnnotatedMessage, options?: TryAddOptions): boolean;\n}\n\n/**\n * An internal class representing a batch of events which can be used to send events to Event Hub.\n *\n * @internal\n */\nexport class EventDataBatchImpl implements EventDataBatch {\n /**\n * Describes the amqp connection context for the Client.\n */\n private _context: ConnectionContext;\n /**\n * The Id of the partition to which the batch is expected to be sent to.\n * Specifying this will throw an error if the batch was created using a `partitionKey`.\n */\n private _partitionId?: string;\n /**\n * A value that is hashed to produce a partition assignment.\n * It guarantees that messages with the same partitionKey end up in the same partition.\n * Specifying this will throw an error if the batch was created using a `partitionId`.\n */\n private _partitionKey?: string;\n /**\n * The maximum size allowed for the batch.\n */\n private _maxSizeInBytes: number;\n /**\n * Current size of the batch in bytes.\n */\n private _sizeInBytes: number;\n /**\n * Encoded amqp messages.\n */\n private _encodedMessages: Buffer[] = [];\n /**\n * Number of events in the batch.\n */\n private _count: number;\n /**\n * List of 'message' span contexts.\n */\n private _spanContexts: TracingContext[] = [];\n /**\n * The message annotations to apply on the batch envelope.\n * This will reflect the message annotations on the first event\n * that was added to the batch.\n * A common annotation is the partition key.\n */\n private _batchAnnotations?: MessageAnnotations;\n /**\n * Indicates that the batch should be treated as idempotent.\n */\n private _isIdempotent: boolean;\n /**\n * The sequence number assigned to the first event in the batch while\n * the batch is being sent to the service.\n */\n private _pendingStartingSequenceNumber?: number;\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n private _startingPublishSequenceNumber?: number;\n\n /**\n * EventDataBatch should not be constructed using `new EventDataBatch()`\n * Use the `createBatch()` method on your `EventHubProducer` instead.\n * @internal\n */\n constructor(\n context: ConnectionContext,\n maxSizeInBytes: number,\n isIdempotent: boolean,\n partitionKey?: string,\n partitionId?: string,\n ) {\n this._context = context;\n this._maxSizeInBytes = maxSizeInBytes;\n this._isIdempotent = isIdempotent;\n this._partitionKey = isDefined(partitionKey) ? String(partitionKey) : partitionKey;\n this._partitionId = isDefined(partitionId) ? String(partitionId) : partitionId;\n this._sizeInBytes = 0;\n this._count = 0;\n }\n\n /**\n * The maximum size of the batch, in bytes.\n * @readonly\n */\n get maxSizeInBytes(): number {\n return this._maxSizeInBytes;\n }\n\n /**\n * The partitionKey set during `EventDataBatch` creation. This value is hashed to\n * produce a partition assignment when the producer is created without a `partitionId`\n * @readonly\n */\n get partitionKey(): string | undefined {\n return this._partitionKey;\n }\n\n /**\n * The partitionId set during `EventDataBatch` creation.\n * If this value is set then partitionKey can not be set.\n * @readonly\n */\n get partitionId(): string | undefined {\n return this._partitionId;\n }\n\n /**\n * Size of the `EventDataBatch` instance after the events added to it have been\n * encoded into a single AMQP message.\n * @readonly\n */\n get sizeInBytes(): number {\n return this._sizeInBytes;\n }\n\n /**\n * Number of events in the `EventDataBatch` instance.\n * @readonly\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n get startingPublishedSequenceNumber(): number | undefined {\n return this._startingPublishSequenceNumber;\n }\n\n /**\n * Gets the \"message\" span contexts that were created when adding events to the batch.\n * @internal\n */\n get _messageSpanContexts(): TracingContext[] {\n return this._spanContexts;\n }\n\n /**\n * Generates an AMQP message that contains the provided encoded events and annotations.\n * @param encodedEvents - The already encoded events to include in the AMQP batch.\n * @param annotations - The message annotations to set on the batch.\n * @param publishingProps - Idempotent publishing properties used to decorate the events in the batch while sending.\n */\n private _generateBatch(\n encodedEvents: Buffer[],\n annotations: MessageAnnotations | undefined,\n publishingProps?: PartitionPublishingProperties,\n ): Buffer {\n if (this._isIdempotent && publishingProps) {\n // We need to decode the encoded events, add the idempotent annotations, and re-encode them.\n // We can't lazily encode the events because we rely on `message.encode` to capture the\n // byte length of anything not in `event.body`.\n // Events can't be decorated ahead of time because the publishing properties aren't known\n // until the events are being sent to the service.\n const decodedEvents = encodedEvents.map(message.decode) as unknown as RheaMessage[];\n const decoratedEvents = this._decorateRheaMessagesWithPublishingProps(\n decodedEvents,\n publishingProps,\n );\n encodedEvents = decoratedEvents.map(message.encode);\n }\n\n const batchEnvelope: RheaMessage = {\n body: message.data_sections(encodedEvents),\n };\n if (annotations) {\n batchEnvelope.message_annotations = annotations;\n }\n return message.encode(batchEnvelope);\n }\n\n /**\n * Uses the publishingProps to add idempotent properties as message annotations to rhea messages.\n */\n private _decorateRheaMessagesWithPublishingProps(\n events: RheaMessage[],\n publishingProps: PartitionPublishingProperties,\n ): RheaMessage[] {\n if (!this._isIdempotent) {\n return events;\n }\n\n const { lastPublishedSequenceNumber = 0, ownerLevel, producerGroupId } = publishingProps;\n const startingSequenceNumber = lastPublishedSequenceNumber + 1;\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber: startingSequenceNumber + i,\n });\n }\n\n this._pendingStartingSequenceNumber = startingSequenceNumber;\n return events;\n }\n\n /**\n * Annotates a rhea message with placeholder idempotent properties if the batch is idempotent.\n * This is necessary so that we can accurately calculate the size of the batch while adding events.\n * Placeholder values are used because real values won't be known until we attempt to send the batch.\n */\n private _decorateRheaMessageWithPlaceholderIdempotencyProps(event: RheaMessage): RheaMessage {\n if (!this._isIdempotent) {\n return event;\n }\n\n if (!event.message_annotations) {\n event.message_annotations = {};\n }\n\n // Set placeholder values for these annotations.\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel: 0,\n publishSequenceNumber: 0,\n producerGroupId: 0,\n });\n\n return event;\n }\n\n /**\n * Generates the single AMQP message which is the result of encoding all the events\n * added into the `EventDataBatch` instance.\n *\n * This is not meant for the user to use directly.\n *\n * When the `EventDataBatch` instance is passed to the `send()` method on the `EventHubProducer`,\n * this single batched AMQP message is what gets sent over the wire to the service.\n * @readonly\n */\n _generateMessage(publishingProps?: PartitionPublishingProperties): Buffer {\n return this._generateBatch(this._encodedMessages, this._batchAnnotations, publishingProps);\n }\n\n /**\n * Sets startingPublishSequenceNumber to the pending publish sequence number.\n */\n _commitPublish(): void {\n this._startingPublishSequenceNumber = this._pendingStartingSequenceNumber;\n }\n\n /**\n * Tries to add an event data to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n public tryAdd(eventData: EventData | AmqpAnnotatedMessage, options: TryAddOptions = {}): boolean {\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"tryAdd\", \"eventData\", eventData);\n\n const { entityPath, host } = this._context.config;\n const { event: instrumentedEvent, spanContext } = instrumentEventData(\n eventData,\n options,\n entityPath,\n host,\n );\n\n // Convert EventData to RheaMessage.\n const amqpMessage = toRheaMessage(instrumentedEvent, this._partitionKey);\n const originalAnnotations = amqpMessage.message_annotations && {\n ...amqpMessage.message_annotations,\n };\n this._decorateRheaMessageWithPlaceholderIdempotencyProps(amqpMessage);\n const encodedMessage = message.encode(amqpMessage);\n\n let currentSize = this._sizeInBytes;\n // The first time an event is added, we need to calculate\n // the overhead of creating an AMQP batch, including the\n // message_annotations that are taken from the 1st message.\n if (this.count === 0) {\n if (originalAnnotations) {\n this._batchAnnotations = originalAnnotations;\n }\n\n // Figure out the overhead of creating a batch by generating an empty batch\n // with the expected batch annotations.\n currentSize += this._generateBatch([], this._batchAnnotations).length;\n }\n\n const messageSize = encodedMessage.length;\n const messageOverhead =\n messageSize <= smallMessageMaxBytes ? smallMessageOverhead : largeMessageOverhead;\n currentSize += messageSize + messageOverhead;\n\n // Check if the size of the batch exceeds the maximum allowed size\n // once we add the new event to it.\n if (currentSize > this._maxSizeInBytes) {\n return false;\n }\n\n // The event will fit in the batch, so it is now safe to store it.\n this._encodedMessages.push(encodedMessage);\n if (spanContext) {\n this._spanContexts.push(spanContext);\n }\n\n this._sizeInBytes = currentSize;\n this._count++;\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"eventDataBatch.js","sourceRoot":"","sources":["../../src/eventDataBatch.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAoClC,4CAOC;AAxCD,iDAMwB;AAExB,+CAAmF;AACnF,gDAAqE;AAErE,iFAA2E;AAC3E,8CAAmE;AAGnE;;GAEG;AACH,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B;;GAEG;AACH,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B;;GAEG;AACH,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,cAAuB;IACtD,OAAO,CACL,IAAA,kCAAsB,EAAC,cAAc,EAAE,CAAC,OAAO,EAAE,aAAa,EAAE,QAAQ,CAAC,CAAC;QAC1E,OAAO,cAAc,CAAC,MAAM,KAAK,UAAU;QAC3C,OAAO,cAAc,CAAC,KAAK,KAAK,QAAQ;QACxC,OAAO,cAAc,CAAC,WAAW,KAAK,QAAQ,CAC/C,CAAC;AACJ,CAAC;AAsED;;;;GAIG;AACH,MAAa,kBAAkB;IA4D7B;;;;OAIG;IACH,YACE,OAA0B,EAC1B,cAAsB,EACtB,YAAqB,EACrB,YAAqB,EACrB,WAAoB;QA9CtB;;WAEG;QACK,qBAAgB,GAAa,EAAE,CAAC;QAKxC;;WAEG;QACK,kBAAa,GAAqB,EAAE,CAAC;QAqC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;QACtC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,C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AAC;QACF,IAAI,CAAC,mDAAmD,CAAC,WAAW,CAAC,CAAC;QACtE,MAAM,cAAc,GAAG,sBAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QAEnD,IAAI,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC;QACpC,yDAAyD;QACzD,wDAAwD;QACxD,2DAA2D;QAC3D,IAAI,IAAI,CAAC,KAAK,KAAK,CAAC,EAAE,CAAC;YACrB,IAAI,mBAAmB,EAAE,CAAC;gBACxB,IAAI,CAAC,iBAAiB,GAAG,mBAAmB,CAAC;YAC/C,CAAC;YAED,2EAA2E;YAC3E,uCAAuC;YACvC,WAAW,IAAI,IAAI,CAAC,cAAc,CAAC,EAAE,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,CAAC;QACxE,CAAC;QAED,MAAM,WAAW,GAAG,cAAc,CAAC,MAAM,CAAC;QAC1C,MAAM,eAAe,GACnB,WAAW,IAAI,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC;QACpF,WAAW,IAAI,WAAW,GAAG,eAAe,CAAC;QAE7C,kEAAkE;QAClE,mCAAmC;QACnC,IAAI,WAAW,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,kEAAkE;QAClE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC3C,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,CAAC;QAED,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA1TD,gDA0TC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport {\n assertIsEventData,\n EventData,\n isAmqpAnnotatedMessage,\n populateIdempotentMessageAnnotations,\n toRheaMessage,\n} from \"./eventData.js\";\nimport { ConnectionContext } from \"./connectionContext.js\";\nimport { MessageAnnotations, message, Message as RheaMessage } from \"rhea-promise\";\nimport { isDefined, isObjectWithProperties } from \"@azure/core-util\";\nimport { OperationTracingOptions, TracingContext } from \"@azure/core-tracing\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData.js\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error.js\";\nimport { PartitionPublishingProperties } from \"./models/private.js\";\n\n/**\n * The amount of bytes to reserve as overhead for a small message.\n */\nconst smallMessageOverhead = 5;\n/**\n * The amount of bytes to reserve as overhead for a large message.\n */\nconst largeMessageOverhead = 8;\n/**\n * The maximum number of bytes that a message may be to be considered small.\n */\nconst smallMessageMaxBytes = 255;\n\n/**\n * Checks if the provided eventDataBatch is an instance of `EventDataBatch`.\n * @param eventDataBatch - The instance of `EventDataBatch` to verify.\n * @internal\n */\nexport function isEventDataBatch(eventDataBatch: unknown): eventDataBatch is EventDataBatch {\n return (\n isObjectWithProperties(eventDataBatch, [\"count\", \"sizeInBytes\", \"tryAdd\"]) &&\n typeof eventDataBatch.tryAdd === \"function\" &&\n typeof eventDataBatch.count === \"number\" &&\n typeof eventDataBatch.sizeInBytes === \"number\"\n );\n}\n\n/**\n * Options to configure the behavior of the `tryAdd` method on the `EventDataBatch` class.\n */\nexport interface TryAddOptions {\n /**\n * The options to use when creating Spans for tracing.\n */\n tracingOptions?: OperationTracingOptions;\n}\n\n/**\n * An interface representing a batch of events which can be used to send events to Event Hub.\n *\n * To create the batch, use the `createBatch()` method on the `EventHubProducerClient`.\n * To send the batch, use the `sendBatch()` method on the same client.\n * To fill the batch, use the `tryAdd()` method on the batch itself.\n *\n */\nexport interface EventDataBatch {\n /**\n * A value that is hashed and used by the Azure Event Hubs service to determine the partition to\n * which the events are sent. Use the `createBatch()` method on the `EventHubProducerClient` to\n * set the partitionKey.\n * @readonly\n * @internal\n */\n readonly partitionKey?: string;\n\n /**\n * Id of the partition to which the batch of events are sent. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the partitionId.\n * @readonly\n * @internal\n */\n readonly partitionId?: string;\n\n /**\n * Size of the batch in bytes after the events added to it have been encoded into a single AMQP\n * message.\n * @readonly\n */\n readonly sizeInBytes: number;\n\n /**\n * Number of events added to the batch.\n * @readonly\n */\n readonly count: number;\n\n /**\n * The maximum size of the batch, in bytes. The `tryAdd` function on the batch will return `false`\n * if the event being added causes the size of the batch to exceed this limit. Use the `createBatch()` method on\n * the `EventHubProducerClient` to set the maxSizeInBytes.\n * @readonly\n */\n readonly maxSizeInBytes: number;\n\n /**\n * Adds an event to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object or AmqpAnnotatedMessage.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n tryAdd(eventData: EventData | AmqpAnnotatedMessage, options?: TryAddOptions): boolean;\n}\n\n/**\n * An internal class representing a batch of events which can be used to send events to Event Hub.\n *\n * @internal\n */\nexport class EventDataBatchImpl implements EventDataBatch {\n /**\n * Describes the amqp connection context for the Client.\n */\n private _context: ConnectionContext;\n /**\n * The Id of the partition to which the batch is expected to be sent to.\n * Specifying this will throw an error if the batch was created using a `partitionKey`.\n */\n private _partitionId?: string;\n /**\n * A value that is hashed to produce a partition assignment.\n * It guarantees that messages with the same partitionKey end up in the same partition.\n * Specifying this will throw an error if the batch was created using a `partitionId`.\n */\n private _partitionKey?: string;\n /**\n * The maximum size allowed for the batch.\n */\n private _maxSizeInBytes: number;\n /**\n * Current size of the batch in bytes.\n */\n private _sizeInBytes: number;\n /**\n * Encoded amqp messages.\n */\n private _encodedMessages: Buffer[] = [];\n /**\n * Number of events in the batch.\n */\n private _count: number;\n /**\n * List of 'message' span contexts.\n */\n private _spanContexts: TracingContext[] = [];\n /**\n * The message annotations to apply on the batch envelope.\n * This will reflect the message annotations on the first event\n * that was added to the batch.\n * A common annotation is the partition key.\n */\n private _batchAnnotations?: MessageAnnotations;\n /**\n * Indicates that the batch should be treated as idempotent.\n */\n private _isIdempotent: boolean;\n /**\n * The sequence number assigned to the first event in the batch while\n * the batch is being sent to the service.\n */\n private _pendingStartingSequenceNumber?: number;\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n private _startingPublishSequenceNumber?: number;\n\n /**\n * EventDataBatch should not be constructed using `new EventDataBatch()`\n * Use the `createBatch()` method on your `EventHubProducer` instead.\n * @internal\n */\n constructor(\n context: ConnectionContext,\n maxSizeInBytes: number,\n isIdempotent: boolean,\n partitionKey?: string,\n partitionId?: string,\n ) {\n this._context = context;\n this._maxSizeInBytes = maxSizeInBytes;\n this._isIdempotent = isIdempotent;\n this._partitionKey = isDefined(partitionKey) ? String(partitionKey) : partitionKey;\n this._partitionId = isDefined(partitionId) ? String(partitionId) : partitionId;\n this._sizeInBytes = 0;\n this._count = 0;\n }\n\n /**\n * The maximum size of the batch, in bytes.\n * @readonly\n */\n get maxSizeInBytes(): number {\n return this._maxSizeInBytes;\n }\n\n /**\n * The partitionKey set during `EventDataBatch` creation. This value is hashed to\n * produce a partition assignment when the producer is created without a `partitionId`\n * @readonly\n */\n get partitionKey(): string | undefined {\n return this._partitionKey;\n }\n\n /**\n * The partitionId set during `EventDataBatch` creation.\n * If this value is set then partitionKey can not be set.\n * @readonly\n */\n get partitionId(): string | undefined {\n return this._partitionId;\n }\n\n /**\n * Size of the `EventDataBatch` instance after the events added to it have been\n * encoded into a single AMQP message.\n * @readonly\n */\n get sizeInBytes(): number {\n return this._sizeInBytes;\n }\n\n /**\n * Number of events in the `EventDataBatch` instance.\n * @readonly\n */\n get count(): number {\n return this._count;\n }\n\n /**\n * The publishing sequence number assigned to the first event in the batch at the time\n * the batch was successfully published.\n * If the producer was not configured to apply sequence numbering or if the batch\n * has not yet been successfully published, the value will be `undefined`.\n */\n get startingPublishedSequenceNumber(): number | undefined {\n return this._startingPublishSequenceNumber;\n }\n\n /**\n * Gets the \"message\" span contexts that were created when adding events to the batch.\n * @internal\n */\n get _messageSpanContexts(): TracingContext[] {\n return this._spanContexts;\n }\n\n /**\n * Generates an AMQP message that contains the provided encoded events and annotations.\n * @param encodedEvents - The already encoded events to include in the AMQP batch.\n * @param annotations - The message annotations to set on the batch.\n * @param publishingProps - Idempotent publishing properties used to decorate the events in the batch while sending.\n */\n private _generateBatch(\n encodedEvents: Buffer[],\n annotations: MessageAnnotations | undefined,\n publishingProps?: PartitionPublishingProperties,\n ): Buffer {\n if (this._isIdempotent && publishingProps) {\n // We need to decode the encoded events, add the idempotent annotations, and re-encode them.\n // We can't lazily encode the events because we rely on `message.encode` to capture the\n // byte length of anything not in `event.body`.\n // Events can't be decorated ahead of time because the publishing properties aren't known\n // until the events are being sent to the service.\n const decodedEvents = encodedEvents.map(message.decode) as unknown as RheaMessage[];\n const decoratedEvents = this._decorateRheaMessagesWithPublishingProps(\n decodedEvents,\n publishingProps,\n );\n encodedEvents = decoratedEvents.map(message.encode);\n }\n\n const batchEnvelope: RheaMessage = {\n body: message.data_sections(encodedEvents),\n };\n if (annotations) {\n batchEnvelope.message_annotations = annotations;\n }\n return message.encode(batchEnvelope);\n }\n\n /**\n * Uses the publishingProps to add idempotent properties as message annotations to rhea messages.\n */\n private _decorateRheaMessagesWithPublishingProps(\n events: RheaMessage[],\n publishingProps: PartitionPublishingProperties,\n ): RheaMessage[] {\n if (!this._isIdempotent) {\n return events;\n }\n\n const { lastPublishedSequenceNumber = 0, ownerLevel, producerGroupId } = publishingProps;\n const startingSequenceNumber = lastPublishedSequenceNumber + 1;\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel,\n producerGroupId,\n publishSequenceNumber: startingSequenceNumber + i,\n });\n }\n\n this._pendingStartingSequenceNumber = startingSequenceNumber;\n return events;\n }\n\n /**\n * Annotates a rhea message with placeholder idempotent properties if the batch is idempotent.\n * This is necessary so that we can accurately calculate the size of the batch while adding events.\n * Placeholder values are used because real values won't be known until we attempt to send the batch.\n */\n private _decorateRheaMessageWithPlaceholderIdempotencyProps(event: RheaMessage): RheaMessage {\n if (!this._isIdempotent) {\n return event;\n }\n\n if (!event.message_annotations) {\n event.message_annotations = {};\n }\n\n // Set placeholder values for these annotations.\n populateIdempotentMessageAnnotations(event, {\n isIdempotentPublishingEnabled: this._isIdempotent,\n ownerLevel: 0,\n publishSequenceNumber: 0,\n producerGroupId: 0,\n });\n\n return event;\n }\n\n /**\n * Generates the single AMQP message which is the result of encoding all the events\n * added into the `EventDataBatch` instance.\n *\n * This is not meant for the user to use directly.\n *\n * When the `EventDataBatch` instance is passed to the `send()` method on the `EventHubProducer`,\n * this single batched AMQP message is what gets sent over the wire to the service.\n * @readonly\n */\n _generateMessage(publishingProps?: PartitionPublishingProperties): Buffer {\n return this._generateBatch(this._encodedMessages, this._batchAnnotations, publishingProps);\n }\n\n /**\n * Sets startingPublishSequenceNumber to the pending publish sequence number.\n */\n _commitPublish(): void {\n this._startingPublishSequenceNumber = this._pendingStartingSequenceNumber;\n }\n\n /**\n * Tries to add an event data to the batch if permitted by the batch's size limit.\n * **NOTE**: Always remember to check the return value of this method, before calling it again\n * for the next event.\n *\n * @param eventData - An individual event data object.\n * @returns A boolean value indicating if the event data has been added to the batch or not.\n */\n public tryAdd(eventData: EventData | AmqpAnnotatedMessage, options: TryAddOptions = {}): boolean {\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"tryAdd\", \"eventData\", eventData);\n if (!isAmqpAnnotatedMessage(eventData)) {\n assertIsEventData(eventData);\n }\n\n const { entityPath, host } = this._context.config;\n const { event: instrumentedEvent, spanContext } = instrumentEventData(\n eventData,\n options,\n entityPath,\n host,\n );\n\n // Convert EventData to RheaMessage.\n const amqpMessage = toRheaMessage(instrumentedEvent, this._partitionKey);\n const originalAnnotations = amqpMessage.message_annotations && {\n ...amqpMessage.message_annotations,\n };\n this._decorateRheaMessageWithPlaceholderIdempotencyProps(amqpMessage);\n const encodedMessage = message.encode(amqpMessage);\n\n let currentSize = this._sizeInBytes;\n // The first time an event is added, we need to calculate\n // the overhead of creating an AMQP batch, including the\n // message_annotations that are taken from the 1st message.\n if (this.count === 0) {\n if (originalAnnotations) {\n this._batchAnnotations = originalAnnotations;\n }\n\n // Figure out the overhead of creating a batch by generating an empty batch\n // with the expected batch annotations.\n currentSize += this._generateBatch([], this._batchAnnotations).length;\n }\n\n const messageSize = encodedMessage.length;\n const messageOverhead =\n messageSize <= smallMessageMaxBytes ? smallMessageOverhead : largeMessageOverhead;\n currentSize += messageSize + messageOverhead;\n\n // Check if the size of the batch exceeds the maximum allowed size\n // once we add the new event to it.\n if (currentSize > this._maxSizeInBytes) {\n return false;\n }\n\n // The event will fit in the batch, so it is now safe to store it.\n this._encodedMessages.push(encodedMessage);\n if (spanContext) {\n this._spanContexts.push(spanContext);\n }\n\n this._sizeInBytes = currentSize;\n this._count++;\n return true;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"eventHubProducerClient.d.ts","sourceRoot":"","sources":["../../src/eventHubProducerClient.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,4BAA4B,EAC5B,sBAAsB,EACtB,6BAA6B,EAC7B,gBAAgB,EACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAwC,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAWtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAqB,MAA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;;;;OAMG;IACH,qBAAqB,CAAC,OAAO,GAAE,4BAAiC,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAO9F;;;;;;;OAOG;IACH,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAW7E;;;;;;;OAOG;IACH,sBAAsB,CACpB,WAAW,EAAE,MAAM,EACnB,OAAO,GAAE,6BAAkC,GAC1C,OAAO,CAAC,mBAAmB,CAAC;CAMhC"}
@@ -9,6 +9,7 @@ const core_util_1 = require("@azure/core-util");
9
9
  const typeGuards_js_1 = require("./util/typeGuards.js");
10
10
  const logger_js_1 = require("./logger.js");
11
11
  const error_js_1 = require("./util/error.js");
12
+ const eventData_js_1 = require("./eventData.js");
12
13
  const eventHubSender_js_1 = require("./eventHubSender.js");
13
14
  const tracing_js_1 = require("./diagnostics/tracing.js");
14
15
  const instrumentEventData_js_1 = require("./diagnostics/instrumentEventData.js");
@@ -191,6 +192,7 @@ class EventHubProducerClient {
191
192
  if (!Array.isArray(batch)) {
192
193
  batch = [batch];
193
194
  }
195
+ batch.forEach(eventData_js_1.assertIsEventData);
194
196
  if (batch.some((event) => (0, core_util_1.isDefined)(event._publishedSequenceNumber))) {
195
197
  throw new Error(error_js_1.idempotentSomeAlreadyPublished);
196
198
  }