@azure/event-hubs 6.0.2-alpha.20251014.1 → 6.0.2-alpha.20251021.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 (259) hide show
  1. package/dist/browser/batchingPartitionChannel.d.ts.map +1 -1
  2. package/dist/browser/batchingPartitionChannel.js +2 -1
  3. package/dist/browser/batchingPartitionChannel.js.map +1 -1
  4. package/dist/browser/connectionContext.d.ts.map +1 -1
  5. package/dist/browser/connectionContext.js +10 -4
  6. package/dist/browser/connectionContext.js.map +1 -1
  7. package/dist/browser/eventHubBufferedProducerClient.d.ts.map +1 -1
  8. package/dist/browser/eventHubBufferedProducerClient.js +2 -1
  9. package/dist/browser/eventHubBufferedProducerClient.js.map +1 -1
  10. package/dist/browser/eventHubConsumerClient.d.ts.map +1 -1
  11. package/dist/browser/eventHubConsumerClient.js +3 -6
  12. package/dist/browser/eventHubConsumerClient.js.map +1 -1
  13. package/dist/browser/eventHubProducerClient.d.ts.map +1 -1
  14. package/dist/browser/eventHubProducerClient.js +3 -6
  15. package/dist/browser/eventHubProducerClient.js.map +1 -1
  16. package/dist/browser/eventHubSender.d.ts.map +1 -1
  17. package/dist/browser/eventHubSender.js +6 -4
  18. package/dist/browser/eventHubSender.js.map +1 -1
  19. package/dist/browser/partitionReceiver.js +4 -4
  20. package/dist/browser/partitionReceiver.js.map +1 -1
  21. package/dist/browser/util/timerLoop.d.ts.map +1 -1
  22. package/dist/browser/util/timerLoop.js +12 -5
  23. package/dist/browser/util/timerLoop.js.map +1 -1
  24. package/dist/commonjs/batchingPartitionChannel.d.ts.map +1 -1
  25. package/dist/commonjs/batchingPartitionChannel.js +2 -1
  26. package/dist/commonjs/batchingPartitionChannel.js.map +1 -1
  27. package/dist/commonjs/connectionContext.d.ts.map +1 -1
  28. package/dist/commonjs/connectionContext.js +10 -4
  29. package/dist/commonjs/connectionContext.js.map +1 -1
  30. package/dist/commonjs/eventHubBufferedProducerClient.d.ts.map +1 -1
  31. package/dist/commonjs/eventHubBufferedProducerClient.js +2 -1
  32. package/dist/commonjs/eventHubBufferedProducerClient.js.map +1 -1
  33. package/dist/commonjs/eventHubConsumerClient.d.ts.map +1 -1
  34. package/dist/commonjs/eventHubConsumerClient.js +3 -6
  35. package/dist/commonjs/eventHubConsumerClient.js.map +1 -1
  36. package/dist/commonjs/eventHubProducerClient.d.ts.map +1 -1
  37. package/dist/commonjs/eventHubProducerClient.js +3 -6
  38. package/dist/commonjs/eventHubProducerClient.js.map +1 -1
  39. package/dist/commonjs/eventHubSender.d.ts.map +1 -1
  40. package/dist/commonjs/eventHubSender.js +6 -4
  41. package/dist/commonjs/eventHubSender.js.map +1 -1
  42. package/dist/commonjs/partitionReceiver.js +4 -4
  43. package/dist/commonjs/partitionReceiver.js.map +1 -1
  44. package/dist/commonjs/util/timerLoop.d.ts.map +1 -1
  45. package/dist/commonjs/util/timerLoop.js +12 -5
  46. package/dist/commonjs/util/timerLoop.js.map +1 -1
  47. package/dist/esm/batchingPartitionChannel.d.ts.map +1 -1
  48. package/dist/esm/batchingPartitionChannel.js +2 -1
  49. package/dist/esm/batchingPartitionChannel.js.map +1 -1
  50. package/dist/esm/connectionContext.d.ts.map +1 -1
  51. package/dist/esm/connectionContext.js +10 -4
  52. package/dist/esm/connectionContext.js.map +1 -1
  53. package/dist/esm/eventHubBufferedProducerClient.d.ts.map +1 -1
  54. package/dist/esm/eventHubBufferedProducerClient.js +2 -1
  55. package/dist/esm/eventHubBufferedProducerClient.js.map +1 -1
  56. package/dist/esm/eventHubConsumerClient.d.ts.map +1 -1
  57. package/dist/esm/eventHubConsumerClient.js +3 -6
  58. package/dist/esm/eventHubConsumerClient.js.map +1 -1
  59. package/dist/esm/eventHubProducerClient.d.ts.map +1 -1
  60. package/dist/esm/eventHubProducerClient.js +3 -6
  61. package/dist/esm/eventHubProducerClient.js.map +1 -1
  62. package/dist/esm/eventHubSender.d.ts.map +1 -1
  63. package/dist/esm/eventHubSender.js +6 -4
  64. package/dist/esm/eventHubSender.js.map +1 -1
  65. package/dist/esm/partitionReceiver.js +4 -4
  66. package/dist/esm/partitionReceiver.js.map +1 -1
  67. package/dist/esm/util/timerLoop.d.ts.map +1 -1
  68. package/dist/esm/util/timerLoop.js +12 -5
  69. package/dist/esm/util/timerLoop.js.map +1 -1
  70. package/dist/react-native/batchingPartitionChannel.d.ts +94 -0
  71. package/dist/react-native/batchingPartitionChannel.d.ts.map +1 -0
  72. package/dist/react-native/batchingPartitionChannel.js +255 -0
  73. package/dist/react-native/batchingPartitionChannel.js.map +1 -0
  74. package/dist/react-native/connectionContext.d.ts +108 -0
  75. package/dist/react-native/connectionContext.d.ts.map +1 -0
  76. package/dist/react-native/connectionContext.js +310 -0
  77. package/dist/react-native/connectionContext.js.map +1 -0
  78. package/dist/react-native/dataTransformer.d.ts +53 -0
  79. package/dist/react-native/dataTransformer.d.ts.map +1 -0
  80. package/dist/react-native/dataTransformer.js +133 -0
  81. package/dist/react-native/dataTransformer.js.map +1 -0
  82. package/dist/react-native/diagnostics/instrumentEventData.d.ts +28 -0
  83. package/dist/react-native/diagnostics/instrumentEventData.d.ts.map +1 -0
  84. package/dist/react-native/diagnostics/instrumentEventData.js +67 -0
  85. package/dist/react-native/diagnostics/instrumentEventData.js.map +1 -0
  86. package/dist/react-native/diagnostics/tracing.d.ts +19 -0
  87. package/dist/react-native/diagnostics/tracing.d.ts.map +1 -0
  88. package/dist/react-native/diagnostics/tracing.js +40 -0
  89. package/dist/react-native/diagnostics/tracing.js.map +1 -0
  90. package/dist/react-native/eventData.d.ts +295 -0
  91. package/dist/react-native/eventData.d.ts.map +1 -0
  92. package/dist/react-native/eventData.js +247 -0
  93. package/dist/react-native/eventData.js.map +1 -0
  94. package/dist/react-native/eventDataAdapter.d.ts +69 -0
  95. package/dist/react-native/eventDataAdapter.d.ts.map +1 -0
  96. package/dist/react-native/eventDataAdapter.js +38 -0
  97. package/dist/react-native/eventDataAdapter.js.map +1 -0
  98. package/dist/react-native/eventDataBatch.d.ts +225 -0
  99. package/dist/react-native/eventDataBatch.d.ts.map +1 -0
  100. package/dist/react-native/eventDataBatch.js +301 -0
  101. package/dist/react-native/eventDataBatch.js.map +1 -0
  102. package/dist/react-native/eventHubBufferedProducerClient.d.ts +323 -0
  103. package/dist/react-native/eventHubBufferedProducerClient.d.ts.map +1 -0
  104. package/dist/react-native/eventHubBufferedProducerClient.js +301 -0
  105. package/dist/react-native/eventHubBufferedProducerClient.js.map +1 -0
  106. package/dist/react-native/eventHubConsumerClient.d.ts +293 -0
  107. package/dist/react-native/eventHubConsumerClient.d.ts.map +1 -0
  108. package/dist/react-native/eventHubConsumerClient.js +336 -0
  109. package/dist/react-native/eventHubConsumerClient.js.map +1 -0
  110. package/dist/react-native/eventHubConsumerClientModels.d.ts +218 -0
  111. package/dist/react-native/eventHubConsumerClientModels.d.ts.map +1 -0
  112. package/dist/react-native/eventHubConsumerClientModels.js +4 -0
  113. package/dist/react-native/eventHubConsumerClientModels.js.map +1 -0
  114. package/dist/react-native/eventHubProducerClient.d.ts +299 -0
  115. package/dist/react-native/eventHubProducerClient.d.ts.map +1 -0
  116. package/dist/react-native/eventHubProducerClient.js +366 -0
  117. package/dist/react-native/eventHubProducerClient.js.map +1 -0
  118. package/dist/react-native/eventHubSender.d.ts +227 -0
  119. package/dist/react-native/eventHubSender.d.ts.map +1 -0
  120. package/dist/react-native/eventHubSender.js +626 -0
  121. package/dist/react-native/eventHubSender.js.map +1 -0
  122. package/dist/react-native/eventPosition.d.ts +73 -0
  123. package/dist/react-native/eventPosition.d.ts.map +1 -0
  124. package/dist/react-native/eventPosition.js +121 -0
  125. package/dist/react-native/eventPosition.js.map +1 -0
  126. package/dist/react-native/eventProcessor.d.ts +232 -0
  127. package/dist/react-native/eventProcessor.d.ts.map +1 -0
  128. package/dist/react-native/eventProcessor.js +389 -0
  129. package/dist/react-native/eventProcessor.js.map +1 -0
  130. package/dist/react-native/eventhubConnectionConfig.d.ts +96 -0
  131. package/dist/react-native/eventhubConnectionConfig.d.ts.map +1 -0
  132. package/dist/react-native/eventhubConnectionConfig.js +98 -0
  133. package/dist/react-native/eventhubConnectionConfig.js.map +1 -0
  134. package/dist/react-native/impl/awaitableQueue.d.ts +25 -0
  135. package/dist/react-native/impl/awaitableQueue.d.ts.map +1 -0
  136. package/dist/react-native/impl/awaitableQueue.js +51 -0
  137. package/dist/react-native/impl/awaitableQueue.js.map +1 -0
  138. package/dist/react-native/impl/partitionAssigner.d.ts +29 -0
  139. package/dist/react-native/impl/partitionAssigner.d.ts.map +1 -0
  140. package/dist/react-native/impl/partitionAssigner.js +52 -0
  141. package/dist/react-native/impl/partitionAssigner.js.map +1 -0
  142. package/dist/react-native/impl/partitionGate.d.ts +27 -0
  143. package/dist/react-native/impl/partitionGate.d.ts.map +1 -0
  144. package/dist/react-native/impl/partitionGate.js +38 -0
  145. package/dist/react-native/impl/partitionGate.js.map +1 -0
  146. package/dist/react-native/impl/partitionKeyToIdMapper.d.ts +6 -0
  147. package/dist/react-native/impl/partitionKeyToIdMapper.d.ts.map +1 -0
  148. package/dist/react-native/impl/partitionKeyToIdMapper.js +111 -0
  149. package/dist/react-native/impl/partitionKeyToIdMapper.js.map +1 -0
  150. package/dist/react-native/inMemoryCheckpointStore.d.ts +44 -0
  151. package/dist/react-native/inMemoryCheckpointStore.d.ts.map +1 -0
  152. package/dist/react-native/inMemoryCheckpointStore.js +94 -0
  153. package/dist/react-native/inMemoryCheckpointStore.js.map +1 -0
  154. package/dist/react-native/index.d.ts +21 -0
  155. package/dist/react-native/index.d.ts.map +1 -0
  156. package/dist/react-native/index.js +12 -0
  157. package/dist/react-native/index.js.map +1 -0
  158. package/dist/react-native/loadBalancerStrategies/balancedStrategy.d.ts +30 -0
  159. package/dist/react-native/loadBalancerStrategies/balancedStrategy.d.ts.map +1 -0
  160. package/dist/react-native/loadBalancerStrategies/balancedStrategy.js +40 -0
  161. package/dist/react-native/loadBalancerStrategies/balancedStrategy.js.map +1 -0
  162. package/dist/react-native/loadBalancerStrategies/greedyStrategy.d.ts +24 -0
  163. package/dist/react-native/loadBalancerStrategies/greedyStrategy.d.ts.map +1 -0
  164. package/dist/react-native/loadBalancerStrategies/greedyStrategy.js +29 -0
  165. package/dist/react-native/loadBalancerStrategies/greedyStrategy.js.map +1 -0
  166. package/dist/react-native/loadBalancerStrategies/loadBalancingStrategy.d.ts +28 -0
  167. package/dist/react-native/loadBalancerStrategies/loadBalancingStrategy.d.ts.map +1 -0
  168. package/dist/react-native/loadBalancerStrategies/loadBalancingStrategy.js +245 -0
  169. package/dist/react-native/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -0
  170. package/dist/react-native/loadBalancerStrategies/unbalancedStrategy.d.ts +20 -0
  171. package/dist/react-native/loadBalancerStrategies/unbalancedStrategy.d.ts.map +1 -0
  172. package/dist/react-native/loadBalancerStrategies/unbalancedStrategy.js +22 -0
  173. package/dist/react-native/loadBalancerStrategies/unbalancedStrategy.js.map +1 -0
  174. package/dist/react-native/logger.d.ts +37 -0
  175. package/dist/react-native/logger.d.ts.map +1 -0
  176. package/dist/react-native/logger.js +56 -0
  177. package/dist/react-native/logger.js.map +1 -0
  178. package/dist/react-native/managementClient.d.ts +145 -0
  179. package/dist/react-native/managementClient.d.ts.map +1 -0
  180. package/dist/react-native/managementClient.js +305 -0
  181. package/dist/react-native/managementClient.js.map +1 -0
  182. package/dist/react-native/models/private.d.ts +185 -0
  183. package/dist/react-native/models/private.d.ts.map +1 -0
  184. package/dist/react-native/models/private.js +4 -0
  185. package/dist/react-native/models/private.js.map +1 -0
  186. package/dist/react-native/models/public.d.ts +240 -0
  187. package/dist/react-native/models/public.d.ts.map +1 -0
  188. package/dist/react-native/models/public.js +18 -0
  189. package/dist/react-native/models/public.js.map +1 -0
  190. package/dist/react-native/package.json +3 -0
  191. package/dist/react-native/partitionProcessor.d.ts +134 -0
  192. package/dist/react-native/partitionProcessor.d.ts.map +1 -0
  193. package/dist/react-native/partitionProcessor.js +137 -0
  194. package/dist/react-native/partitionProcessor.js.map +1 -0
  195. package/dist/react-native/partitionPump.d.ts +38 -0
  196. package/dist/react-native/partitionPump.d.ts.map +1 -0
  197. package/dist/react-native/partitionPump.js +175 -0
  198. package/dist/react-native/partitionPump.js.map +1 -0
  199. package/dist/react-native/partitionReceiver.d.ts +82 -0
  200. package/dist/react-native/partitionReceiver.d.ts.map +1 -0
  201. package/dist/react-native/partitionReceiver.js +335 -0
  202. package/dist/react-native/partitionReceiver.js.map +1 -0
  203. package/dist/react-native/pumpManager.d.ts +72 -0
  204. package/dist/react-native/pumpManager.d.ts.map +1 -0
  205. package/dist/react-native/pumpManager.js +120 -0
  206. package/dist/react-native/pumpManager.js.map +1 -0
  207. package/dist/react-native/util/connectionStringUtils.d.ts +52 -0
  208. package/dist/react-native/util/connectionStringUtils.d.ts.map +1 -0
  209. package/dist/react-native/util/connectionStringUtils.js +48 -0
  210. package/dist/react-native/util/connectionStringUtils.js.map +1 -0
  211. package/dist/react-native/util/constants.d.ts +25 -0
  212. package/dist/react-native/util/constants.d.ts.map +1 -0
  213. package/dist/react-native/util/constants.js +27 -0
  214. package/dist/react-native/util/constants.js.map +1 -0
  215. package/dist/react-native/util/delayWithoutThrow.d.ts +8 -0
  216. package/dist/react-native/util/delayWithoutThrow.d.ts.map +1 -0
  217. package/dist/react-native/util/delayWithoutThrow.js +17 -0
  218. package/dist/react-native/util/delayWithoutThrow.js.map +1 -0
  219. package/dist/react-native/util/error.d.ts +39 -0
  220. package/dist/react-native/util/error.d.ts.map +1 -0
  221. package/dist/react-native/util/error.js +103 -0
  222. package/dist/react-native/util/error.js.map +1 -0
  223. package/dist/react-native/util/getPromiseParts.d.ts +10 -0
  224. package/dist/react-native/util/getPromiseParts.d.ts.map +1 -0
  225. package/dist/react-native/util/getPromiseParts.js +20 -0
  226. package/dist/react-native/util/getPromiseParts.js.map +1 -0
  227. package/dist/react-native/util/operationOptions.d.ts +16 -0
  228. package/dist/react-native/util/operationOptions.d.ts.map +1 -0
  229. package/dist/react-native/util/operationOptions.js +4 -0
  230. package/dist/react-native/util/operationOptions.js.map +1 -0
  231. package/dist/react-native/util/parseEndpoint.d.ts +11 -0
  232. package/dist/react-native/util/parseEndpoint.d.ts.map +1 -0
  233. package/dist/react-native/util/parseEndpoint.js +17 -0
  234. package/dist/react-native/util/parseEndpoint.js.map +1 -0
  235. package/dist/react-native/util/retries.d.ts +6 -0
  236. package/dist/react-native/util/retries.d.ts.map +1 -0
  237. package/dist/react-native/util/retries.js +13 -0
  238. package/dist/react-native/util/retries.js.map +1 -0
  239. package/dist/react-native/util/runtimeInfo-react-native.d.mts.map +1 -0
  240. package/dist/react-native/util/runtimeInfo-react-native.mjs.map +1 -0
  241. package/dist/react-native/util/runtimeInfo.d.ts +6 -0
  242. package/dist/react-native/util/runtimeInfo.js +20 -0
  243. package/dist/react-native/util/timerLoop.d.ts +26 -0
  244. package/dist/react-native/util/timerLoop.d.ts.map +1 -0
  245. package/dist/react-native/util/timerLoop.js +34 -0
  246. package/dist/react-native/util/timerLoop.js.map +1 -0
  247. package/dist/react-native/util/typeGuards.d.ts +8 -0
  248. package/dist/react-native/util/typeGuards.d.ts.map +1 -0
  249. package/dist/react-native/util/typeGuards.js +12 -0
  250. package/dist/react-native/util/typeGuards.js.map +1 -0
  251. package/dist/react-native/util/utils.d.ts +7 -0
  252. package/dist/react-native/util/utils.d.ts.map +1 -0
  253. package/dist/react-native/util/utils.js +13 -0
  254. package/dist/react-native/util/utils.js.map +1 -0
  255. package/dist/react-native/withAuth.d.ts +25 -0
  256. package/dist/react-native/withAuth.d.ts.map +1 -0
  257. package/dist/react-native/withAuth.js +84 -0
  258. package/dist/react-native/withAuth.js.map +1 -0
  259. package/package.json +16 -11
@@ -0,0 +1,310 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { ConnectionEvents } from "rhea-promise";
4
+ import { ConnectionConfig, ConnectionContextBase, Constants, createSasTokenProvider, } from "@azure/core-amqp";
5
+ import { parseEventHubConnectionString } from "./util/connectionStringUtils.js";
6
+ import { ManagementClient } from "./managementClient.js";
7
+ import { isNamedKeyCredential, isSASCredential } from "@azure/core-auth";
8
+ import { logErrorStackTrace, logger } from "./logger.js";
9
+ import { EventHubConnectionConfig } from "./eventhubConnectionConfig.js";
10
+ import { getRuntimeInfo } from "./util/runtimeInfo.js";
11
+ import { isCredential } from "./util/typeGuards.js";
12
+ import { packageJsonInfo } from "./util/constants.js";
13
+ import { createAbortablePromise } from "@azure/core-util";
14
+ /**
15
+ * @internal
16
+ */
17
+ export var ConnectionContext;
18
+ (function (ConnectionContext) {
19
+ /**
20
+ * The user agent string for the EventHubs client.
21
+ * See guideline at https://github.com/Azure/azure-sdk/blob/main/docs/design/Telemetry.mdk
22
+ */
23
+ const userAgent = `azsdk-js-azureeventhubs/${packageJsonInfo.version} (${getRuntimeInfo()})`;
24
+ function getUserAgent(options) {
25
+ const finalUserAgent = options.userAgent ? `${userAgent},${options.userAgent}` : userAgent;
26
+ if (finalUserAgent.length > Constants.maxUserAgentLength) {
27
+ throw new Error(`The user-agent string cannot be more than ${Constants.maxUserAgentLength} characters in length.` +
28
+ `The given user-agent string is: ${finalUserAgent} with length: ${finalUserAgent.length}`);
29
+ }
30
+ return finalUserAgent;
31
+ }
32
+ ConnectionContext.getUserAgent = getUserAgent;
33
+ function create(config, tokenCredential, options) {
34
+ if (!options)
35
+ options = {};
36
+ config.webSocket = options.webSocketOptions && options.webSocketOptions.webSocket;
37
+ config.webSocketEndpointPath = "$servicebus/websocket";
38
+ config.webSocketConstructorOptions =
39
+ options.webSocketOptions && options.webSocketOptions.webSocketConstructorOptions;
40
+ const parameters = {
41
+ config: config,
42
+ // re-enabling this will be a post-GA discussion.
43
+ // dataTransformer: options.dataTransformer,
44
+ isEntityPathRequired: true,
45
+ connectionProperties: {
46
+ product: "MSJSClient",
47
+ userAgent: getUserAgent(options),
48
+ version: packageJsonInfo.version,
49
+ },
50
+ };
51
+ // Let us create the base context and then add EventHub specific ConnectionContext properties.
52
+ const connectionContext = ConnectionContextBase.create(parameters);
53
+ connectionContext.tokenCredential = tokenCredential;
54
+ connectionContext.wasConnectionCloseCalled = false;
55
+ connectionContext.senders = {};
56
+ connectionContext.receivers = {};
57
+ const mOptions = {
58
+ address: options.managementSessionAddress,
59
+ audience: options.managementSessionAudience,
60
+ };
61
+ connectionContext.managementSession = new ManagementClient(connectionContext, mOptions);
62
+ let waitForConnectionRefreshResolve;
63
+ let waitForConnectionRefreshPromise;
64
+ Object.assign(connectionContext, {
65
+ isConnectionClosing() {
66
+ // When the connection is not open, but the remote end is open,
67
+ // then the rhea connection is in the process of terminating.
68
+ return Boolean(!this.connection.isOpen() && this.connection.isRemoteOpen());
69
+ },
70
+ async readyToOpenLink(optionsArg) {
71
+ // Check that the connection isn't in the process of closing.
72
+ // This can happen when the idle timeout has been reached but
73
+ // the underlying socket is waiting to be destroyed.
74
+ if (this.isConnectionClosing()) {
75
+ // Wait for the disconnected event that indicates the underlying socket has closed.
76
+ await this.waitForDisconnectedEvent(optionsArg);
77
+ }
78
+ // Wait for the connection to be reset.
79
+ await this.waitForConnectionReset();
80
+ },
81
+ waitForDisconnectedEvent(optionsArg) {
82
+ return createAbortablePromise((resolve) => {
83
+ logger.verbose(`[${this.connectionId}] Attempting to reinitialize connection` +
84
+ ` but the connection is in the process of closing.` +
85
+ ` Waiting for the disconnect event before continuing.`);
86
+ this.connection.once(ConnectionEvents.disconnected, resolve);
87
+ }, optionsArg);
88
+ },
89
+ waitForConnectionReset() {
90
+ // Check if the connection is currently in the process of disconnecting.
91
+ if (waitForConnectionRefreshPromise) {
92
+ return waitForConnectionRefreshPromise;
93
+ }
94
+ return Promise.resolve();
95
+ },
96
+ async close() {
97
+ try {
98
+ if (this.connection.isOpen()) {
99
+ // Close all the senders.
100
+ await Promise.all(Object.keys(connectionContext.senders).map((name) => connectionContext.senders[name]?.close().catch(() => {
101
+ /* error already logged, swallow it here */
102
+ })));
103
+ // Close all the receivers.
104
+ await Promise.all(Object.keys(connectionContext.receivers).map((name) => connectionContext.receivers[name]?.close().catch(() => {
105
+ /* error already logged, swallow it here */
106
+ })));
107
+ // Close the cbs session;
108
+ await this.cbsSession.close();
109
+ // Close the management session
110
+ await this.managementSession?.close();
111
+ await this.connection.close();
112
+ this.wasConnectionCloseCalled = true;
113
+ logger.info("Closed the amqp connection '%s' on the client.", this.connectionId);
114
+ }
115
+ }
116
+ catch (err) {
117
+ const errorDescription = err instanceof Error ? `${err.name}: ${err.message}` : JSON.stringify(err);
118
+ logger.warning(`An error occurred while closing the connection "${this.connectionId}":\n${errorDescription}`);
119
+ logErrorStackTrace(err);
120
+ throw err;
121
+ }
122
+ },
123
+ });
124
+ // Define listeners to be added to the connection object for
125
+ // "connection_open" and "connection_error" events.
126
+ const onConnectionOpen = () => {
127
+ connectionContext.wasConnectionCloseCalled = false;
128
+ logger.verbose("[%s] setting 'wasConnectionCloseCalled' property of connection context to %s.", connectionContext.connection.id, connectionContext.wasConnectionCloseCalled);
129
+ };
130
+ async function handleDisconnection(context) {
131
+ if (waitForConnectionRefreshPromise) {
132
+ return;
133
+ }
134
+ waitForConnectionRefreshPromise = new Promise((resolve) => {
135
+ waitForConnectionRefreshResolve = resolve;
136
+ });
137
+ try {
138
+ logger.verbose("[%s] 'disconnected' event occurred on the amqp connection.", connectionContext.connection.id);
139
+ if (context.connection && context.connection.error) {
140
+ logger.verbose("[%s] Accompanying error on the context.connection: %O", connectionContext.connection.id, context.connection.error);
141
+ }
142
+ if (context.error) {
143
+ logger.verbose("[%s] Accompanying error on the context: %O", connectionContext.connection.id, context.error);
144
+ }
145
+ const state = {
146
+ wasConnectionCloseCalled: connectionContext.wasConnectionCloseCalled,
147
+ numSenders: Object.keys(connectionContext.senders).length,
148
+ numReceivers: Object.keys(connectionContext.receivers).length,
149
+ };
150
+ logger.verbose("[%s] Closing all open senders and receivers in the state: %O", connectionContext.connection.id, state);
151
+ // Clear internal map maintained by rhea to avoid reconnecting of old links once the
152
+ // connection is back up.
153
+ connectionContext.connection.removeAllSessions();
154
+ // Close the cbs session to ensure all the event handlers are released.
155
+ await connectionContext.cbsSession?.close().catch(() => {
156
+ /* error already logged, swallow it here */
157
+ });
158
+ // Close the management session to ensure all the event handlers are released.
159
+ await connectionContext.managementSession?.close().catch(() => {
160
+ /* error already logged, swallow it here */
161
+ });
162
+ // Close all senders and receivers to ensure clean up of timers & other resources.
163
+ if (state.numSenders || state.numReceivers) {
164
+ await Promise.all(Object.keys(connectionContext.senders).map((name) => connectionContext.senders[name]?.close().catch(() => {
165
+ /* error already logged, swallow it here */
166
+ })));
167
+ await Promise.all(Object.keys(connectionContext.receivers).map((name) => connectionContext.receivers[name]?.close().catch(() => {
168
+ /* error already logged, swallow it here */
169
+ })));
170
+ }
171
+ }
172
+ catch (err) {
173
+ logger.verbose(`[${connectionContext.connectionId}] An error occurred while closing the connection in 'disconnected'. %O`, err);
174
+ }
175
+ try {
176
+ await refreshConnection(connectionContext);
177
+ }
178
+ catch (err) {
179
+ logger.verbose(`[${connectionContext.connectionId}] An error occurred while refreshing the connection in 'disconnected'. %O`, err);
180
+ }
181
+ finally {
182
+ waitForConnectionRefreshResolve();
183
+ waitForConnectionRefreshPromise = undefined;
184
+ }
185
+ }
186
+ const onDisconnected = (context) => {
187
+ // Fire-and-forget async operation with error handling
188
+ handleDisconnection(context).catch((err) => {
189
+ logger.verbose(`[${connectionContext.connectionId}] Unhandled error in 'disconnected' event handler. %O`, err);
190
+ });
191
+ };
192
+ const protocolError = (context) => {
193
+ logger.verbose("[%s] 'protocol_error' event occurred on the amqp connection.", connectionContext.connection.id);
194
+ if (context.connection && context.connection.error) {
195
+ logger.verbose("[%s] Accompanying error on the context.connection: %O", connectionContext.connection.id, context.connection && context.connection.error);
196
+ }
197
+ if (context.error) {
198
+ logger.verbose("[%s] Accompanying error on the context: %O", connectionContext.connection.id, context.error);
199
+ }
200
+ };
201
+ const error = (context) => {
202
+ logger.verbose("[%s] 'error' event occurred on the amqp connection.", connectionContext.connection.id);
203
+ if (context.connection && context.connection.error) {
204
+ logger.verbose("[%s] Accompanying error on the context.connection: %O", connectionContext.connection.id, context.connection && context.connection.error);
205
+ }
206
+ if (context.error) {
207
+ logger.verbose("[%s] Accompanying error on the context: %O", connectionContext.connection.id, context.error);
208
+ }
209
+ };
210
+ function addConnectionListeners(connection) {
211
+ // Add listeners on the connection object.
212
+ connection.on(ConnectionEvents.connectionOpen, onConnectionOpen);
213
+ connection.on(ConnectionEvents.disconnected, onDisconnected);
214
+ connection.on(ConnectionEvents.protocolError, protocolError);
215
+ connection.on(ConnectionEvents.error, error);
216
+ }
217
+ function cleanConnectionContext(context) {
218
+ // Remove listeners from the connection object.
219
+ context.connection.removeListener(ConnectionEvents.connectionOpen, onConnectionOpen);
220
+ context.connection.removeListener(ConnectionEvents.disconnected, onDisconnected);
221
+ context.connection.removeListener(ConnectionEvents.protocolError, protocolError);
222
+ context.connection.removeListener(ConnectionEvents.error, error);
223
+ // Close the connection
224
+ return context.connection.close();
225
+ }
226
+ async function refreshConnection(context) {
227
+ const originalConnectionId = context.connectionId;
228
+ try {
229
+ await cleanConnectionContext(context);
230
+ }
231
+ catch (err) {
232
+ logger.verbose(`[${context.connectionId}] There was an error closing the connection before reconnecting: %O`, err);
233
+ }
234
+ // Create a new connection, id, locks, and cbs client.
235
+ context.refreshConnection();
236
+ addConnectionListeners(context.connection);
237
+ logger.verbose(`The connection "${originalConnectionId}" has been updated to "${context.connectionId}".`);
238
+ }
239
+ addConnectionListeners(connectionContext.connection);
240
+ logger.verbose("[%s] Created connection context successfully.", connectionContext.connectionId);
241
+ return connectionContext;
242
+ }
243
+ ConnectionContext.create = create;
244
+ })(ConnectionContext || (ConnectionContext = {}));
245
+ /**
246
+ * Helper method to create a ConnectionContext from the input passed to either
247
+ * EventHubProducerClient or EventHubConsumerClient constructors
248
+ *
249
+ * @internal
250
+ */
251
+ export function createConnectionContext(hostOrConnectionString, eventHubNameOrOptions, credentialOrOptions, options) {
252
+ let connectionString;
253
+ let config;
254
+ let credential;
255
+ hostOrConnectionString = String(hostOrConnectionString);
256
+ if (!isCredential(credentialOrOptions)) {
257
+ const parsedCS = parseEventHubConnectionString(hostOrConnectionString);
258
+ if (!(parsedCS.eventHubName ||
259
+ (typeof eventHubNameOrOptions === "string" && eventHubNameOrOptions))) {
260
+ throw new TypeError(`Either provide "eventHubName" or the "connectionString": "${hostOrConnectionString}", ` +
261
+ `must contain "EntityPath=<your-event-hub-name>".`);
262
+ }
263
+ if (parsedCS.eventHubName &&
264
+ typeof eventHubNameOrOptions === "string" &&
265
+ eventHubNameOrOptions &&
266
+ parsedCS.eventHubName !== eventHubNameOrOptions) {
267
+ throw new TypeError(`The entity path "${parsedCS.eventHubName}" in connectionString: "${hostOrConnectionString}" ` +
268
+ `doesn't match with eventHubName: "${eventHubNameOrOptions}".`);
269
+ }
270
+ connectionString = hostOrConnectionString;
271
+ if (typeof eventHubNameOrOptions !== "string") {
272
+ // connectionstring and/or options were passed to constructor
273
+ config = EventHubConnectionConfig.create(connectionString);
274
+ options = eventHubNameOrOptions;
275
+ }
276
+ else {
277
+ // connectionstring, eventHubName and/or options were passed to constructor
278
+ const eventHubName = eventHubNameOrOptions;
279
+ config = EventHubConnectionConfig.create(connectionString, eventHubName);
280
+ options = credentialOrOptions;
281
+ }
282
+ const parsed = parseEventHubConnectionString(connectionString);
283
+ // Since connectionString was passed, create a TokenProvider.
284
+ credential = createSasTokenProvider(parsed);
285
+ }
286
+ else {
287
+ // host, eventHubName, a TokenCredential and/or options were passed to constructor
288
+ const eventHubName = eventHubNameOrOptions;
289
+ let host = hostOrConnectionString;
290
+ if (isNamedKeyCredential(credentialOrOptions) || isSASCredential(credentialOrOptions)) {
291
+ credential = createSasTokenProvider(credentialOrOptions);
292
+ }
293
+ else {
294
+ credential = credentialOrOptions;
295
+ }
296
+ if (!eventHubName) {
297
+ throw new TypeError(`"eventHubName" is missing`);
298
+ }
299
+ if (!host.endsWith("/"))
300
+ host += "/";
301
+ connectionString = `Endpoint=sb://${host};SharedAccessKeyName=defaultKeyName;SharedAccessKey=defaultKeyValue;EntityPath=${eventHubName}`;
302
+ config = EventHubConnectionConfig.create(connectionString);
303
+ }
304
+ if (options?.customEndpointAddress) {
305
+ EventHubConnectionConfig.setCustomEndpointAddress(config, options.customEndpointAddress);
306
+ }
307
+ ConnectionConfig.validate(config);
308
+ return ConnectionContext.create(config, credential, options);
309
+ }
310
+ //# sourceMappingURL=connectionContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connectionContext.js","sourceRoot":"","sources":["../../src/connectionContext.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,SAAS,EACT,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAEhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAGzE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAwG1D;;GAEG;AACH,MAAM,KAAW,iBAAiB,CA4UjC;AA5UD,WAAiB,iBAAiB;IAChC;;;OAGG;IACH,MAAM,SAAS,GAAW,2BACxB,eAAe,CAAC,OAClB,KAAK,cAAc,EAAE,GAAG,CAAC;IAEzB,SAAgB,Y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A6D;QAC7D,UAAU,GAAG,sBAAsB,CAAC,MAAM,CAAC,CAAC;IAC9C,CAAC;SAAM,CAAC;QACN,kFAAkF;QAClF,MAAM,YAAY,GAAG,qBAAqB,CAAC;QAC3C,IAAI,IAAI,GAAG,sBAAsB,CAAC;QAClC,IAAI,oBAAoB,CAAC,mBAAmB,CAAC,IAAI,eAAe,CAAC,mBAAmB,CAAC,EAAE,CAAC;YACtF,UAAU,GAAG,sBAAsB,CAAC,mBAAmB,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,UAAU,GAAG,mBAAmB,CAAC;QACnC,CAAC;QACD,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,MAAM,IAAI,SAAS,CAAC,2BAA2B,CAAC,CAAC;QACnD,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;QACrC,gBAAgB,GAAG,iBAAiB,IAAI,kFAAkF,YAAY,EAAE,CAAC;QACzI,MAAM,GAAG,wBAAwB,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI,OAAO,EAAE,qBAAqB,EAAE,CAAC;QACnC,wBAAwB,CAAC,wBAAwB,CAAC,MAAM,EAAE,OAAO,CAAC,qBAAqB,CAAC,CAAC;IAC3F,CAAC;IAED,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAElC,OAAO,iBAAiB,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable no-inner-declarations */\n\nimport type { Connection, Dictionary, EventContext, OnAmqpEvent } from \"rhea-promise\";\nimport { ConnectionEvents } from \"rhea-promise\";\nimport type { CreateConnectionContextBaseParameters, SasTokenProvider } from \"@azure/core-amqp\";\nimport {\n ConnectionConfig,\n ConnectionContextBase,\n Constants,\n createSasTokenProvider,\n} from \"@azure/core-amqp\";\nimport type { EventHubConnectionStringProperties } from \"./util/connectionStringUtils.js\";\nimport { parseEventHubConnectionString } from \"./util/connectionStringUtils.js\";\nimport type { ManagementClientOptions } from \"./managementClient.js\";\nimport { ManagementClient } from \"./managementClient.js\";\nimport type { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport { isNamedKeyCredential, isSASCredential } from \"@azure/core-auth\";\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport type { EventHubClientOptions } from \"./models/public.js\";\nimport { EventHubConnectionConfig } from \"./eventhubConnectionConfig.js\";\nimport type { PartitionReceiver } from \"./partitionReceiver.js\";\nimport type { EventHubSender } from \"./eventHubSender.js\";\nimport { getRuntimeInfo } from \"./util/runtimeInfo.js\";\nimport { isCredential } from \"./util/typeGuards.js\";\nimport { packageJsonInfo } from \"./util/constants.js\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { createAbortablePromise } from \"@azure/core-util\";\n\n/**\n * @internal\n * Provides contextual information like the underlying amqp connection, cbs session, management session,\n * tokenProvider, senders, receivers, etc. about the EventHub client.\n */\nexport interface ConnectionContext extends ConnectionContextBase {\n /**\n * The EventHub connection config that is created after\n * parsing the connection string.\n */\n readonly config: EventHubConnectionConfig;\n /**\n * The credential to be used for Authentication.\n * Default value: SasTokenProvider.\n */\n tokenCredential: SasTokenProvider | TokenCredential;\n /**\n * Indicates whether the close() method was\n * called on theconnection object.\n */\n wasConnectionCloseCalled: boolean;\n /**\n * A dictionary of the EventHub Receivers associated with this client.\n */\n receivers: Dictionary<PartitionReceiver>;\n /**\n * A dictionary of the EventHub Senders associated with this client.\n */\n senders: Dictionary<EventHubSender>;\n /**\n * A reference to the management session ($management endpoint) on\n * the underlying amqp connection for the EventHub Client.\n */\n managementSession?: ManagementClient;\n /**\n * Function returning a promise that resolves once the connectionContext is ready to open an AMQP link.\n * ConnectionContext will be ready to open an AMQP link when:\n * - The AMQP connection is already open on both sides.\n * - The AMQP connection has been closed or disconnected. In this case, a new AMQP connection is expected\n * to be created first.\n * An AMQP link cannot be opened if the AMQP connection\n * is in the process of closing or disconnecting.\n */\n readyToOpenLink(options?: { abortSignal?: AbortSignalLike }): Promise<void>;\n /**\n * Closes all AMQP links, sessions and connection.\n */\n close(): Promise<void>;\n}\n\n/**\n * Describes the members on the ConnectionContext that are only\n * used by it internally.\n * @internal\n */\nexport interface ConnectionContextInternalMembers extends ConnectionContext {\n /**\n * Indicates whether the connection is in the process of closing.\n * When this returns `true`, a `disconnected` event will be received\n * after the connection is closed.\n *\n */\n isConnectionClosing(): boolean;\n /**\n * Resolves once the context's connection emits a `disconnected` event.\n */\n waitForDisconnectedEvent(options?: { abortSignal?: AbortSignalLike }): Promise<void>;\n /**\n * Resolves once the connection has finished being reset.\n * Connections are reset as part of reacting to a `disconnected` event.\n */\n waitForConnectionReset(): Promise<void>;\n}\n\n/**\n * @internal\n */\nexport interface ConnectionContextOptions extends EventHubClientOptions {\n managementSessionAddress?: string;\n managementSessionAudience?: string;\n}\n\n/**\n * Helper type to get the names of all the functions on an object.\n */\ntype FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; // eslint-disable-line @typescript-eslint/no-unsafe-function-type\n/**\n * Helper type to get the types of all the functions on an object.\n */\ntype FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;\n/**\n * Helper type to get the types of all the functions on ConnectionContext\n * and the internal methods from ConnectionContextInternalMembers.\n * Note that this excludes the functions that ConnectionContext inherits.\n * Each function also has its `this` type set as `ConnectionContext`.\n */\ntype ConnectionContextMethods = Omit<\n FunctionProperties<ConnectionContextInternalMembers>,\n FunctionPropertyNames<ConnectionContextBase>\n> &\n ThisType<ConnectionContextInternalMembers>;\n\n/**\n * @internal\n */\nexport namespace ConnectionContext {\n /**\n * The user agent string for the EventHubs client.\n * See guideline at https://github.com/Azure/azure-sdk/blob/main/docs/design/Telemetry.mdk\n */\n const userAgent: string = `azsdk-js-azureeventhubs/${\n packageJsonInfo.version\n } (${getRuntimeInfo()})`;\n\n export function getUserAgent(options: ConnectionContextOptions): string {\n const finalUserAgent = options.userAgent ? `${userAgent},${options.userAgent}` : userAgent;\n if (finalUserAgent.length > Constants.maxUserAgentLength) {\n throw new Error(\n `The user-agent string cannot be more than ${Constants.maxUserAgentLength} characters in length.` +\n `The given user-agent string is: ${finalUserAgent} with length: ${finalUserAgent.length}`,\n );\n }\n return finalUserAgent;\n }\n\n export function create(\n config: EventHubConnectionConfig,\n tokenCredential: SasTokenProvider | TokenCredential,\n options?: ConnectionContextOptions,\n ): ConnectionContext {\n if (!options) options = {};\n\n config.webSocket = options.webSocketOptions && options.webSocketOptions.webSocket;\n config.webSocketEndpointPath = \"$servicebus/websocket\";\n config.webSocketConstructorOptions =\n options.webSocketOptions && options.webSocketOptions.webSocketConstructorOptions;\n\n const parameters: CreateConnectionContextBaseParameters = {\n config: config,\n // re-enabling this will be a post-GA discussion.\n // dataTransformer: options.dataTransformer,\n isEntityPathRequired: true,\n connectionProperties: {\n product: \"MSJSClient\",\n userAgent: getUserAgent(options),\n version: packageJsonInfo.version,\n },\n };\n // Let us create the base context and then add EventHub specific ConnectionContext properties.\n const connectionContext = ConnectionContextBase.create(parameters) as ConnectionContext;\n connectionContext.tokenCredential = tokenCredential;\n connectionContext.wasConnectionCloseCalled = false;\n connectionContext.senders = {};\n connectionContext.receivers = {};\n const mOptions: ManagementClientOptions = {\n address: options.managementSessionAddress,\n audience: options.managementSessionAudience,\n };\n connectionContext.managementSession = new ManagementClient(connectionContext, mOptions);\n\n let waitForConnectionRefreshResolve: () => void;\n let waitForConnectionRefreshPromise: Promise<void> | undefined;\n\n Object.assign<ConnectionContext, ConnectionContextMethods>(connectionContext, {\n isConnectionClosing() {\n // When the connection is not open, but the remote end is open,\n // then the rhea connection is in the process of terminating.\n return Boolean(!this.connection.isOpen() && this.connection.isRemoteOpen());\n },\n async readyToOpenLink(optionsArg?: { abortSignal?: AbortSignalLike }) {\n // Check that the connection isn't in the process of closing.\n // This can happen when the idle timeout has been reached but\n // the underlying socket is waiting to be destroyed.\n if (this.isConnectionClosing()) {\n // Wait for the disconnected event that indicates the underlying socket has closed.\n await this.waitForDisconnectedEvent(optionsArg);\n }\n\n // Wait for the connection to be reset.\n await this.waitForConnectionReset();\n },\n waitForDisconnectedEvent(optionsArg?: { abortSignal?: AbortSignalLike }) {\n return createAbortablePromise((resolve) => {\n logger.verbose(\n `[${this.connectionId}] Attempting to reinitialize connection` +\n ` but the connection is in the process of closing.` +\n ` Waiting for the disconnect event before continuing.`,\n );\n this.connection.once(ConnectionEvents.disconnected, resolve);\n }, optionsArg);\n },\n waitForConnectionReset() {\n // Check if the connection is currently in the process of disconnecting.\n if (waitForConnectionRefreshPromise) {\n return waitForConnectionRefreshPromise;\n }\n return Promise.resolve();\n },\n async close() {\n try {\n if (this.connection.isOpen()) {\n // Close all the senders.\n await Promise.all(\n Object.keys(connectionContext.senders).map((name) =>\n connectionContext.senders[name]?.close().catch(() => {\n /* error already logged, swallow it here */\n }),\n ),\n );\n // Close all the receivers.\n await Promise.all(\n Object.keys(connectionContext.receivers).map((name) =>\n connectionContext.receivers[name]?.close().catch(() => {\n /* error already logged, swallow it here */\n }),\n ),\n );\n // Close the cbs session;\n await this.cbsSession.close();\n // Close the management session\n await this.managementSession?.close();\n await this.connection.close();\n this.wasConnectionCloseCalled = true;\n logger.info(\"Closed the amqp connection '%s' on the client.\", this.connectionId);\n }\n } catch (err: any) {\n const errorDescription =\n err instanceof Error ? `${err.name}: ${err.message}` : JSON.stringify(err);\n logger.warning(\n `An error occurred while closing the connection \"${this.connectionId}\":\\n${errorDescription}`,\n );\n logErrorStackTrace(err);\n throw err;\n }\n },\n });\n\n // Define listeners to be added to the connection object for\n // \"connection_open\" and \"connection_error\" events.\n const onConnectionOpen: OnAmqpEvent = () => {\n connectionContext.wasConnectionCloseCalled = false;\n logger.verbose(\n \"[%s] setting 'wasConnectionCloseCalled' property of connection context to %s.\",\n connectionContext.connection.id,\n connectionContext.wasConnectionCloseCalled,\n );\n };\n\n async function handleDisconnection(context: EventContext): Promise<void> {\n if (waitForConnectionRefreshPromise) {\n return;\n }\n waitForConnectionRefreshPromise = new Promise((resolve) => {\n waitForConnectionRefreshResolve = resolve;\n });\n try {\n logger.verbose(\n \"[%s] 'disconnected' event occurred on the amqp connection.\",\n connectionContext.connection.id,\n );\n\n if (context.connection && context.connection.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context.connection: %O\",\n connectionContext.connection.id,\n context.connection.error,\n );\n }\n if (context.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context: %O\",\n connectionContext.connection.id,\n context.error,\n );\n }\n const state: Readonly<{\n wasConnectionCloseCalled: boolean;\n numSenders: number;\n numReceivers: number;\n }> = {\n wasConnectionCloseCalled: connectionContext.wasConnectionCloseCalled,\n numSenders: Object.keys(connectionContext.senders).length,\n numReceivers: Object.keys(connectionContext.receivers).length,\n };\n logger.verbose(\n \"[%s] Closing all open senders and receivers in the state: %O\",\n connectionContext.connection.id,\n state,\n );\n\n // Clear internal map maintained by rhea to avoid reconnecting of old links once the\n // connection is back up.\n connectionContext.connection.removeAllSessions();\n\n // Close the cbs session to ensure all the event handlers are released.\n await connectionContext.cbsSession?.close().catch(() => {\n /* error already logged, swallow it here */\n });\n // Close the management session to ensure all the event handlers are released.\n await connectionContext.managementSession?.close().catch(() => {\n /* error already logged, swallow it here */\n });\n\n // Close all senders and receivers to ensure clean up of timers & other resources.\n if (state.numSenders || state.numReceivers) {\n await Promise.all(\n Object.keys(connectionContext.senders).map((name) =>\n connectionContext.senders[name]?.close().catch(() => {\n /* error already logged, swallow it here */\n }),\n ),\n );\n\n await Promise.all(\n Object.keys(connectionContext.receivers).map((name) =>\n connectionContext.receivers[name]?.close().catch(() => {\n /* error already logged, swallow it here */\n }),\n ),\n );\n }\n } catch (err: any) {\n logger.verbose(\n `[${connectionContext.connectionId}] An error occurred while closing the connection in 'disconnected'. %O`,\n err,\n );\n }\n\n try {\n await refreshConnection(connectionContext);\n } catch (err: any) {\n logger.verbose(\n `[${connectionContext.connectionId}] An error occurred while refreshing the connection in 'disconnected'. %O`,\n err,\n );\n } finally {\n waitForConnectionRefreshResolve();\n waitForConnectionRefreshPromise = undefined;\n }\n }\n\n const onDisconnected: OnAmqpEvent = (context: EventContext) => {\n // Fire-and-forget async operation with error handling\n handleDisconnection(context).catch((err) => {\n logger.verbose(\n `[${connectionContext.connectionId}] Unhandled error in 'disconnected' event handler. %O`,\n err,\n );\n });\n };\n\n const protocolError: OnAmqpEvent = (context: EventContext) => {\n logger.verbose(\n \"[%s] 'protocol_error' event occurred on the amqp connection.\",\n connectionContext.connection.id,\n );\n\n if (context.connection && context.connection.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context.connection: %O\",\n connectionContext.connection.id,\n context.connection && context.connection.error,\n );\n }\n if (context.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context: %O\",\n connectionContext.connection.id,\n context.error,\n );\n }\n };\n\n const error: OnAmqpEvent = (context: EventContext) => {\n logger.verbose(\n \"[%s] 'error' event occurred on the amqp connection.\",\n connectionContext.connection.id,\n );\n\n if (context.connection && context.connection.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context.connection: %O\",\n connectionContext.connection.id,\n context.connection && context.connection.error,\n );\n }\n if (context.error) {\n logger.verbose(\n \"[%s] Accompanying error on the context: %O\",\n connectionContext.connection.id,\n context.error,\n );\n }\n };\n\n function addConnectionListeners(connection: Connection): void {\n // Add listeners on the connection object.\n connection.on(ConnectionEvents.connectionOpen, onConnectionOpen);\n connection.on(ConnectionEvents.disconnected, onDisconnected);\n connection.on(ConnectionEvents.protocolError, protocolError);\n connection.on(ConnectionEvents.error, error);\n }\n\n function cleanConnectionContext(context: ConnectionContext): Promise<void> {\n // Remove listeners from the connection object.\n context.connection.removeListener(ConnectionEvents.connectionOpen, onConnectionOpen);\n context.connection.removeListener(ConnectionEvents.disconnected, onDisconnected);\n context.connection.removeListener(ConnectionEvents.protocolError, protocolError);\n context.connection.removeListener(ConnectionEvents.error, error);\n // Close the connection\n return context.connection.close();\n }\n\n async function refreshConnection(context: ConnectionContext): Promise<void> {\n const originalConnectionId = context.connectionId;\n try {\n await cleanConnectionContext(context);\n } catch (err: any) {\n logger.verbose(\n `[${context.connectionId}] There was an error closing the connection before reconnecting: %O`,\n err,\n );\n }\n\n // Create a new connection, id, locks, and cbs client.\n context.refreshConnection();\n addConnectionListeners(context.connection);\n logger.verbose(\n `The connection \"${originalConnectionId}\" has been updated to \"${context.connectionId}\".`,\n );\n }\n\n addConnectionListeners(connectionContext.connection);\n\n logger.verbose(\"[%s] Created connection context successfully.\", connectionContext.connectionId);\n return connectionContext;\n }\n}\n\n/**\n * Helper method to create a ConnectionContext from the input passed to either\n * EventHubProducerClient or EventHubConsumerClient constructors\n *\n * @internal\n */\nexport function createConnectionContext(\n hostOrConnectionString: string,\n eventHubNameOrOptions?: string | EventHubClientOptions,\n credentialOrOptions?:\n | TokenCredential\n | NamedKeyCredential\n | SASCredential\n | EventHubClientOptions,\n options?: EventHubClientOptions,\n): ConnectionContext {\n let connectionString;\n let config;\n let credential: TokenCredential | SasTokenProvider;\n hostOrConnectionString = String(hostOrConnectionString);\n\n if (!isCredential(credentialOrOptions)) {\n const parsedCS = parseEventHubConnectionString(hostOrConnectionString);\n if (\n !(\n parsedCS.eventHubName ||\n (typeof eventHubNameOrOptions === \"string\" && eventHubNameOrOptions)\n )\n ) {\n throw new TypeError(\n `Either provide \"eventHubName\" or the \"connectionString\": \"${hostOrConnectionString}\", ` +\n `must contain \"EntityPath=<your-event-hub-name>\".`,\n );\n }\n if (\n parsedCS.eventHubName &&\n typeof eventHubNameOrOptions === \"string\" &&\n eventHubNameOrOptions &&\n parsedCS.eventHubName !== eventHubNameOrOptions\n ) {\n throw new TypeError(\n `The entity path \"${parsedCS.eventHubName}\" in connectionString: \"${hostOrConnectionString}\" ` +\n `doesn't match with eventHubName: \"${eventHubNameOrOptions}\".`,\n );\n }\n connectionString = hostOrConnectionString;\n if (typeof eventHubNameOrOptions !== \"string\") {\n // connectionstring and/or options were passed to constructor\n config = EventHubConnectionConfig.create(connectionString);\n options = eventHubNameOrOptions;\n } else {\n // connectionstring, eventHubName and/or options were passed to constructor\n const eventHubName = eventHubNameOrOptions;\n config = EventHubConnectionConfig.create(connectionString, eventHubName);\n options = credentialOrOptions;\n }\n\n const parsed = parseEventHubConnectionString(connectionString) as Required<\n | Pick<EventHubConnectionStringProperties, \"sharedAccessKey\" | \"sharedAccessKeyName\">\n | Pick<EventHubConnectionStringProperties, \"sharedAccessSignature\">\n >;\n // Since connectionString was passed, create a TokenProvider.\n credential = createSasTokenProvider(parsed);\n } else {\n // host, eventHubName, a TokenCredential and/or options were passed to constructor\n const eventHubName = eventHubNameOrOptions;\n let host = hostOrConnectionString;\n if (isNamedKeyCredential(credentialOrOptions) || isSASCredential(credentialOrOptions)) {\n credential = createSasTokenProvider(credentialOrOptions);\n } else {\n credential = credentialOrOptions;\n }\n if (!eventHubName) {\n throw new TypeError(`\"eventHubName\" is missing`);\n }\n\n if (!host.endsWith(\"/\")) host += \"/\";\n connectionString = `Endpoint=sb://${host};SharedAccessKeyName=defaultKeyName;SharedAccessKey=defaultKeyValue;EntityPath=${eventHubName}`;\n config = EventHubConnectionConfig.create(connectionString);\n }\n\n if (options?.customEndpointAddress) {\n EventHubConnectionConfig.setCustomEndpointAddress(config, options.customEndpointAddress);\n }\n\n ConnectionConfig.validate(config);\n\n return ConnectionContext.create(config, credential, options);\n}\n"]}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The allowed AMQP message body types.
3
+ * @internal
4
+ */
5
+ export type BodyTypes = "data" | "value" | "sequence";
6
+ /** @internal */
7
+ export declare const dataSectionTypeCode: 117;
8
+ /** @internal */
9
+ export declare const sequenceSectionTypeCode: 118;
10
+ /** @internal */
11
+ export declare const valueSectionTypeCode: 119;
12
+ /**
13
+ * The default data transformer that will be used by the Azure SDK.
14
+ * @internal
15
+ */
16
+ export declare const defaultDataTransformer: {
17
+ /**
18
+ * A function that takes the body property from an EventData object
19
+ * and returns an encoded body (some form of AMQP type).
20
+ *
21
+ * @param body - The AMQP message body
22
+ * @param bodyType - The AMQP section to story the body in.
23
+ * @returns The encoded AMQP message body as an AMQP Data/Sequence/Value section.
24
+ */
25
+ encode(body: unknown, bodyType: BodyTypes): any;
26
+ /**
27
+ * A function that takes the body property from an AMQP message, which can come from either
28
+ * the 'data', 'value' or 'sequence' sections of an AMQP message.
29
+ *
30
+ * If the body is not a JSON string the the raw contents will be returned, along with the bodyType
31
+ * indicating which part of the AMQP message the body was decoded from.
32
+ *
33
+ * @param body - The AMQP message body as received from rhea.
34
+ * @param skipParsingBodyAsJson - Boolean to skip running JSON.parse() on message body when body type is `content`.
35
+ * @returns The decoded/raw body and the body type.
36
+ */
37
+ decode(body: unknown | RheaAmqpSection, skipParsingBodyAsJson: boolean): {
38
+ body: unknown;
39
+ bodyType: BodyTypes;
40
+ };
41
+ };
42
+ /**
43
+ * Mirror of the internal Section interface in rhea.
44
+ *
45
+ * @internal
46
+ */
47
+ export interface RheaAmqpSection {
48
+ typecode: typeof dataSectionTypeCode | typeof sequenceSectionTypeCode | typeof valueSectionTypeCode;
49
+ content: any;
50
+ }
51
+ /** @internal */
52
+ export declare function isRheaAmqpSection(possibleSection: any | RheaAmqpSection): possibleSection is RheaAmqpSection;
53
+ //# sourceMappingURL=dataTransformer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTransformer.d.ts","sourceRoot":"","sources":["../../src/dataTransformer.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,UAAU,CAAC;AAEtD,gBAAgB;AAChB,eAAO,MAAM,mBAAmB,EAAG,GAAa,CAAC;AACjD,gBAAgB;AAChB,eAAO,MAAM,uBAAuB,EAAG,GAAa,CAAC;AACrD,gBAAgB;AAChB,eAAO,MAAM,oBAAoB,EAAG,GAAa,CAAC;AAElD;;;GAGG;AACH,eAAO,MAAM,sBAAsB;IACjC;;;;;;;OAOG;iBACU,OAAO,YAAY,SAAS,GAAG,GAAG;IAmC/C;;;;;;;;;;OAUG;iBAEK,OAAO,GAAG,eAAe,yBACR,OAAO,GAC7B;QAAE,IAAI,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,SAAS,CAAA;KAAE;CA6B1C,CAAC;AA2BF;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,EACJ,OAAO,mBAAmB,GAC1B,OAAO,uBAAuB,GAC9B,OAAO,oBAAoB,CAAC;IAChC,OAAO,EAAE,GAAG,CAAC;CACd;AAED,gBAAgB;AAChB,wBAAgB,iBAAiB,CAC/B,eAAe,EAAE,GAAG,GAAG,eAAe,GACrC,eAAe,IAAI,eAAe,CAQpC"}
@@ -0,0 +1,133 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import { logErrorStackTrace, logger } from "./logger.js";
4
+ import { Buffer } from "buffer";
5
+ import isBuffer from "is-buffer";
6
+ import { message } from "rhea-promise";
7
+ /** @internal */
8
+ export const dataSectionTypeCode = 0x75;
9
+ /** @internal */
10
+ export const sequenceSectionTypeCode = 0x76;
11
+ /** @internal */
12
+ export const valueSectionTypeCode = 0x77;
13
+ /**
14
+ * The default data transformer that will be used by the Azure SDK.
15
+ * @internal
16
+ */
17
+ export const defaultDataTransformer = {
18
+ /**
19
+ * A function that takes the body property from an EventData object
20
+ * and returns an encoded body (some form of AMQP type).
21
+ *
22
+ * @param body - The AMQP message body
23
+ * @param bodyType - The AMQP section to story the body in.
24
+ * @returns The encoded AMQP message body as an AMQP Data/Sequence/Value section.
25
+ */
26
+ encode(body, bodyType) {
27
+ let result;
28
+ // string, undefined, null, boolean, array, object, number should end up here
29
+ // coercing undefined to null as that will ensure that null value will be given to the
30
+ // customer on receive.
31
+ if (body === undefined)
32
+ body = null;
33
+ if (bodyType === "value") {
34
+ // TODO: Expose value_section from `rhea` similar to the data_section and sequence_section.
35
+ // Right now there isn't a way to create a value section officially.
36
+ result = message.data_section(body);
37
+ result.typecode = valueSectionTypeCode;
38
+ }
39
+ else if (bodyType === "sequence") {
40
+ result = message.sequence_section(body);
41
+ }
42
+ else if (isBuffer(body) || body instanceof Uint8Array) {
43
+ result = message.data_section(body);
44
+ }
45
+ else if (body === null && bodyType === "data") {
46
+ result = message.data_section(null);
47
+ }
48
+ else {
49
+ try {
50
+ const bodyStr = JSON.stringify(body);
51
+ result = message.data_section(Buffer.from(bodyStr, "utf8"));
52
+ }
53
+ catch (err) {
54
+ const msg = `An error occurred while executing JSON.stringify() on the given body ` +
55
+ body +
56
+ `${err ? err.stack : JSON.stringify(err)}`;
57
+ logger.warning("[encode] " + msg);
58
+ logErrorStackTrace(err);
59
+ throw new Error(msg);
60
+ }
61
+ }
62
+ return result;
63
+ },
64
+ /**
65
+ * A function that takes the body property from an AMQP message, which can come from either
66
+ * the 'data', 'value' or 'sequence' sections of an AMQP message.
67
+ *
68
+ * If the body is not a JSON string the the raw contents will be returned, along with the bodyType
69
+ * indicating which part of the AMQP message the body was decoded from.
70
+ *
71
+ * @param body - The AMQP message body as received from rhea.
72
+ * @param skipParsingBodyAsJson - Boolean to skip running JSON.parse() on message body when body type is `content`.
73
+ * @returns The decoded/raw body and the body type.
74
+ */
75
+ decode(body, skipParsingBodyAsJson) {
76
+ try {
77
+ if (isRheaAmqpSection(body)) {
78
+ switch (body.typecode) {
79
+ case dataSectionTypeCode:
80
+ return {
81
+ body: skipParsingBodyAsJson ? body.content : tryToJsonDecode(body.content),
82
+ bodyType: "data",
83
+ };
84
+ case sequenceSectionTypeCode:
85
+ return { body: body.content, bodyType: "sequence" };
86
+ case valueSectionTypeCode:
87
+ return { body: body.content, bodyType: "value" };
88
+ }
89
+ }
90
+ else {
91
+ if (isBuffer(body)) {
92
+ return { body: skipParsingBodyAsJson ? body : tryToJsonDecode(body), bodyType: "data" };
93
+ }
94
+ return { body, bodyType: "value" };
95
+ }
96
+ }
97
+ catch (err) {
98
+ logger.verbose("[decode] An error occurred while decoding the received message body. The error is: %O", err);
99
+ throw err;
100
+ }
101
+ },
102
+ };
103
+ /**
104
+ * Attempts to decode 'body' as a JSON string. If it fails it returns body
105
+ * verbatim.
106
+ *
107
+ * @param body - An AMQP message body.
108
+ * @returns A JSON decoded object, or body if body was not a JSON string.
109
+ *
110
+ * @internal
111
+ */
112
+ function tryToJsonDecode(body) {
113
+ let processedBody = body;
114
+ try {
115
+ // Trying to stringify and JSON.parse() anything else will fail flat and we shall return
116
+ // the original type back
117
+ const bodyStr = processedBody.toString("utf8");
118
+ processedBody = JSON.parse(bodyStr);
119
+ }
120
+ catch (err) {
121
+ logger.verbose("[decode] An error occurred while trying JSON.parse() on the received body. The error is %O", err);
122
+ }
123
+ return processedBody;
124
+ }
125
+ /** @internal */
126
+ export function isRheaAmqpSection(possibleSection) {
127
+ return (possibleSection != null &&
128
+ typeof possibleSection.typecode === "number" &&
129
+ (possibleSection.typecode === dataSectionTypeCode ||
130
+ possibleSection.typecode === valueSectionTypeCode ||
131
+ possibleSection.typecode === sequenceSectionTypeCode));
132
+ }
133
+ //# sourceMappingURL=dataTransformer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataTransformer.js","sourceRoot":"","sources":["../../src/dataTransformer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,QAAQ,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAQvC,gBAAgB;AAChB,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAa,CAAC;AACjD,gBAAgB;AAChB,MAAM,CAAC,MAAM,uBAAuB,GAAG,IAAa,C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AAC;YAClB,MAAM,CAAC,OAAO,CACZ,uFAAuF,EACvF,GAAG,CACJ,CAAC;YACF,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,eAAe,CAAC,IAAa;IACpC,IAAI,aAAa,GAAQ,IAAI,CAAC;IAC9B,IAAI,CAAC;QACH,wFAAwF;QACxF,yBAAyB;QACzB,MAAM,OAAO,GAAW,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACvD,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACtC,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,MAAM,CAAC,OAAO,CACZ,4FAA4F,EAC5F,GAAG,CACJ,CAAC;IACJ,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAeD,gBAAgB;AAChB,MAAM,UAAU,iBAAiB,CAC/B,eAAsC;IAEtC,OAAO,CACL,eAAe,IAAI,IAAI;QACvB,OAAO,eAAe,CAAC,QAAQ,KAAK,QAAQ;QAC5C,CAAC,eAAe,CAAC,QAAQ,KAAK,mBAAmB;YAC/C,eAAe,CAAC,QAAQ,KAAK,oBAAoB;YACjD,eAAe,CAAC,QAAQ,KAAK,uBAAuB,CAAC,CACxD,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { logErrorStackTrace, logger } from \"./logger.js\";\nimport { Buffer } from \"buffer\";\nimport isBuffer from \"is-buffer\";\nimport { message } from \"rhea-promise\";\n\n/**\n * The allowed AMQP message body types.\n * @internal\n */\nexport type BodyTypes = \"data\" | \"value\" | \"sequence\";\n\n/** @internal */\nexport const dataSectionTypeCode = 0x75 as const;\n/** @internal */\nexport const sequenceSectionTypeCode = 0x76 as const;\n/** @internal */\nexport const valueSectionTypeCode = 0x77 as const;\n\n/**\n * The default data transformer that will be used by the Azure SDK.\n * @internal\n */\nexport const defaultDataTransformer = {\n /**\n * A function that takes the body property from an EventData object\n * and returns an encoded body (some form of AMQP type).\n *\n * @param body - The AMQP message body\n * @param bodyType - The AMQP section to story the body in.\n * @returns The encoded AMQP message body as an AMQP Data/Sequence/Value section.\n */\n encode(body: unknown, bodyType: BodyTypes): any {\n let result: any;\n // string, undefined, null, boolean, array, object, number should end up here\n // coercing undefined to null as that will ensure that null value will be given to the\n // customer on receive.\n if (body === undefined) body = null;\n\n if (bodyType === \"value\") {\n // TODO: Expose value_section from `rhea` similar to the data_section and sequence_section.\n // Right now there isn't a way to create a value section officially.\n result = message.data_section(body);\n result.typecode = valueSectionTypeCode;\n } else if (bodyType === \"sequence\") {\n result = message.sequence_section(body);\n } else if (isBuffer(body) || body instanceof Uint8Array) {\n result = message.data_section(body);\n } else if (body === null && bodyType === \"data\") {\n result = message.data_section(null);\n } else {\n try {\n const bodyStr = JSON.stringify(body);\n result = message.data_section(Buffer.from(bodyStr, \"utf8\"));\n } catch (err: any) {\n const msg =\n `An error occurred while executing JSON.stringify() on the given body ` +\n body +\n `${err ? err.stack : JSON.stringify(err)}`;\n logger.warning(\"[encode] \" + msg);\n logErrorStackTrace(err);\n throw new Error(msg);\n }\n }\n return result;\n },\n\n /**\n * A function that takes the body property from an AMQP message, which can come from either\n * the 'data', 'value' or 'sequence' sections of an AMQP message.\n *\n * If the body is not a JSON string the the raw contents will be returned, along with the bodyType\n * indicating which part of the AMQP message the body was decoded from.\n *\n * @param body - The AMQP message body as received from rhea.\n * @param skipParsingBodyAsJson - Boolean to skip running JSON.parse() on message body when body type is `content`.\n * @returns The decoded/raw body and the body type.\n */\n decode(\n body: unknown | RheaAmqpSection,\n skipParsingBodyAsJson: boolean,\n ): { body: unknown; bodyType: BodyTypes } {\n try {\n if (isRheaAmqpSection(body)) {\n switch (body.typecode) {\n case dataSectionTypeCode:\n return {\n body: skipParsingBodyAsJson ? body.content : tryToJsonDecode(body.content),\n bodyType: \"data\",\n };\n case sequenceSectionTypeCode:\n return { body: body.content, bodyType: \"sequence\" };\n case valueSectionTypeCode:\n return { body: body.content, bodyType: \"value\" };\n }\n } else {\n if (isBuffer(body)) {\n return { body: skipParsingBodyAsJson ? body : tryToJsonDecode(body), bodyType: \"data\" };\n }\n\n return { body, bodyType: \"value\" };\n }\n } catch (err: any) {\n logger.verbose(\n \"[decode] An error occurred while decoding the received message body. The error is: %O\",\n err,\n );\n throw err;\n }\n },\n};\n\n/**\n * Attempts to decode 'body' as a JSON string. If it fails it returns body\n * verbatim.\n *\n * @param body - An AMQP message body.\n * @returns A JSON decoded object, or body if body was not a JSON string.\n *\n * @internal\n */\nfunction tryToJsonDecode(body: unknown): unknown {\n let processedBody: any = body;\n try {\n // Trying to stringify and JSON.parse() anything else will fail flat and we shall return\n // the original type back\n const bodyStr: string = processedBody.toString(\"utf8\");\n processedBody = JSON.parse(bodyStr);\n } catch (err: any) {\n logger.verbose(\n \"[decode] An error occurred while trying JSON.parse() on the received body. The error is %O\",\n err,\n );\n }\n return processedBody;\n}\n\n/**\n * Mirror of the internal Section interface in rhea.\n *\n * @internal\n */\nexport interface RheaAmqpSection {\n typecode:\n | typeof dataSectionTypeCode\n | typeof sequenceSectionTypeCode\n | typeof valueSectionTypeCode;\n content: any;\n}\n\n/** @internal */\nexport function isRheaAmqpSection(\n possibleSection: any | RheaAmqpSection,\n): possibleSection is RheaAmqpSection {\n return (\n possibleSection != null &&\n typeof possibleSection.typecode === \"number\" &&\n (possibleSection.typecode === dataSectionTypeCode ||\n possibleSection.typecode === valueSectionTypeCode ||\n possibleSection.typecode === sequenceSectionTypeCode)\n );\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import type { EventData } from "../eventData.js";
2
+ import type { TracingContext } from "@azure/core-tracing";
3
+ import type { AmqpAnnotatedMessage } from "@azure/core-amqp";
4
+ import type { OperationOptions } from "../util/operationOptions.js";
5
+ import type { MessagingOperationNames } from "./tracing.js";
6
+ /**
7
+ * @internal
8
+ */
9
+ export declare const TRACEPARENT_PROPERTY = "Diagnostic-Id";
10
+ /**
11
+ * Populates the `EventData` with `SpanContext` info to support trace propagation.
12
+ * Creates and returns a copy of the passed in `EventData` unless the `EventData`
13
+ * has already been instrumented.
14
+ * @param eventData - The `EventData` or `AmqpAnnotatedMessage` to instrument.
15
+ * @param span - The `Span` containing the context to propagate tracing information.
16
+ * @param operation - The type of the operation being performed.
17
+ */
18
+ export declare function instrumentEventData(eventData: EventData | AmqpAnnotatedMessage, options: OperationOptions, entityPath: string, host: string, operation?: MessagingOperationNames): {
19
+ event: EventData;
20
+ spanContext: TracingContext | undefined;
21
+ };
22
+ /**
23
+ * Extracts the `SpanContext` from an `EventData` if the context exists.
24
+ * @param eventData - An individual `EventData` object.
25
+ * @internal
26
+ */
27
+ export declare function extractSpanContextFromEventData(eventData: EventData): TracingContext | undefined;
28
+ //# sourceMappingURL=instrumentEventData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentEventData.d.ts","sourceRoot":"","sources":["../../../src/diagnostics/instrumentEventData.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAG5D;;GAEG;AACH,eAAO,MAAM,oBAAoB,kBAAkB,CAAC;AAEpD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,SAAS,GAAG,oBAAoB,EAC3C,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE,uBAAuB,GAClC;IAAE,KAAK,EAAE,SAAS,CAAC;IAAC,WAAW,EAAE,cAAc,GAAG,SAAS,CAAA;CAAE,CA+C/D;AAED;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,SAAS,EAAE,SAAS,GAAG,cAAc,GAAG,SAAS,CAOhG"}