@azure/event-hubs 5.13.0-beta.2 → 6.0.0-alpha.20250128.2

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 (616) hide show
  1. package/README.md +32 -31
  2. package/dist/browser/batchingPartitionChannel.d.ts +94 -0
  3. package/dist/browser/batchingPartitionChannel.d.ts.map +1 -0
  4. package/{dist-esm/src → dist/browser}/batchingPartitionChannel.js +4 -4
  5. package/dist/browser/batchingPartitionChannel.js.map +1 -0
  6. package/dist/browser/connectionContext.d.ts +108 -0
  7. package/dist/browser/connectionContext.d.ts.map +1 -0
  8. package/{dist-esm/src → dist/browser}/connectionContext.js +9 -11
  9. package/dist/browser/connectionContext.js.map +1 -0
  10. package/dist/browser/dataTransformer.d.ts +53 -0
  11. package/dist/browser/dataTransformer.d.ts.map +1 -0
  12. package/{dist-esm/src → dist/browser}/dataTransformer.js +2 -2
  13. package/dist/browser/dataTransformer.js.map +1 -0
  14. package/dist/browser/diagnostics/instrumentEventData.d.ts +28 -0
  15. package/dist/browser/diagnostics/instrumentEventData.d.ts.map +1 -0
  16. package/{dist-esm/src → dist/browser}/diagnostics/instrumentEventData.js +3 -3
  17. package/dist/browser/diagnostics/instrumentEventData.js.map +1 -0
  18. package/dist/browser/diagnostics/tracing.d.ts +19 -0
  19. package/dist/browser/diagnostics/tracing.d.ts.map +1 -0
  20. package/{dist-esm/src → dist/browser}/diagnostics/tracing.js +2 -2
  21. package/dist/browser/diagnostics/tracing.js.map +1 -0
  22. package/dist/browser/eventData.d.ts +295 -0
  23. package/dist/browser/eventData.d.ts.map +1 -0
  24. package/{dist-esm/src → dist/browser}/eventData.js +39 -5
  25. package/dist/browser/eventData.js.map +1 -0
  26. package/dist/browser/eventDataAdapter.d.ts +69 -0
  27. package/dist/browser/eventDataAdapter.d.ts.map +1 -0
  28. package/{dist-esm/src → dist/browser}/eventDataAdapter.js +1 -1
  29. package/dist/browser/eventDataAdapter.js.map +1 -0
  30. package/dist/browser/eventDataBatch.d.ts +225 -0
  31. package/dist/browser/eventDataBatch.d.ts.map +1 -0
  32. package/{dist-esm/src → dist/browser}/eventDataBatch.js +7 -4
  33. package/dist/browser/eventDataBatch.js.map +1 -0
  34. package/dist/browser/eventHubBufferedProducerClient.d.ts +323 -0
  35. package/dist/browser/eventHubBufferedProducerClient.d.ts.map +1 -0
  36. package/{dist-esm/src → dist/browser}/eventHubBufferedProducerClient.js +10 -9
  37. package/dist/browser/eventHubBufferedProducerClient.js.map +1 -0
  38. package/dist/browser/eventHubConsumerClient.d.ts +277 -0
  39. package/dist/browser/eventHubConsumerClient.d.ts.map +1 -0
  40. package/{dist-esm/src → dist/browser}/eventHubConsumerClient.js +12 -12
  41. package/dist/browser/eventHubConsumerClient.js.map +1 -0
  42. package/dist/browser/eventHubConsumerClientModels.d.ts +218 -0
  43. package/dist/browser/eventHubConsumerClientModels.d.ts.map +1 -0
  44. package/dist/browser/eventHubConsumerClientModels.js +4 -0
  45. package/dist/browser/eventHubConsumerClientModels.js.map +1 -0
  46. package/dist/browser/eventHubProducerClient.d.ts +266 -0
  47. package/dist/browser/eventHubProducerClient.d.ts.map +1 -0
  48. package/{dist-esm/src → dist/browser}/eventHubProducerClient.js +12 -10
  49. package/dist/browser/eventHubProducerClient.js.map +1 -0
  50. package/dist/browser/eventHubSender.d.ts +227 -0
  51. package/dist/browser/eventHubSender.d.ts.map +1 -0
  52. package/{dist-esm/src → dist/browser}/eventHubSender.js +12 -12
  53. package/dist/browser/eventHubSender.js.map +1 -0
  54. package/dist/browser/eventPosition.d.ts +73 -0
  55. package/dist/browser/eventPosition.d.ts.map +1 -0
  56. package/{dist-esm/src → dist/browser}/eventPosition.js +2 -2
  57. package/dist/browser/eventPosition.js.map +1 -0
  58. package/dist/browser/eventProcessor.d.ts +232 -0
  59. package/dist/browser/eventProcessor.d.ts.map +1 -0
  60. package/{dist-esm/src → dist/browser}/eventProcessor.js +18 -18
  61. package/dist/browser/eventProcessor.js.map +1 -0
  62. package/dist/browser/eventhubConnectionConfig.d.ts +96 -0
  63. package/dist/browser/eventhubConnectionConfig.d.ts.map +1 -0
  64. package/{dist-esm/src → dist/browser}/eventhubConnectionConfig.js +2 -2
  65. package/dist/browser/eventhubConnectionConfig.js.map +1 -0
  66. package/dist/browser/impl/awaitableQueue.d.ts +25 -0
  67. package/dist/browser/impl/awaitableQueue.d.ts.map +1 -0
  68. package/{dist-esm/src → dist/browser}/impl/awaitableQueue.js +1 -1
  69. package/dist/browser/impl/awaitableQueue.js.map +1 -0
  70. package/dist/browser/impl/partitionAssigner.d.ts +29 -0
  71. package/dist/browser/impl/partitionAssigner.d.ts.map +1 -0
  72. package/{dist-esm/src → dist/browser}/impl/partitionAssigner.js +2 -2
  73. package/dist/browser/impl/partitionAssigner.js.map +1 -0
  74. package/dist/browser/impl/partitionGate.d.ts +27 -0
  75. package/dist/browser/impl/partitionGate.d.ts.map +1 -0
  76. package/{dist-esm/src → dist/browser}/impl/partitionGate.js +1 -1
  77. package/{dist-esm/src → dist/browser}/impl/partitionGate.js.map +1 -1
  78. package/dist/browser/impl/partitionKeyToIdMapper.d.ts +6 -0
  79. package/dist/browser/impl/partitionKeyToIdMapper.d.ts.map +1 -0
  80. package/{dist-esm/src → dist/browser}/impl/partitionKeyToIdMapper.js +1 -1
  81. package/{dist-esm/src → dist/browser}/impl/partitionKeyToIdMapper.js.map +1 -1
  82. package/dist/browser/inMemoryCheckpointStore.d.ts +44 -0
  83. package/dist/browser/inMemoryCheckpointStore.d.ts.map +1 -0
  84. package/{dist-esm/src → dist/browser}/inMemoryCheckpointStore.js +3 -3
  85. package/dist/browser/inMemoryCheckpointStore.js.map +1 -0
  86. package/dist/browser/index.d.ts +21 -0
  87. package/dist/browser/index.d.ts.map +1 -0
  88. package/{dist-esm/src → dist/browser}/index.js +9 -9
  89. package/dist/browser/index.js.map +1 -0
  90. package/dist/browser/loadBalancerStrategies/balancedStrategy.d.ts +30 -0
  91. package/dist/browser/loadBalancerStrategies/balancedStrategy.d.ts.map +1 -0
  92. package/{dist-esm/src → dist/browser}/loadBalancerStrategies/balancedStrategy.js +2 -2
  93. package/dist/browser/loadBalancerStrategies/balancedStrategy.js.map +1 -0
  94. package/dist/browser/loadBalancerStrategies/greedyStrategy.d.ts +24 -0
  95. package/dist/browser/loadBalancerStrategies/greedyStrategy.d.ts.map +1 -0
  96. package/{dist-esm/src → dist/browser}/loadBalancerStrategies/greedyStrategy.js +2 -2
  97. package/dist/browser/loadBalancerStrategies/greedyStrategy.js.map +1 -0
  98. package/dist/browser/loadBalancerStrategies/loadBalancingStrategy.d.ts +28 -0
  99. package/dist/browser/loadBalancerStrategies/loadBalancingStrategy.d.ts.map +1 -0
  100. package/{dist-esm/src → dist/browser}/loadBalancerStrategies/loadBalancingStrategy.js +2 -2
  101. package/dist/browser/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -0
  102. package/dist/browser/loadBalancerStrategies/unbalancedStrategy.d.ts +20 -0
  103. package/dist/browser/loadBalancerStrategies/unbalancedStrategy.d.ts.map +1 -0
  104. package/{dist-esm/src → dist/browser}/loadBalancerStrategies/unbalancedStrategy.js +1 -1
  105. package/dist/browser/loadBalancerStrategies/unbalancedStrategy.js.map +1 -0
  106. package/dist/browser/logger.d.ts +37 -0
  107. package/dist/browser/logger.d.ts.map +1 -0
  108. package/{dist-esm/src → dist/browser}/logger.js +1 -1
  109. package/dist/browser/logger.js.map +1 -0
  110. package/dist/browser/managementClient.d.ts +145 -0
  111. package/dist/browser/managementClient.d.ts.map +1 -0
  112. package/{dist-esm/src → dist/browser}/managementClient.js +8 -8
  113. package/dist/browser/managementClient.js.map +1 -0
  114. package/dist/browser/models/private.d.ts +185 -0
  115. package/dist/browser/models/private.d.ts.map +1 -0
  116. package/dist/browser/models/private.js +4 -0
  117. package/dist/browser/models/private.js.map +1 -0
  118. package/dist/browser/models/public.d.ts +240 -0
  119. package/dist/browser/models/public.d.ts.map +1 -0
  120. package/{dist-esm/src → dist/browser}/models/public.js +1 -1
  121. package/dist/browser/models/public.js.map +1 -0
  122. package/dist/browser/package.json +3 -0
  123. package/dist/browser/partitionProcessor.d.ts +134 -0
  124. package/dist/browser/partitionProcessor.d.ts.map +1 -0
  125. package/{dist-esm/src → dist/browser}/partitionProcessor.js +2 -2
  126. package/dist/browser/partitionProcessor.js.map +1 -0
  127. package/dist/browser/partitionPump.d.ts +38 -0
  128. package/dist/browser/partitionPump.d.ts.map +1 -0
  129. package/{dist-esm/src → dist/browser}/partitionPump.js +6 -7
  130. package/dist/browser/partitionPump.js.map +1 -0
  131. package/dist/browser/partitionReceiver.d.ts +82 -0
  132. package/dist/browser/partitionReceiver.d.ts.map +1 -0
  133. package/{dist-esm/src → dist/browser}/partitionReceiver.js +14 -12
  134. package/dist/browser/partitionReceiver.js.map +1 -0
  135. package/dist/browser/pumpManager.d.ts +72 -0
  136. package/dist/browser/pumpManager.d.ts.map +1 -0
  137. package/{dist-esm/src → dist/browser}/pumpManager.js +4 -4
  138. package/dist/browser/pumpManager.js.map +1 -0
  139. package/dist/browser/util/connectionStringUtils.d.ts +52 -0
  140. package/dist/browser/util/connectionStringUtils.d.ts.map +1 -0
  141. package/{dist-esm/src → dist/browser}/util/connectionStringUtils.js +1 -1
  142. package/{dist-esm/src → dist/browser}/util/connectionStringUtils.js.map +1 -1
  143. package/dist/browser/util/constants.d.ts +25 -0
  144. package/dist/browser/util/constants.d.ts.map +1 -0
  145. package/{dist-esm/src → dist/browser}/util/constants.js +4 -2
  146. package/dist/browser/util/constants.js.map +1 -0
  147. package/dist/browser/util/delayWithoutThrow.d.ts +8 -0
  148. package/dist/browser/util/delayWithoutThrow.d.ts.map +1 -0
  149. package/{dist-esm/src → dist/browser}/util/delayWithoutThrow.js +1 -1
  150. package/dist/browser/util/delayWithoutThrow.js.map +1 -0
  151. package/dist/browser/util/error.d.ts +39 -0
  152. package/dist/browser/util/error.d.ts.map +1 -0
  153. package/{dist-esm/src → dist/browser}/util/error.js +2 -2
  154. package/dist/browser/util/error.js.map +1 -0
  155. package/dist/browser/util/getPromiseParts.d.ts +10 -0
  156. package/dist/browser/util/getPromiseParts.d.ts.map +1 -0
  157. package/{dist-esm/src → dist/browser}/util/getPromiseParts.js +1 -1
  158. package/{dist-esm/src → dist/browser}/util/getPromiseParts.js.map +1 -1
  159. package/dist/browser/util/operationOptions.d.ts +16 -0
  160. package/dist/browser/util/operationOptions.d.ts.map +1 -0
  161. package/dist/browser/util/operationOptions.js +4 -0
  162. package/dist/browser/util/operationOptions.js.map +1 -0
  163. package/dist/browser/util/parseEndpoint.d.ts +11 -0
  164. package/dist/browser/util/parseEndpoint.d.ts.map +1 -0
  165. package/{dist-esm/src → dist/browser}/util/parseEndpoint.js +1 -1
  166. package/{dist-esm/src → dist/browser}/util/parseEndpoint.js.map +1 -1
  167. package/dist/browser/util/retries.d.ts +6 -0
  168. package/dist/browser/util/retries.d.ts.map +1 -0
  169. package/{dist-esm/src → dist/browser}/util/retries.js +1 -1
  170. package/dist/browser/util/retries.js.map +1 -0
  171. package/dist/browser/util/runtimeInfo-browser.d.mts.map +1 -0
  172. package/dist/browser/util/runtimeInfo-browser.mjs.map +1 -0
  173. package/dist/browser/util/runtimeInfo.d.ts +6 -0
  174. package/{dist-esm/src/util/runtimeInfo.browser.js → dist/browser/util/runtimeInfo.js} +2 -2
  175. package/dist/browser/util/timerLoop.d.ts +26 -0
  176. package/dist/browser/util/timerLoop.d.ts.map +1 -0
  177. package/{dist-esm/src → dist/browser}/util/timerLoop.js +1 -1
  178. package/{dist-esm/src → dist/browser}/util/timerLoop.js.map +1 -1
  179. package/dist/browser/util/typeGuards.d.ts +8 -0
  180. package/dist/browser/util/typeGuards.d.ts.map +1 -0
  181. package/{dist-esm/src → dist/browser}/util/typeGuards.js +2 -2
  182. package/dist/browser/util/typeGuards.js.map +1 -0
  183. package/dist/browser/util/utils.d.ts +7 -0
  184. package/dist/browser/util/utils.d.ts.map +1 -0
  185. package/{dist-esm/src → dist/browser}/util/utils.js +1 -1
  186. package/{dist-esm/src → dist/browser}/util/utils.js.map +1 -1
  187. package/dist/browser/withAuth.d.ts +25 -0
  188. package/dist/browser/withAuth.d.ts.map +1 -0
  189. package/{dist-esm/src → dist/browser}/withAuth.js +4 -4
  190. package/dist/browser/withAuth.js.map +1 -0
  191. package/dist/commonjs/batchingPartitionChannel.d.ts +94 -0
  192. package/dist/commonjs/batchingPartitionChannel.d.ts.map +1 -0
  193. package/dist/commonjs/batchingPartitionChannel.js +252 -0
  194. package/dist/commonjs/batchingPartitionChannel.js.map +1 -0
  195. package/dist/commonjs/connectionContext.d.ts +108 -0
  196. package/dist/commonjs/connectionContext.d.ts.map +1 -0
  197. package/dist/commonjs/connectionContext.js +322 -0
  198. package/dist/commonjs/connectionContext.js.map +1 -0
  199. package/dist/commonjs/dataTransformer.d.ts +53 -0
  200. package/dist/commonjs/dataTransformer.d.ts.map +1 -0
  201. package/dist/commonjs/dataTransformer.js +138 -0
  202. package/dist/commonjs/dataTransformer.js.map +1 -0
  203. package/dist/commonjs/diagnostics/instrumentEventData.d.ts +28 -0
  204. package/dist/commonjs/diagnostics/instrumentEventData.d.ts.map +1 -0
  205. package/dist/commonjs/diagnostics/instrumentEventData.js +73 -0
  206. package/dist/commonjs/diagnostics/instrumentEventData.js.map +1 -0
  207. package/dist/commonjs/diagnostics/tracing.d.ts +19 -0
  208. package/dist/commonjs/diagnostics/tracing.d.ts.map +1 -0
  209. package/dist/commonjs/diagnostics/tracing.js +44 -0
  210. package/dist/commonjs/diagnostics/tracing.js.map +1 -0
  211. package/dist/commonjs/eventData.d.ts +295 -0
  212. package/dist/commonjs/eventData.d.ts.map +1 -0
  213. package/dist/commonjs/eventData.js +253 -0
  214. package/dist/commonjs/eventData.js.map +1 -0
  215. package/dist/commonjs/eventDataAdapter.d.ts +69 -0
  216. package/dist/commonjs/eventDataAdapter.d.ts.map +1 -0
  217. package/dist/commonjs/eventDataAdapter.js +38 -0
  218. package/dist/commonjs/eventDataAdapter.js.map +1 -0
  219. package/dist/commonjs/eventDataBatch.d.ts +225 -0
  220. package/dist/commonjs/eventDataBatch.d.ts.map +1 -0
  221. package/dist/commonjs/eventDataBatch.js +254 -0
  222. package/dist/commonjs/eventDataBatch.js.map +1 -0
  223. package/dist/commonjs/eventHubBufferedProducerClient.d.ts +323 -0
  224. package/dist/commonjs/eventHubBufferedProducerClient.d.ts.map +1 -0
  225. package/dist/commonjs/eventHubBufferedProducerClient.js +289 -0
  226. package/dist/commonjs/eventHubBufferedProducerClient.js.map +1 -0
  227. package/dist/commonjs/eventHubConsumerClient.d.ts +277 -0
  228. package/dist/commonjs/eventHubConsumerClient.d.ts.map +1 -0
  229. package/dist/commonjs/eventHubConsumerClient.js +298 -0
  230. package/dist/commonjs/eventHubConsumerClient.js.map +1 -0
  231. package/dist/commonjs/eventHubConsumerClientModels.d.ts +218 -0
  232. package/dist/commonjs/eventHubConsumerClientModels.d.ts.map +1 -0
  233. package/dist/commonjs/eventHubConsumerClientModels.js +5 -0
  234. package/dist/commonjs/eventHubConsumerClientModels.js.map +1 -0
  235. package/dist/commonjs/eventHubProducerClient.d.ts +266 -0
  236. package/dist/commonjs/eventHubProducerClient.d.ts.map +1 -0
  237. package/dist/commonjs/eventHubProducerClient.js +319 -0
  238. package/dist/commonjs/eventHubProducerClient.js.map +1 -0
  239. package/dist/commonjs/eventHubSender.d.ts +227 -0
  240. package/dist/commonjs/eventHubSender.d.ts.map +1 -0
  241. package/dist/commonjs/eventHubSender.js +547 -0
  242. package/dist/commonjs/eventHubSender.js.map +1 -0
  243. package/dist/commonjs/eventPosition.d.ts +73 -0
  244. package/dist/commonjs/eventPosition.d.ts.map +1 -0
  245. package/dist/commonjs/eventPosition.js +128 -0
  246. package/dist/commonjs/eventPosition.js.map +1 -0
  247. package/dist/commonjs/eventProcessor.d.ts +232 -0
  248. package/dist/commonjs/eventProcessor.d.ts.map +1 -0
  249. package/dist/commonjs/eventProcessor.js +371 -0
  250. package/dist/commonjs/eventProcessor.js.map +1 -0
  251. package/dist/commonjs/eventhubConnectionConfig.d.ts +96 -0
  252. package/dist/commonjs/eventhubConnectionConfig.d.ts.map +1 -0
  253. package/dist/commonjs/eventhubConnectionConfig.js +101 -0
  254. package/dist/commonjs/eventhubConnectionConfig.js.map +1 -0
  255. package/dist/commonjs/impl/awaitableQueue.d.ts +25 -0
  256. package/dist/commonjs/impl/awaitableQueue.d.ts.map +1 -0
  257. package/dist/commonjs/impl/awaitableQueue.js +51 -0
  258. package/dist/commonjs/impl/awaitableQueue.js.map +1 -0
  259. package/dist/commonjs/impl/partitionAssigner.d.ts +29 -0
  260. package/dist/commonjs/impl/partitionAssigner.d.ts.map +1 -0
  261. package/dist/commonjs/impl/partitionAssigner.js +58 -0
  262. package/dist/commonjs/impl/partitionAssigner.js.map +1 -0
  263. package/dist/commonjs/impl/partitionGate.d.ts +27 -0
  264. package/dist/commonjs/impl/partitionGate.d.ts.map +1 -0
  265. package/dist/commonjs/impl/partitionGate.js +44 -0
  266. package/dist/commonjs/impl/partitionGate.js.map +1 -0
  267. package/dist/commonjs/impl/partitionKeyToIdMapper.d.ts +6 -0
  268. package/dist/commonjs/impl/partitionKeyToIdMapper.d.ts.map +1 -0
  269. package/dist/commonjs/impl/partitionKeyToIdMapper.js +115 -0
  270. package/dist/commonjs/impl/partitionKeyToIdMapper.js.map +1 -0
  271. package/dist/commonjs/inMemoryCheckpointStore.d.ts +44 -0
  272. package/dist/commonjs/inMemoryCheckpointStore.d.ts.map +1 -0
  273. package/dist/commonjs/inMemoryCheckpointStore.js +96 -0
  274. package/dist/commonjs/inMemoryCheckpointStore.js.map +1 -0
  275. package/dist/commonjs/index.d.ts +21 -0
  276. package/dist/commonjs/index.d.ts.map +1 -0
  277. package/dist/commonjs/index.js +26 -0
  278. package/dist/commonjs/index.js.map +1 -0
  279. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.d.ts +30 -0
  280. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.d.ts.map +1 -0
  281. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js +43 -0
  282. package/dist/commonjs/loadBalancerStrategies/balancedStrategy.js.map +1 -0
  283. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.d.ts +24 -0
  284. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.d.ts.map +1 -0
  285. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js +32 -0
  286. package/dist/commonjs/loadBalancerStrategies/greedyStrategy.js.map +1 -0
  287. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.d.ts +28 -0
  288. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.d.ts.map +1 -0
  289. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.js +248 -0
  290. package/dist/commonjs/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -0
  291. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.d.ts +20 -0
  292. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.d.ts.map +1 -0
  293. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.js +26 -0
  294. package/dist/commonjs/loadBalancerStrategies/unbalancedStrategy.js.map +1 -0
  295. package/dist/commonjs/logger.d.ts +37 -0
  296. package/dist/commonjs/logger.d.ts.map +1 -0
  297. package/dist/commonjs/logger.js +65 -0
  298. package/dist/commonjs/logger.js.map +1 -0
  299. package/dist/commonjs/managementClient.d.ts +145 -0
  300. package/dist/commonjs/managementClient.d.ts.map +1 -0
  301. package/dist/commonjs/managementClient.js +275 -0
  302. package/dist/commonjs/managementClient.js.map +1 -0
  303. package/dist/commonjs/models/private.d.ts +185 -0
  304. package/dist/commonjs/models/private.d.ts.map +1 -0
  305. package/dist/commonjs/models/private.js +5 -0
  306. package/dist/commonjs/models/private.js.map +1 -0
  307. package/dist/commonjs/models/public.d.ts +240 -0
  308. package/dist/commonjs/models/public.d.ts.map +1 -0
  309. package/dist/commonjs/models/public.js +21 -0
  310. package/dist/commonjs/models/public.js.map +1 -0
  311. package/dist/commonjs/package.json +3 -0
  312. package/dist/commonjs/partitionProcessor.d.ts +134 -0
  313. package/dist/commonjs/partitionProcessor.d.ts.map +1 -0
  314. package/dist/commonjs/partitionProcessor.js +138 -0
  315. package/dist/commonjs/partitionProcessor.js.map +1 -0
  316. package/dist/commonjs/partitionPump.d.ts +38 -0
  317. package/dist/commonjs/partitionPump.d.ts.map +1 -0
  318. package/dist/commonjs/partitionPump.js +171 -0
  319. package/dist/commonjs/partitionPump.js.map +1 -0
  320. package/dist/commonjs/partitionReceiver.d.ts +82 -0
  321. package/dist/commonjs/partitionReceiver.d.ts.map +1 -0
  322. package/dist/commonjs/partitionReceiver.js +335 -0
  323. package/dist/commonjs/partitionReceiver.js.map +1 -0
  324. package/dist/commonjs/pumpManager.d.ts +72 -0
  325. package/dist/commonjs/pumpManager.d.ts.map +1 -0
  326. package/dist/commonjs/pumpManager.js +122 -0
  327. package/dist/commonjs/pumpManager.js.map +1 -0
  328. package/{types/latest → dist/commonjs}/tsdoc-metadata.json +1 -1
  329. package/dist/commonjs/util/connectionStringUtils.d.ts +52 -0
  330. package/dist/commonjs/util/connectionStringUtils.d.ts.map +1 -0
  331. package/dist/commonjs/util/connectionStringUtils.js +51 -0
  332. package/dist/commonjs/util/connectionStringUtils.js.map +1 -0
  333. package/dist/commonjs/util/constants.d.ts +25 -0
  334. package/dist/commonjs/util/constants.d.ts.map +1 -0
  335. package/dist/commonjs/util/constants.js +30 -0
  336. package/dist/commonjs/util/constants.js.map +1 -0
  337. package/dist/commonjs/util/delayWithoutThrow.d.ts +8 -0
  338. package/dist/commonjs/util/delayWithoutThrow.d.ts.map +1 -0
  339. package/dist/commonjs/util/delayWithoutThrow.js +20 -0
  340. package/dist/commonjs/util/delayWithoutThrow.js.map +1 -0
  341. package/dist/commonjs/util/error.d.ts +39 -0
  342. package/dist/commonjs/util/error.d.ts.map +1 -0
  343. package/dist/commonjs/util/error.js +110 -0
  344. package/dist/commonjs/util/error.js.map +1 -0
  345. package/dist/commonjs/util/getPromiseParts.d.ts +10 -0
  346. package/dist/commonjs/util/getPromiseParts.d.ts.map +1 -0
  347. package/dist/commonjs/util/getPromiseParts.js +23 -0
  348. package/dist/commonjs/util/getPromiseParts.js.map +1 -0
  349. package/dist/commonjs/util/operationOptions.d.ts +16 -0
  350. package/dist/commonjs/util/operationOptions.d.ts.map +1 -0
  351. package/dist/commonjs/util/operationOptions.js +5 -0
  352. package/dist/commonjs/util/operationOptions.js.map +1 -0
  353. package/dist/commonjs/util/parseEndpoint.d.ts +11 -0
  354. package/dist/commonjs/util/parseEndpoint.d.ts.map +1 -0
  355. package/dist/commonjs/util/parseEndpoint.js +20 -0
  356. package/dist/commonjs/util/parseEndpoint.js.map +1 -0
  357. package/dist/commonjs/util/retries.d.ts +6 -0
  358. package/dist/commonjs/util/retries.d.ts.map +1 -0
  359. package/dist/commonjs/util/retries.js +16 -0
  360. package/dist/commonjs/util/retries.js.map +1 -0
  361. package/dist/commonjs/util/runtimeInfo.d.ts +6 -0
  362. package/dist/commonjs/util/runtimeInfo.d.ts.map +1 -0
  363. package/dist/commonjs/util/runtimeInfo.js +15 -0
  364. package/dist/commonjs/util/runtimeInfo.js.map +1 -0
  365. package/dist/commonjs/util/timerLoop.d.ts +26 -0
  366. package/dist/commonjs/util/timerLoop.d.ts.map +1 -0
  367. package/dist/commonjs/util/timerLoop.js +30 -0
  368. package/dist/commonjs/util/timerLoop.js.map +1 -0
  369. package/dist/commonjs/util/typeGuards.d.ts +8 -0
  370. package/dist/commonjs/util/typeGuards.d.ts.map +1 -0
  371. package/dist/commonjs/util/typeGuards.js +15 -0
  372. package/dist/commonjs/util/typeGuards.js.map +1 -0
  373. package/dist/commonjs/util/utils.d.ts +7 -0
  374. package/dist/commonjs/util/utils.d.ts.map +1 -0
  375. package/dist/commonjs/util/utils.js +16 -0
  376. package/dist/commonjs/util/utils.js.map +1 -0
  377. package/dist/commonjs/withAuth.d.ts +25 -0
  378. package/dist/commonjs/withAuth.d.ts.map +1 -0
  379. package/dist/commonjs/withAuth.js +88 -0
  380. package/dist/commonjs/withAuth.js.map +1 -0
  381. package/dist/esm/batchingPartitionChannel.d.ts +94 -0
  382. package/dist/esm/batchingPartitionChannel.d.ts.map +1 -0
  383. package/dist/esm/batchingPartitionChannel.js +248 -0
  384. package/dist/esm/batchingPartitionChannel.js.map +1 -0
  385. package/dist/esm/connectionContext.d.ts +108 -0
  386. package/dist/esm/connectionContext.d.ts.map +1 -0
  387. package/dist/esm/connectionContext.js +318 -0
  388. package/dist/esm/connectionContext.js.map +1 -0
  389. package/dist/esm/dataTransformer.d.ts +53 -0
  390. package/dist/esm/dataTransformer.d.ts.map +1 -0
  391. package/dist/esm/dataTransformer.js +133 -0
  392. package/dist/esm/dataTransformer.js.map +1 -0
  393. package/dist/esm/diagnostics/instrumentEventData.d.ts +28 -0
  394. package/dist/esm/diagnostics/instrumentEventData.d.ts.map +1 -0
  395. package/dist/esm/diagnostics/instrumentEventData.js +68 -0
  396. package/dist/esm/diagnostics/instrumentEventData.js.map +1 -0
  397. package/dist/esm/diagnostics/tracing.d.ts +19 -0
  398. package/dist/esm/diagnostics/tracing.d.ts.map +1 -0
  399. package/dist/esm/diagnostics/tracing.js +40 -0
  400. package/dist/esm/diagnostics/tracing.js.map +1 -0
  401. package/dist/esm/eventData.d.ts +295 -0
  402. package/dist/esm/eventData.d.ts.map +1 -0
  403. package/dist/esm/eventData.js +245 -0
  404. package/dist/esm/eventData.js.map +1 -0
  405. package/dist/esm/eventDataAdapter.d.ts +69 -0
  406. package/dist/esm/eventDataAdapter.d.ts.map +1 -0
  407. package/dist/esm/eventDataAdapter.js +35 -0
  408. package/dist/esm/eventDataAdapter.js.map +1 -0
  409. package/dist/esm/eventDataBatch.d.ts +225 -0
  410. package/dist/esm/eventDataBatch.d.ts.map +1 -0
  411. package/dist/esm/eventDataBatch.js +249 -0
  412. package/dist/esm/eventDataBatch.js.map +1 -0
  413. package/dist/esm/eventHubBufferedProducerClient.d.ts +323 -0
  414. package/dist/esm/eventHubBufferedProducerClient.d.ts.map +1 -0
  415. package/dist/esm/eventHubBufferedProducerClient.js +285 -0
  416. package/dist/esm/eventHubBufferedProducerClient.js.map +1 -0
  417. package/dist/esm/eventHubConsumerClient.d.ts +277 -0
  418. package/dist/esm/eventHubConsumerClient.d.ts.map +1 -0
  419. package/dist/esm/eventHubConsumerClient.js +293 -0
  420. package/dist/esm/eventHubConsumerClient.js.map +1 -0
  421. package/dist/esm/eventHubConsumerClientModels.d.ts +218 -0
  422. package/dist/esm/eventHubConsumerClientModels.d.ts.map +1 -0
  423. package/dist/esm/eventHubConsumerClientModels.js +4 -0
  424. package/dist/esm/eventHubConsumerClientModels.js.map +1 -0
  425. package/dist/esm/eventHubProducerClient.d.ts +266 -0
  426. package/dist/esm/eventHubProducerClient.d.ts.map +1 -0
  427. package/dist/esm/eventHubProducerClient.js +315 -0
  428. package/dist/esm/eventHubProducerClient.js.map +1 -0
  429. package/dist/esm/eventHubSender.d.ts +227 -0
  430. package/dist/esm/eventHubSender.d.ts.map +1 -0
  431. package/dist/esm/eventHubSender.js +541 -0
  432. package/dist/esm/eventHubSender.js.map +1 -0
  433. package/dist/esm/eventPosition.d.ts +73 -0
  434. package/dist/esm/eventPosition.d.ts.map +1 -0
  435. package/dist/esm/eventPosition.js +121 -0
  436. package/dist/esm/eventPosition.js.map +1 -0
  437. package/dist/esm/eventProcessor.d.ts +232 -0
  438. package/dist/esm/eventProcessor.d.ts.map +1 -0
  439. package/dist/esm/eventProcessor.js +367 -0
  440. package/dist/esm/eventProcessor.js.map +1 -0
  441. package/dist/esm/eventhubConnectionConfig.d.ts +96 -0
  442. package/dist/esm/eventhubConnectionConfig.d.ts.map +1 -0
  443. package/dist/esm/eventhubConnectionConfig.js +98 -0
  444. package/dist/esm/eventhubConnectionConfig.js.map +1 -0
  445. package/dist/esm/impl/awaitableQueue.d.ts +25 -0
  446. package/dist/esm/impl/awaitableQueue.d.ts.map +1 -0
  447. package/dist/esm/impl/awaitableQueue.js +47 -0
  448. package/dist/esm/impl/awaitableQueue.js.map +1 -0
  449. package/dist/esm/impl/partitionAssigner.d.ts +29 -0
  450. package/dist/esm/impl/partitionAssigner.d.ts.map +1 -0
  451. package/dist/esm/impl/partitionAssigner.js +54 -0
  452. package/dist/esm/impl/partitionAssigner.js.map +1 -0
  453. package/dist/esm/impl/partitionGate.d.ts +27 -0
  454. package/dist/esm/impl/partitionGate.d.ts.map +1 -0
  455. package/dist/esm/impl/partitionGate.js +40 -0
  456. package/dist/esm/impl/partitionGate.js.map +1 -0
  457. package/dist/esm/impl/partitionKeyToIdMapper.d.ts +6 -0
  458. package/dist/esm/impl/partitionKeyToIdMapper.d.ts.map +1 -0
  459. package/dist/esm/impl/partitionKeyToIdMapper.js +111 -0
  460. package/dist/esm/impl/partitionKeyToIdMapper.js.map +1 -0
  461. package/dist/esm/inMemoryCheckpointStore.d.ts +44 -0
  462. package/dist/esm/inMemoryCheckpointStore.d.ts.map +1 -0
  463. package/dist/esm/inMemoryCheckpointStore.js +92 -0
  464. package/dist/esm/inMemoryCheckpointStore.js.map +1 -0
  465. package/dist/esm/index.d.ts +21 -0
  466. package/dist/esm/index.d.ts.map +1 -0
  467. package/dist/esm/index.js +12 -0
  468. package/dist/esm/index.js.map +1 -0
  469. package/dist/esm/loadBalancerStrategies/balancedStrategy.d.ts +30 -0
  470. package/dist/esm/loadBalancerStrategies/balancedStrategy.d.ts.map +1 -0
  471. package/dist/esm/loadBalancerStrategies/balancedStrategy.js +39 -0
  472. package/dist/esm/loadBalancerStrategies/balancedStrategy.js.map +1 -0
  473. package/dist/esm/loadBalancerStrategies/greedyStrategy.d.ts +24 -0
  474. package/dist/esm/loadBalancerStrategies/greedyStrategy.d.ts.map +1 -0
  475. package/dist/esm/loadBalancerStrategies/greedyStrategy.js +28 -0
  476. package/dist/esm/loadBalancerStrategies/greedyStrategy.js.map +1 -0
  477. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.d.ts +28 -0
  478. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.d.ts.map +1 -0
  479. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.js +245 -0
  480. package/dist/esm/loadBalancerStrategies/loadBalancingStrategy.js.map +1 -0
  481. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.d.ts +20 -0
  482. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.d.ts.map +1 -0
  483. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.js +22 -0
  484. package/dist/esm/loadBalancerStrategies/unbalancedStrategy.js.map +1 -0
  485. package/dist/esm/logger.d.ts +37 -0
  486. package/dist/esm/logger.d.ts.map +1 -0
  487. package/dist/esm/logger.js +56 -0
  488. package/dist/esm/logger.js.map +1 -0
  489. package/dist/esm/managementClient.d.ts +145 -0
  490. package/dist/esm/managementClient.d.ts.map +1 -0
  491. package/dist/esm/managementClient.js +271 -0
  492. package/dist/esm/managementClient.js.map +1 -0
  493. package/dist/esm/models/private.d.ts +185 -0
  494. package/dist/esm/models/private.d.ts.map +1 -0
  495. package/dist/esm/models/private.js +4 -0
  496. package/dist/esm/models/private.js.map +1 -0
  497. package/dist/esm/models/public.d.ts +240 -0
  498. package/dist/esm/models/public.d.ts.map +1 -0
  499. package/dist/esm/models/public.js +18 -0
  500. package/dist/esm/models/public.js.map +1 -0
  501. package/dist/esm/package.json +3 -0
  502. package/dist/esm/partitionProcessor.d.ts +134 -0
  503. package/dist/esm/partitionProcessor.d.ts.map +1 -0
  504. package/dist/esm/partitionProcessor.js +134 -0
  505. package/dist/esm/partitionProcessor.js.map +1 -0
  506. package/dist/esm/partitionPump.d.ts +38 -0
  507. package/dist/esm/partitionPump.d.ts.map +1 -0
  508. package/dist/esm/partitionPump.js +166 -0
  509. package/dist/esm/partitionPump.js.map +1 -0
  510. package/dist/esm/partitionReceiver.d.ts +82 -0
  511. package/dist/esm/partitionReceiver.d.ts.map +1 -0
  512. package/dist/esm/partitionReceiver.js +330 -0
  513. package/dist/esm/partitionReceiver.js.map +1 -0
  514. package/dist/esm/pumpManager.d.ts +72 -0
  515. package/dist/esm/pumpManager.d.ts.map +1 -0
  516. package/dist/esm/pumpManager.js +118 -0
  517. package/dist/esm/pumpManager.js.map +1 -0
  518. package/dist/esm/util/connectionStringUtils.d.ts +52 -0
  519. package/dist/esm/util/connectionStringUtils.d.ts.map +1 -0
  520. package/dist/esm/util/connectionStringUtils.js +48 -0
  521. package/dist/esm/util/connectionStringUtils.js.map +1 -0
  522. package/dist/esm/util/constants.d.ts +25 -0
  523. package/dist/esm/util/constants.d.ts.map +1 -0
  524. package/dist/esm/util/constants.js +27 -0
  525. package/dist/esm/util/constants.js.map +1 -0
  526. package/dist/esm/util/delayWithoutThrow.d.ts +8 -0
  527. package/dist/esm/util/delayWithoutThrow.d.ts.map +1 -0
  528. package/dist/esm/util/delayWithoutThrow.js +17 -0
  529. package/dist/esm/util/delayWithoutThrow.js.map +1 -0
  530. package/dist/esm/util/error.d.ts +39 -0
  531. package/dist/esm/util/error.d.ts.map +1 -0
  532. package/dist/esm/util/error.js +103 -0
  533. package/dist/esm/util/error.js.map +1 -0
  534. package/dist/esm/util/getPromiseParts.d.ts +10 -0
  535. package/dist/esm/util/getPromiseParts.d.ts.map +1 -0
  536. package/dist/esm/util/getPromiseParts.js +20 -0
  537. package/dist/esm/util/getPromiseParts.js.map +1 -0
  538. package/dist/esm/util/operationOptions.d.ts +16 -0
  539. package/dist/esm/util/operationOptions.d.ts.map +1 -0
  540. package/dist/esm/util/operationOptions.js +4 -0
  541. package/dist/esm/util/operationOptions.js.map +1 -0
  542. package/dist/esm/util/parseEndpoint.d.ts +11 -0
  543. package/dist/esm/util/parseEndpoint.d.ts.map +1 -0
  544. package/dist/esm/util/parseEndpoint.js +17 -0
  545. package/dist/esm/util/parseEndpoint.js.map +1 -0
  546. package/dist/esm/util/retries.d.ts +6 -0
  547. package/dist/esm/util/retries.d.ts.map +1 -0
  548. package/dist/esm/util/retries.js +13 -0
  549. package/dist/esm/util/retries.js.map +1 -0
  550. package/dist/esm/util/runtimeInfo.d.ts +6 -0
  551. package/dist/esm/util/runtimeInfo.d.ts.map +1 -0
  552. package/{dist-esm/src → dist/esm}/util/runtimeInfo.js +1 -1
  553. package/{dist-esm/src → dist/esm}/util/runtimeInfo.js.map +1 -1
  554. package/dist/esm/util/timerLoop.d.ts +26 -0
  555. package/dist/esm/util/timerLoop.d.ts.map +1 -0
  556. package/dist/esm/util/timerLoop.js +27 -0
  557. package/dist/esm/util/timerLoop.js.map +1 -0
  558. package/dist/esm/util/typeGuards.d.ts +8 -0
  559. package/dist/esm/util/typeGuards.d.ts.map +1 -0
  560. package/dist/esm/util/typeGuards.js +12 -0
  561. package/dist/esm/util/typeGuards.js.map +1 -0
  562. package/dist/esm/util/utils.d.ts +7 -0
  563. package/dist/esm/util/utils.d.ts.map +1 -0
  564. package/dist/esm/util/utils.js +13 -0
  565. package/dist/esm/util/utils.js.map +1 -0
  566. package/dist/esm/withAuth.d.ts +25 -0
  567. package/dist/esm/withAuth.d.ts.map +1 -0
  568. package/dist/esm/withAuth.js +84 -0
  569. package/dist/esm/withAuth.js.map +1 -0
  570. package/package.json +85 -80
  571. package/dist/index.js +0 -5372
  572. package/dist/index.js.map +0 -1
  573. package/dist-esm/src/batchingPartitionChannel.js.map +0 -1
  574. package/dist-esm/src/connectionContext.js.map +0 -1
  575. package/dist-esm/src/dataTransformer.js.map +0 -1
  576. package/dist-esm/src/diagnostics/instrumentEventData.js.map +0 -1
  577. package/dist-esm/src/diagnostics/tracing.js.map +0 -1
  578. package/dist-esm/src/eventData.js.map +0 -1
  579. package/dist-esm/src/eventDataAdapter.js.map +0 -1
  580. package/dist-esm/src/eventDataBatch.js.map +0 -1
  581. package/dist-esm/src/eventHubBufferedProducerClient.js.map +0 -1
  582. package/dist-esm/src/eventHubConsumerClient.js.map +0 -1
  583. package/dist-esm/src/eventHubConsumerClientModels.js +0 -4
  584. package/dist-esm/src/eventHubConsumerClientModels.js.map +0 -1
  585. package/dist-esm/src/eventHubProducerClient.js.map +0 -1
  586. package/dist-esm/src/eventHubSender.js.map +0 -1
  587. package/dist-esm/src/eventPosition.js.map +0 -1
  588. package/dist-esm/src/eventProcessor.js.map +0 -1
  589. package/dist-esm/src/eventhubConnectionConfig.js.map +0 -1
  590. package/dist-esm/src/impl/awaitableQueue.js.map +0 -1
  591. package/dist-esm/src/impl/partitionAssigner.js.map +0 -1
  592. package/dist-esm/src/inMemoryCheckpointStore.js.map +0 -1
  593. package/dist-esm/src/index.js.map +0 -1
  594. package/dist-esm/src/loadBalancerStrategies/balancedStrategy.js.map +0 -1
  595. package/dist-esm/src/loadBalancerStrategies/greedyStrategy.js.map +0 -1
  596. package/dist-esm/src/loadBalancerStrategies/loadBalancingStrategy.js.map +0 -1
  597. package/dist-esm/src/loadBalancerStrategies/unbalancedStrategy.js.map +0 -1
  598. package/dist-esm/src/logger.js.map +0 -1
  599. package/dist-esm/src/managementClient.js.map +0 -1
  600. package/dist-esm/src/models/private.js +0 -4
  601. package/dist-esm/src/models/private.js.map +0 -1
  602. package/dist-esm/src/models/public.js.map +0 -1
  603. package/dist-esm/src/partitionProcessor.js.map +0 -1
  604. package/dist-esm/src/partitionPump.js.map +0 -1
  605. package/dist-esm/src/partitionReceiver.js.map +0 -1
  606. package/dist-esm/src/pumpManager.js.map +0 -1
  607. package/dist-esm/src/util/constants.js.map +0 -1
  608. package/dist-esm/src/util/delayWithoutThrow.js.map +0 -1
  609. package/dist-esm/src/util/error.js.map +0 -1
  610. package/dist-esm/src/util/operationOptions.js +0 -4
  611. package/dist-esm/src/util/operationOptions.js.map +0 -1
  612. package/dist-esm/src/util/retries.js.map +0 -1
  613. package/dist-esm/src/util/runtimeInfo.browser.js.map +0 -1
  614. package/dist-esm/src/util/typeGuards.js.map +0 -1
  615. package/dist-esm/src/withAuth.js.map +0 -1
  616. package/types/latest/event-hubs.d.ts +0 -1877
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":["../src/logger.ts","../src/partitionProcessor.ts","../src/eventPosition.ts","../src/models/public.ts","../src/dataTransformer.ts","../src/util/constants.ts","../src/eventData.ts","../src/util/retries.ts","../src/util/utils.ts","../src/util/timerLoop.ts","../src/withAuth.ts","../src/partitionReceiver.ts","../src/diagnostics/tracing.ts","../src/diagnostics/instrumentEventData.ts","../src/partitionPump.ts","../src/pumpManager.ts","../src/util/delayWithoutThrow.ts","../src/eventProcessor.ts","../src/util/connectionStringUtils.ts","../src/util/error.ts","../src/managementClient.ts","../src/util/parseEndpoint.ts","../src/eventhubConnectionConfig.ts","../src/util/runtimeInfo.ts","../src/util/typeGuards.ts","../src/connectionContext.ts","../src/loadBalancerStrategies/loadBalancingStrategy.ts","../src/loadBalancerStrategies/balancedStrategy.ts","../src/loadBalancerStrategies/greedyStrategy.ts","../src/inMemoryCheckpointStore.ts","../src/impl/partitionGate.ts","../src/loadBalancerStrategies/unbalancedStrategy.ts","../src/eventHubConsumerClient.ts","../src/eventDataBatch.ts","../src/eventHubSender.ts","../src/eventHubProducerClient.ts","../src/impl/awaitableQueue.ts","../src/util/getPromiseParts.ts","../src/batchingPartitionChannel.ts","../src/impl/partitionKeyToIdMapper.ts","../src/impl/partitionAssigner.ts","../src/eventHubBufferedProducerClient.ts","../src/eventDataAdapter.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureLogger, AzureLogLevel, createClientLogger, Debugger } from \"@azure/logger\";\nimport { isObjectWithProperties } from \"@azure/core-util\";\n\n/**\n * The `@azure/logger` configuration for this package.\n * This will output logs using the `azure:event-hubs` namespace prefix.\n */\nexport const logger = createClientLogger(\"event-hubs\");\n\n/**\n * Logs the error's stack trace to \"verbose\" if a stack trace is available.\n * @param error - Error containing a stack trace.\n * @internal\n */\nexport function logErrorStackTrace(error: unknown): void {\n if (isObjectWithProperties(error, [\"stack\"])) {\n logger.verbose(error.stack);\n }\n}\n\n/**\n * @internal\n */\nexport function createReceiverLogPrefix(\n consumerId: string,\n connectionId: string,\n partitionId: string,\n): string {\n return `[${connectionId}] Receiver P${partitionId}-${consumerId}`;\n}\n\n/**\n * @internal\n */\nexport function createSenderLogPrefix(senderId: string, connectionId: string): string {\n return `[${connectionId}] Sender ${senderId}`;\n}\n\n/**\n * @internal\n */\nexport function createManagementLogPrefix(connectionId: string): string {\n return `[${connectionId}] Management`;\n}\n\n/**\n * @internal\n */\nexport type SimpleLogger = {\n [Property in keyof AzureLogger]: Debugger[\"log\"];\n};\n\nfunction createLogFunction(\n azureLogger: AzureLogger,\n prefix: string,\n level: AzureLogLevel,\n): (arg: any, ...args: any[]) => void {\n return (arg: any, ...args: any[]) =>\n azureLogger[level](\n ...(typeof arg === \"string\" ? [`${prefix}: ${arg}`] : [prefix, arg]),\n ...args,\n );\n}\n\n/**\n * @internal\n */\nexport function createSimpleLogger(azureLogger: AzureLogger, prefix: string): SimpleLogger {\n return {\n info: createLogFunction(azureLogger, prefix, \"info\"),\n error: createLogFunction(azureLogger, prefix, \"error\"),\n verbose: createLogFunction(azureLogger, prefix, \"verbose\"),\n warning: createLogFunction(azureLogger, prefix, \"warning\"),\n };\n}\n\n/** @internal */\nexport function logObj(obj: unknown): void {\n JSON.stringify(obj, undefined, 2);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n BasicPartitionProperties,\n PartitionContext,\n SubscriptionEventHandlers,\n} from \"./eventHubConsumerClientModels\";\nimport { CheckpointStore } from \"./eventProcessor\";\nimport { CloseReason } from \"./models/public\";\nimport { LastEnqueuedEventProperties } from \"./partitionReceiver\";\nimport { ReceivedEventData } from \"./eventData\";\nimport { logger } from \"./logger\";\n\n/**\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * When the `updateCheckpoint()` method on the `PartitionProcessor` class is called by the user, a\n * `Checkpoint` is created internally. It is then stored in the storage solution implemented by the\n * `CheckpointManager` chosen by the user when creating an `EventProcessor`.\n *\n * Users are never expected to interact with `Checkpoint` directly. This interface exists to support the\n * internal workings of `EventProcessor` and `CheckpointManager`.\n **/\nexport interface Checkpoint {\n /**\n * The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n */\n fullyQualifiedNamespace: string;\n /**\n * The event hub name\n */\n eventHubName: string;\n /**\n * The consumer group name\n */\n consumerGroup: string;\n /**\n * The identifier of the Event Hub partition\n */\n partitionId: string;\n /**\n * The sequence number of the event\n */\n sequenceNumber: number;\n /**\n * The offset of the event.\n */\n offset: string;\n}\n\n/**\n * The `PartitionProcessor` is responsible for processing events received from Event Hubs when using `EventProcessor`\n *\n * The EventProcessor creates a new instance of the PartitionProcessor for each partition of the event hub it starts processing. When you extend the `PartitionProcessor` in order to customize it as you see fit,\n * - Override the `processEvents()` method to add the code to process the received events. This is also a good place to update the checkpoints using the `updateCheckpoint()` method\n * - Optionally override the `processError()` method to handle any error that might have occurred when processing the events.\n * - Optionally override the `initialize()` method to implement any set up related tasks you would want to carry out before starting to receive events from the partition\n * - Optionally override the `close()` method to implement any tear down or clean up tasks you would want to carry out.\n * @internal\n */\nexport class PartitionProcessor implements PartitionContext {\n private _lastEnqueuedEventProperties?: LastEnqueuedEventProperties;\n\n constructor(\n private _eventHandlers: SubscriptionEventHandlers,\n private _checkpointStore: CheckpointStore,\n private _context: BasicPartitionProperties & {\n eventProcessorId: string;\n },\n ) {}\n\n /**\n * Information on the last enqueued event in the partition that is being processed.\n * This property is updated by the `EventProcessor` if the `trackLastEnqueuedEventProperties` option is set to true\n * when creating an instance of EventProcessor\n * @readonly\n */\n public get lastEnqueuedEventProperties(): LastEnqueuedEventProperties {\n return this._lastEnqueuedEventProperties!;\n }\n\n /**\n * Information on the last enqueued event in the partition that is being processed.\n * This property is updated by the `EventProcessor` if the `trackLastEnqueuedEventProperties` option is set to true\n * when creating an instance of EventProcessor\n */\n public set lastEnqueuedEventProperties(properties: LastEnqueuedEventProperties) {\n this._lastEnqueuedEventProperties = properties;\n }\n\n /**\n * The fully qualified namespace from where the current partition is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get fullyQualifiedNamespace(): string {\n return this._context.fullyQualifiedNamespace;\n }\n\n /**\n * The name of the consumer group from where the current partition is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get consumerGroup(): string {\n return this._context.consumerGroup!;\n }\n\n /**\n * The name of the event hub to which the current partition belongs. It is set by the `EventProcessor`\n * @readonly\n */\n public get eventHubName(): string {\n return this._context.eventHubName;\n }\n\n /**\n * The identifier of the Event Hub partition that is being processed. It is set by the `EventProcessor`\n * @readonly\n */\n public get partitionId(): string {\n return this._context.partitionId;\n }\n\n /**\n * The unique identifier of the `EventProcessor` that has spawned the current instance of `PartitionProcessor`. This is set by the `EventProcessor`\n */\n public get eventProcessorId(): string {\n return this._context.eventProcessorId;\n }\n\n /**\n * This method is called when the `EventProcessor` takes ownership of a new partition and before any\n * events are received.\n */\n async initialize(): Promise<void> {\n return this._eventHandlers.processInitialize?.(this);\n }\n\n /**\n * This method is called before the partition processor is closed by the EventProcessor.\n *\n * @param reason - The reason for closing this partition processor.\n */\n async close(reason: CloseReason): Promise<void> {\n if (this._eventHandlers.processClose) {\n await this._eventHandlers.processClose(reason, this);\n }\n }\n\n /**\n * This method is called when new events are received.\n *\n * This is also a good place to update checkpoints as appropriate.\n *\n * @param event - The received events to be processed.\n */\n async processEvents(events: ReceivedEventData[]): Promise<void> {\n await this._eventHandlers.processEvents(events, this);\n }\n\n /**\n * This method is called when an error occurs while receiving events from Event Hubs.\n *\n * @param error - The error to be processed.\n */\n async processError(error: Error): Promise<void> {\n if (this._eventHandlers.processError) {\n try {\n await this._eventHandlers.processError(error, this);\n } catch (err: any) {\n logger.verbose(`Error thrown from user's processError handler : ${err}`);\n }\n }\n }\n\n /**\n * Updates the checkpoint using the event data.\n *\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * @param eventData - The event that you want to update the checkpoint with.\n */\n public async updateCheckpoint(eventData: ReceivedEventData): Promise<void> {\n const checkpoint: Checkpoint = {\n fullyQualifiedNamespace: this._context.fullyQualifiedNamespace,\n eventHubName: this._context.eventHubName,\n consumerGroup: this._context.consumerGroup,\n partitionId: this._context.partitionId,\n sequenceNumber: eventData.sequenceNumber,\n offset: eventData.offset,\n };\n\n await this._checkpointStore!.updateCheckpoint(checkpoint);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Constants, ErrorNameConditionMapper, translate } from \"@azure/core-amqp\";\nimport { isDefined, objectHasProperty } from \"@azure/core-util\";\n\n/**\n * Represents the position of an event in an Event Hub partition, typically used when calling the `subscribe()`\n * method on an `EventHubConsumerClient` to specify the position in the partition to begin receiving events from.\n *\n * To get an EventPosition representing the start or end of the stream, use the constants\n * `earliestEventPosition` and `latestEventPosition` respectively.\n *\n */\nexport interface EventPosition {\n /**\n * The offset of the event identified by this position.\n * Expected to be undefined if the position is just created from a sequence number or an enqueued time.\n *\n * The offset is the relative position for an event in the context of the partition.\n * The offset should not be considered a stable value.\n * The same offset may refer to a different event as events reach the age limit for\n * retention and are no longer visible within the partition.\n */\n offset?: string | \"@latest\";\n /**\n * Indicates if the specified offset is inclusive of the event which it identifies.\n * This information is only relevent if the event position was identified by an offset or sequence number.\n * Default value: `false`.\n */\n isInclusive?: boolean;\n /**\n * The enqueued time in UTC of the event identified by this position.\n * When provided as a number this value is the number of milliseconds since the Unix Epoch.\n * Expected to be undefined if the position is just created from a sequence number or an offset.\n */\n enqueuedOn?: Date | number;\n\n /**\n * The sequence number of the event identified by this position.\n * Expected to be undefined if the position is just created from an offset or enqueued time.\n */\n sequenceNumber?: number;\n}\n\n/**\n * @internal\n * Gets the expression to be set as the filter clause when creating the receiver\n * @returns filterExpression\n */\nexport function getEventPositionFilter(eventPosition: EventPosition): string {\n let result;\n // order of preference\n if (isDefined(eventPosition.offset)) {\n result = eventPosition.isInclusive\n ? `${Constants.offsetAnnotation} >= '${eventPosition.offset}'`\n : `${Constants.offsetAnnotation} > '${eventPosition.offset}'`;\n } else if (isDefined(eventPosition.sequenceNumber)) {\n result = eventPosition.isInclusive\n ? `${Constants.sequenceNumberAnnotation} >= '${eventPosition.sequenceNumber}'`\n : `${Constants.sequenceNumberAnnotation} > '${eventPosition.sequenceNumber}'`;\n } else if (isDefined(eventPosition.enqueuedOn)) {\n const time =\n eventPosition.enqueuedOn instanceof Date\n ? eventPosition.enqueuedOn.getTime()\n : eventPosition.enqueuedOn;\n result = `${Constants.enqueuedTimeAnnotation} > '${time}'`;\n }\n\n if (!result) {\n throw translate({\n condition: ErrorNameConditionMapper.ArgumentError,\n description: \"No starting position was set in the EventPosition.\",\n });\n }\n return result;\n}\n\n/**\n * @internal\n */\nexport function isLatestPosition(eventPosition: EventPosition): boolean {\n if (eventPosition.offset === \"@latest\") {\n return true;\n }\n\n return false;\n}\n\n/**\n * Gets the `EventPosition` corresponding to the location of the the first event present in the partition.\n * Pass this position to the `EventHubConsumerClient.subscribe()` method to begin receiving events from the\n * first event in the partition which has not expired due to the retention policy.\n */\nexport const earliestEventPosition: EventPosition = {\n offset: \"-1:-1\",\n};\n\n/**\n * Gets the `EventPosition` corresponding to the end of the partition.\n * Pass this position to the `EventHubConsumerClient.subscribe()` method to begin receiving events from the\n * event that is enqueued right after the method call.\n * @returns EventPosition\n */\nexport const latestEventPosition: EventPosition = {\n offset: \"@latest\",\n};\n\n/**\n * @internal\n */\nexport function validateEventPositions(\n position: EventPosition | { [partitionId: string]: EventPosition },\n): void {\n if (!isDefined(position)) {\n return;\n }\n\n const keys = Object.keys(position);\n\n if (!keys.length) {\n throw new TypeError(\n \"Invalid value for EventPosition found. Pass an object with either of offset, sequenceNumber or enqueuedOn properties set.\",\n );\n }\n\n if (isEventPosition(position)) {\n validateEventPosition(position);\n return;\n }\n\n const positions = position as { [partitionId: string]: EventPosition };\n for (let i = 0; i < keys.length; i++) {\n if (Object.prototype.hasOwnProperty.call(positions, keys[i])) {\n validateEventPosition(positions[keys[i]]);\n }\n }\n}\n\n/**\n * Determines whether a position is an EventPosition.\n * Does not validate that the position is allowed.\n * @internal\n */\nexport function isEventPosition(position: unknown): position is EventPosition {\n if (!position) {\n return false;\n }\n\n if (objectHasProperty(position, \"offset\") && isDefined(position.offset)) {\n return true;\n }\n\n if (objectHasProperty(position, \"sequenceNumber\") && isDefined(position.sequenceNumber)) {\n return true;\n }\n\n if (objectHasProperty(position, \"enqueuedOn\") && isDefined(position.enqueuedOn)) {\n return true;\n }\n\n return false;\n}\n\nfunction validateEventPosition(position: EventPosition): void {\n if (!isDefined(position)) {\n return;\n }\n const offsetPresent = isDefined(position.offset);\n const sequenceNumberPresent = isDefined(position.sequenceNumber);\n const enqueuedOnPresent = isDefined(position.enqueuedOn);\n\n if (\n (offsetPresent && sequenceNumberPresent) ||\n (offsetPresent && enqueuedOnPresent) ||\n (enqueuedOnPresent && sequenceNumberPresent)\n ) {\n throw new TypeError(\n \"Invalid value for EventPosition found. Set only one of offset, sequenceNumber or enqueuedOn properties.\",\n );\n }\n\n if (!offsetPresent && !enqueuedOnPresent && !sequenceNumberPresent) {\n throw new TypeError(\n \"Invalid value for EventPosition found. Pass an object with either of offset, sequenceNumber or enqueuedOn properties set.\",\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { RetryOptions, WebSocketOptions } from \"@azure/core-amqp\";\nimport { OperationOptions } from \"../util/operationOptions\";\n\n/**\n * The set of options to configure the behavior of `getEventHubProperties`.\n * - `abortSignal` : An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.\n * - `parentSpan` : The `Span` or `SpanContext` to use as the `parent` of the span created while calling this operation.\n */\nexport interface GetEventHubPropertiesOptions extends OperationOptions {}\n\n/**\n * The set of options to configure the behavior of `getPartitionProperties`.\n * - `abortSignal` : An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.\n * - `parentSpan` : The `Span` or `SpanContext` to use as the `parent` of the span created while calling this operation.\n */\nexport interface GetPartitionPropertiesOptions extends OperationOptions {}\n\n/**\n * The set of options to configure the behavior of `getPartitionIds`.\n * - `abortSignal` : An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.\n * - `parentSpan` : The `Span` or `SpanContext` to use as the `parent` of the span created while calling this operation.\n */\nexport interface GetPartitionIdsOptions extends OperationOptions {}\n\n/**\n * Options to configure the `sendBatch` method on the `EventHubProducerClient`\n * when sending an array of events.\n * If `partitionId` is set, `partitionKey` must not be set and vice versa.\n *\n * - `partitionId` : The partition this batch will be sent to.\n * - `partitionKey` : A value that is hashed to produce a partition assignment.\n * - `abortSignal` : A signal used to cancel the send operation.\n */\nexport interface SendBatchOptions extends OperationOptions {\n /**\n * The partition this batch will be sent to.\n * If this value is set then partitionKey can not be set.\n */\n 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 producer was created using a `partitionId`.\n */\n partitionKey?: string;\n}\n\n/**\n * The set of options to configure the `send` operation on the `EventHubProducer`.\n * - `partitionKey` : A value that is hashed to produce a partition assignment.\n * - `abortSignal` : A signal used to cancel the send operation.\n *\n * Example usage:\n * ```js\n * {\n * partitionKey: 'foo'\n * }\n * ```\n *\n * @internal\n */\nexport interface SendOptions extends OperationOptions {\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 producer was created using a `partitionId`.\n */\n partitionKey?: string;\n}\n\n/**\n * An enum representing the different reasons for an `EventHubConsumerClient` to stop processing\n * events from a partition in a consumer group of an Event Hub.\n */\nexport enum CloseReason {\n /**\n * Ownership of the partition was lost or transitioned to a new processor instance.\n */\n OwnershipLost = \"OwnershipLost\",\n /**\n * The EventProcessor was shutdown.\n */\n Shutdown = \"Shutdown\",\n}\n\n/**\n * Describes the options that can be provided while creating the EventHubClient.\n * - `userAgent` : A string to append to the built in user agent string that is passed as a connection property\n * to the service.\n * - `webSocketOptions` : Options to configure the channelling of the AMQP connection over Web Sockets.\n * - `websocket` : The WebSocket constructor used to create an AMQP connection if you choose to make the connection\n * over a WebSocket.\n * - `webSocketConstructorOptions` : Options to pass to the Websocket constructor when you choose to make the connection\n * over a WebSocket.\n * - `retryOptions` : The retry options for all the operations on the client/producer/consumer.\n * - `maxRetries` : The number of times the operation can be retried in case of a retryable error.\n * - `maxRetryDelayInMs`: The maximum delay between retries. Applicable only when performing exponential retries.\n * - `mode`: Which retry mode to apply, specified by the `RetryMode` enum. Options are `Exponential` and `Fixed`. Defaults to `Fixed`.\n * - `retryDelayInMs`: Amount of time to wait in milliseconds before making the next attempt. When `mode` is set to `Exponential`,\n * this is used to compute the exponentially increasing delays between retries. Default: 30000 milliseconds.\n * - `timeoutInMs`: Amount of time in milliseconds to wait before the operation times out. This will trigger a retry if there are any\n * retry attempts remaining. Default value: 60000 milliseconds.\n *\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n *\n * Example usage:\n * ```js\n * {\n * retryOptions: {\n * maxRetries: 4\n * }\n * }\n * ```\n */\nexport interface EventHubClientOptions {\n /**\n * A custom endpoint to use when connecting to the Event Hubs service.\n * This can be useful when your network does not allow connecting to the\n * standard Azure Event Hubs endpoint address, but does allow connecting\n * through an intermediary.\n *\n * Example: \"https://my.custom.endpoint:100/\"\n */\n customEndpointAddress?: string;\n /**\n * Options to configure the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n *\n */\n retryOptions?: RetryOptions;\n /**\n * Options to configure the channelling of the AMQP connection over Web Sockets.\n */\n webSocketOptions?: WebSocketOptions;\n /**\n * Value that is appended to the built in user agent string that is passed to the Event Hubs service.\n */\n userAgent?: string;\n /**\n * A unique name used to identify the client. If not provided, a GUID will be used as the identifier\n */\n identifier?: string;\n}\n\n/**\n * Describes the options that can be provided while creating the EventHubConsumerClient.\n * - `loadBalancingOptions`: Options to tune how the EventHubConsumerClient claims partitions.\n * - `userAgent` : A string to append to the built in user agent string that is passed as a connection property\n * to the service.\n * - `webSocketOptions` : Options to configure the channelling of the AMQP connection over Web Sockets.\n * - `websocket` : The WebSocket constructor used to create an AMQP connection if you choose to make the connection\n * over a WebSocket.\n * - `webSocketConstructorOptions` : Options to pass to the Websocket constructor when you choose to make the connection\n * over a WebSocket.\n * - `retryOptions` : The retry options for all the operations on the client/producer/consumer.\n * - `maxRetries` : The number of times the operation can be retried in case of a retryable error.\n * - `maxRetryDelayInMs`: The maximum delay between retries. Applicable only when performing exponential retries.\n * - `mode`: Which retry mode to apply, specified by the `RetryMode` enum. Options are `Exponential` and `Fixed`. Defaults to `Fixed`.\n * - `retryDelayInMs`: Amount of time to wait in milliseconds before making the next attempt. When `mode` is set to `Exponential`,\n * this is used to compute the exponentially increasing delays between retries. Default: 30000 milliseconds.\n * - `timeoutInMs`: Amount of time in milliseconds to wait before the operation times out. This will trigger a retry if there are any\n * retry attempts remaining. Default value: 60000 milliseconds.\n *\n * A simple usage can be `{ \"maxRetries\": 4 }`.\n *\n * Example usage:\n * ```js\n * {\n * retryOptions: {\n * maxRetries: 4\n * }\n * }\n * ```\n */\nexport interface EventHubConsumerClientOptions extends EventHubClientOptions {\n /**\n * Options to tune how the EventHubConsumerClient claims partitions.\n */\n loadBalancingOptions?: LoadBalancingOptions;\n}\n\n/**\n * An options bag to configure load balancing settings.\n */\nexport interface LoadBalancingOptions {\n /**\n * Whether to apply a greedy or a more balanced approach when\n * claiming partitions.\n *\n * - balanced: The `EventHubConsumerClient` will take a measured approach to\n * requesting partition ownership when balancing work with other clients,\n * slowly claiming partitions until a stabilized distribution is achieved.\n *\n * - greedy: The `EventHubConsumerClient` will attempt to claim ownership\n * of its fair share of partitions aggressively when balancing work with\n * other clients.\n *\n * This option is ignored when either:\n * - `CheckpointStore` is __not__ provided to the `EventHubConsumerClient`.\n * - `subscribe()` is called for a single partition.\n * Default: balanced\n */\n strategy?: \"balanced\" | \"greedy\";\n /**\n * The length of time between attempts to claim partitions.\n * Default: 10000\n */\n updateIntervalInMs?: number;\n /**\n * The length of time a partition claim is valid.\n * Default: 60000\n */\n partitionOwnershipExpirationIntervalInMs?: number;\n}\n\n/**\n * Options to configure the `createBatch` method on the `EventHubProducerClient`.\n * - `partitionKey` : A value that is hashed to produce a partition assignment.\n * - `maxSizeInBytes`: The upper limit for the size of batch.\n * - `abortSignal` : A signal the request to cancel the send operation.\n *\n * Example usage:\n * ```js\n * {\n * partitionKey: 'foo',\n * maxSizeInBytes: 1024 * 1024 // 1 MB\n * }\n * ```\n */\nexport interface CreateBatchOptions extends OperationOptions {\n /**\n * A value that is hashed to produce a partition assignment. It guarantees that messages\n * with the same partitionKey end up in the same partition.\n * If this value is set then partitionId can not be set.\n */\n partitionKey?: string;\n /**\n * The partition this batch will be sent to.\n * If this value is set then partitionKey can not be set.\n */\n partitionId?: string;\n /**\n * The upper limit for the size of batch. The `tryAdd` function will return `false` after this limit is reached.\n */\n maxSizeInBytes?: number;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { logErrorStackTrace, logger } from \"./logger\";\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","// 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.1\",\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/**\n * @internal\n */\nexport const PENDING_PUBLISH_SEQ_NUM_SYMBOL = Symbol.for(\n \"@azure/event-hubs.pendingPublishSequenceNumber\",\n);\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AmqpAnnotatedMessage, Constants } from \"@azure/core-amqp\";\nimport { BodyTypes, defaultDataTransformer } from \"./dataTransformer\";\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\";\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Constants, RetryOptions } from \"@azure/core-amqp\";\n\n/**\n * @internal\n */\nexport function getRetryAttemptTimeoutInMs(retryOptions: RetryOptions = {}): number {\n const { timeoutInMs } = retryOptions;\n return typeof timeoutInMs !== \"number\" || !isFinite(timeoutInMs)\n ? Constants.defaultOperationTimeoutInMs\n : timeoutInMs;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { randomUUID } from \"@azure/core-util\";\n\n/**\n * Returns a random name by appending a guid to the input string as follows:\n * `{name}-{uuid}`.\n * @internal\n */\nexport function getRandomName(prefix?: string): string {\n const str = randomUUID();\n return prefix ? `${prefix}-${str}` : str;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A timer loop is a loop over multiple instances of a promise every specific\n * time interval. It is different from `setInterval` in that it waits until the\n * promise is settled before it goes to the next iteration.\n * */\nexport interface TimerLoop {\n /**\n * Starts the timer loop. If the loop is already running, the loop will be\n * restarted.\n */\n start: () => void;\n /**\n * Stops the timer loop. If the loop is not running, it is a no-op.\n */\n stop: () => void;\n /**\n * Whether the loop is running.\n */\n isRunning: boolean;\n}\n\n/**\n * Creates a timer loop with the given timeout and task.\n * @internal\n */\nexport function createTimerLoop(\n timeoutInMs: number,\n createTask: () => Promise<unknown>,\n): TimerLoop {\n let token: ReturnType<typeof setTimeout>;\n const loop = {\n start: () => {\n clearTimeout(token);\n token = setTimeout(\n () =>\n createTask()\n .catch(() => {\n /** eats up any unhandled error */\n })\n .finally(loop.start),\n timeoutInMs,\n );\n loop.isRunning = true;\n },\n stop: () => {\n clearTimeout(token);\n loop.isRunning = false;\n },\n isRunning: false,\n };\n return loop;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Constants,\n TokenType,\n defaultCancellableLock,\n isSasTokenProvider,\n SasTokenProvider,\n CbsClient,\n CbsResponse,\n} from \"@azure/core-amqp\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AccessToken, TokenCredential } from \"@azure/core-auth\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { createTimerLoop, TimerLoop } from \"./util/timerLoop\";\nimport { SimpleLogger, logObj } from \"./logger\";\n\n/**\n *\n * @param callback - The callback to be executed after the token is obtained.\n * @param context - The connection context.\n * @param audience - The audience for which the token is needed.\n * @param timeoutInMs - The timeout in milliseconds.\n * @param logger - The logger to be used for logging.\n * @returns A TimerLoop that keeps the token refreshed.\n * @internal\n */\nexport async function withAuth(\n callback: () => Promise<void>,\n context: ConnectionContext,\n audience: string,\n timeoutInMs: number,\n logger: SimpleLogger,\n options: {\n abortSignal?: AbortSignalLike;\n },\n): Promise<TimerLoop> {\n const info = await getTokenInfo(context.tokenCredential, audience);\n await setupClaimNegotiation(context, audience, info, timeoutInMs, logger, options);\n await callback();\n async function createTask(): Promise<void> {\n try {\n const info2 = await getTokenInfo(context.tokenCredential, audience);\n await setupClaimNegotiation(context, audience, info2, timeoutInMs, logger, options);\n logger.verbose(\n `next token renewal is in ${info2.timeToLiveInMs} milliseconds @(${new Date(\n Date.now() + info2.timeToLiveInMs,\n ).toString()}).`,\n );\n } catch (err) {\n logger.verbose(`an error occurred while renewing the token: ${logObj(err)}`);\n }\n }\n const loop = createTimerLoop(info.timeToLiveInMs, createTask);\n loop.start();\n return loop;\n}\n\n/**\n * @internal\n */\nexport async function openCbsSession(\n client: CbsClient,\n timeoutAfterStartTime: number,\n { abortSignal }: { abortSignal?: AbortSignalLike } = {},\n): Promise<void> {\n return defaultCancellableLock.acquire(\n client.cbsLock,\n () =>\n client.init({\n abortSignal,\n timeoutInMs: timeoutAfterStartTime - Date.now(),\n }),\n {\n abortSignal,\n timeoutInMs: timeoutAfterStartTime - Date.now(),\n },\n );\n}\n\n/**\n * A representation of an access token.\n * @internal\n */\ninterface TokenInfo {\n /** The access token */\n token: AccessToken;\n /** The type of the token */\n type: TokenType;\n /** The time duration after which the token should be refreshed */\n timeToLiveInMs: number;\n}\n\nasync function getAadToken(cred: TokenCredential): Promise<TokenInfo> {\n const token = await cred.getToken(Constants.aadEventHubsScope);\n if (!token) {\n throw new Error(`Failed to get token from the provided \"TokenCredential\" object`);\n }\n return {\n token,\n type: TokenType.CbsTokenTypeJwt,\n timeToLiveInMs: token.expiresOnTimestamp - Date.now() - 2 * 60 * 1000,\n };\n}\n\nasync function getSharedKeyBasedToken(\n cred: SasTokenProvider,\n audience: string,\n): Promise<TokenInfo> {\n return {\n token: await cred.getToken(audience),\n type: TokenType.CbsTokenTypeSas,\n timeToLiveInMs: 45 * 60 * 1000,\n };\n}\n\nasync function getTokenInfo(\n cred: SasTokenProvider | TokenCredential,\n audience: string,\n): Promise<TokenInfo> {\n return isSasTokenProvider(cred) ? getSharedKeyBasedToken(cred, audience) : getAadToken(cred);\n}\n\nfunction negotiateClaim(\n { token, type }: TokenInfo,\n audience: string,\n cbsSession: CbsClient,\n timeoutAfterStartTime: number,\n lock: string,\n abortSignal?: AbortSignalLike,\n): Promise<CbsResponse> {\n return defaultCancellableLock.acquire(\n lock,\n () =>\n cbsSession.negotiateClaim(audience, token.token, type, {\n abortSignal,\n timeoutInMs: timeoutAfterStartTime - Date.now(),\n }),\n {\n abortSignal,\n timeoutInMs: timeoutAfterStartTime - Date.now(),\n },\n );\n}\n\nasync function setupClaimNegotiation(\n context: ConnectionContext,\n audience: string,\n info: TokenInfo,\n timeoutInMs: number,\n logger: SimpleLogger,\n {\n abortSignal,\n }: {\n abortSignal?: AbortSignalLike;\n },\n): Promise<void> {\n const startTime = Date.now();\n logger.verbose(\n `acquiring cbs lock: '${context.cbsSession.cbsLock}' for creating the cbs session`,\n );\n\n await openCbsSession(context.cbsSession, timeoutInMs + startTime, { abortSignal });\n logger.verbose(`acquiring cbs lock: '${context.negotiateClaimLock}' for cbs auth`);\n await negotiateClaim(\n info,\n audience,\n context.cbsSession,\n timeoutInMs + startTime,\n context.negotiateClaimLock,\n abortSignal,\n );\n logger.verbose(\"claim negotiation succeeded\");\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortController, 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\";\nimport { EventPosition, getEventPositionFilter } from \"./eventPosition\";\nimport {\n createSimpleLogger,\n logErrorStackTrace,\n logObj,\n logger as azureLogger,\n SimpleLogger,\n createReceiverLogPrefix,\n} from \"./logger\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { PartitionReceiverOptions } from \"./models/private\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries\";\nimport { createAbortablePromise } from \"@azure/core-util\";\nimport { TimerLoop } from \"./util/timerLoop\";\nimport { getRandomName } from \"./util/utils\";\nimport { withAuth } from \"./withAuth\";\nimport { receiverIdPropertyName } from \"./util/constants\";\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\n const updatedOptions = {\n abortSignal: aborter.signal,\n abortErrorMsg: StandardAbortMessage,\n cleanupBeforeAbort: () => {\n if (clientAbortSignal?.aborted) {\n cleanupBeforeAbort?.();\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createTracingClient, TracingSpanOptions, TracingSpanKind } from \"@azure/core-tracing\";\nimport { EventHubConnectionConfig } from \"../eventhubConnectionConfig\";\nimport { packageJsonInfo } from \"../util/constants\";\n\n/**\n * The names of the operations that can be instrumented.\n */\nexport type MessagingOperationNames = \"publish\" | \"receive\" | \"process\";\n\n/**\n * The {@link TracingClient} that is used to add tracing spans.\n */\nexport const tracingClient = createTracingClient({\n namespace: \"Microsoft.EventHub\",\n packageName: packageJsonInfo.name,\n packageVersion: packageJsonInfo.version,\n});\n\n/**\n * Creates {@link TracingSpanOptions} from the provided data.\n * @param eventHubConfig - The configuration object containing initial attributes to set on the span.\n * @param spanKind - The {@link TracingSpanKind} for the newly created span.\n * @param operation - The operation type.\n * @returns a {@link TracingSpanOptions} that can be passed to a {@link TracingClient}\n */\nexport function toSpanOptions(\n eventHubConfig: Pick<EventHubConnectionConfig, \"entityPath\" | \"host\">,\n operation?: MessagingOperationNames,\n spanKind?: TracingSpanKind,\n): TracingSpanOptions {\n const propertyName =\n operation === \"process\" || operation === \"receive\"\n ? \"messaging.source.name\"\n : \"messaging.destination.name\";\n\n const spanAttributes = {\n \"messaging.system\": \"eventhubs\",\n [propertyName]: eventHubConfig.entityPath,\n \"net.peer.name\": eventHubConfig.host,\n };\n\n if (operation) {\n spanAttributes[\"messaging.operation\"] = operation;\n }\n\n const spanOptions: TracingSpanOptions = {\n spanAttributes: spanAttributes,\n };\n if (spanKind) {\n spanOptions.spanKind = spanKind;\n }\n return spanOptions;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { EventData, isAmqpAnnotatedMessage } from \"../eventData\";\nimport { TracingContext } from \"@azure/core-tracing\";\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { OperationOptions } from \"../util/operationOptions\";\nimport { MessagingOperationNames, toSpanOptions, tracingClient } from \"./tracing\";\n\n/**\n * @internal\n */\nexport const TRACEPARENT_PROPERTY = \"Diagnostic-Id\";\n\n/**\n * Populates the `EventData` with `SpanContext` info to support trace propagation.\n * Creates and returns a copy of the passed in `EventData` unless the `EventData`\n * has already been instrumented.\n * @param eventData - The `EventData` or `AmqpAnnotatedMessage` to instrument.\n * @param span - The `Span` containing the context to propagate tracing information.\n * @param operation - The type of the operation being performed.\n */\nexport function instrumentEventData(\n eventData: EventData | AmqpAnnotatedMessage,\n options: OperationOptions,\n entityPath: string,\n host: string,\n operation?: MessagingOperationNames,\n): { event: EventData; spanContext: TracingContext | undefined } {\n const props = isAmqpAnnotatedMessage(eventData)\n ? eventData.applicationProperties\n : eventData.properties;\n\n // check if the event has already been instrumented\n const previouslyInstrumented = Boolean(props?.[TRACEPARENT_PROPERTY]);\n\n if (previouslyInstrumented) {\n return { event: eventData, spanContext: undefined };\n }\n\n const { span: messageSpan, updatedOptions } = tracingClient.startSpan(\n \"message\",\n options,\n toSpanOptions({ entityPath, host }, operation, \"producer\"),\n );\n try {\n if (!messageSpan.isRecording()) {\n return {\n event: eventData,\n spanContext: undefined,\n };\n }\n\n const traceParent = tracingClient.createRequestHeaders(\n updatedOptions.tracingOptions?.tracingContext,\n )[\"traceparent\"];\n if (traceParent) {\n const copiedProps = { ...props };\n\n // create a copy so the original isn't modified\n if (isAmqpAnnotatedMessage(eventData)) {\n eventData = { ...eventData, applicationProperties: copiedProps };\n } else {\n eventData = { ...eventData, properties: copiedProps };\n }\n copiedProps[TRACEPARENT_PROPERTY] = traceParent;\n }\n\n return {\n event: eventData,\n spanContext: updatedOptions.tracingOptions?.tracingContext,\n };\n } finally {\n messageSpan.end();\n }\n}\n\n/**\n * Extracts the `SpanContext` from an `EventData` if the context exists.\n * @param eventData - An individual `EventData` object.\n * @internal\n */\nexport function extractSpanContextFromEventData(eventData: EventData): TracingContext | undefined {\n if (!eventData.properties || !eventData.properties[TRACEPARENT_PROPERTY]) {\n return;\n }\n\n const diagnosticId = eventData.properties[TRACEPARENT_PROPERTY];\n return tracingClient.parseTraceparentHeader(diagnosticId);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TracingSpanOptions, TracingSpanLink } from \"@azure/core-tracing\";\nimport { logErrorStackTrace, logger } from \"./logger\";\nimport { AbortController } from \"@azure/abort-controller\";\nimport { CloseReason } from \"./models/public\";\nimport { CommonEventProcessorOptions } from \"./models/private\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { EventHubConnectionConfig } from \"./eventhubConnectionConfig\";\nimport { createReceiver, PartitionReceiver } from \"./partitionReceiver\";\nimport { EventPosition } from \"./eventPosition\";\nimport { MessagingError } from \"@azure/core-amqp\";\nimport { PartitionProcessor } from \"./partitionProcessor\";\nimport { ReceivedEventData } from \"./eventData\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing\";\nimport { extractSpanContextFromEventData } from \"./diagnostics/instrumentEventData\";\n\n/**\n * @internal\n */\nexport class PartitionPump {\n private _partitionProcessor: PartitionProcessor;\n private _processorOptions: CommonEventProcessorOptions;\n private _receiver: PartitionReceiver | undefined;\n private _isReceiving: boolean = false;\n private _isStopped: boolean = false;\n private _abortController: AbortController;\n constructor(\n private _context: ConnectionContext,\n partitionProcessor: PartitionProcessor,\n private readonly _startPosition: EventPosition,\n options: CommonEventProcessorOptions,\n ) {\n this._partitionProcessor = partitionProcessor;\n this._processorOptions = options;\n this._abortController = new AbortController();\n }\n\n public get isReceiving(): boolean {\n return this._isReceiving;\n }\n\n async start(): Promise<void> {\n this._isReceiving = true;\n try {\n await this._partitionProcessor.initialize();\n } catch (err) {\n // swallow the error from the user-defined code\n this._partitionProcessor.processError(err as Error);\n }\n\n // this is intentionally not await'd - the _receiveEvents loop will continue to\n // execute and can be stopped by calling .stop()\n this._receiveEvents(this._partitionProcessor.partitionId);\n logger.info(\n `Successfully started the receiver for partition \"${this._partitionProcessor.partitionId}\".`,\n );\n }\n\n /**\n * Creates a new `PartitionReceiver` and replaces any existing receiver.\n * @param partitionId - The partition the receiver should read messages from.\n * @param lastSeenSequenceNumber - The sequence number to begin receiving messages from (exclusive).\n * If `-1`, then the PartitionPump's startPosition will be used instead.\n */\n private _setOrReplaceReceiver(\n partitionId: string,\n lastSeenSequenceNumber: number,\n ): PartitionReceiver {\n // Determine what the new EventPosition should be.\n // If this PartitionPump has received events, we'll start from the last\n // seen sequenceNumber (exclusive).\n // Otherwise, use the `_startPosition`.\n const currentEventPosition: EventPosition =\n lastSeenSequenceNumber >= 0\n ? {\n sequenceNumber: lastSeenSequenceNumber,\n isInclusive: false,\n }\n : this._startPosition;\n\n // Set or replace the PartitionPump's receiver.\n this._receiver = createReceiver(\n this._context,\n this._partitionProcessor.consumerGroup,\n this._partitionProcessor.eventProcessorId,\n partitionId,\n currentEventPosition,\n {\n ownerLevel: this._processorOptions.ownerLevel,\n trackLastEnqueuedEventProperties: this._processorOptions.trackLastEnqueuedEventProperties,\n retryOptions: this._processorOptions.retryOptions,\n skipParsingBodyAsJson: this._processorOptions.skipParsingBodyAsJson,\n prefetchCount: this._processorOptions.prefetchCount,\n },\n );\n\n return this._receiver;\n }\n\n private async _receiveEvents(partitionId: string): Promise<void> {\n let lastSeenSequenceNumber = -1;\n let receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n\n while (this._isReceiving) {\n try {\n // Check if the receiver was closed so we can recreate it.\n if (receiver.isClosed) {\n receiver = this._setOrReplaceReceiver(partitionId, lastSeenSequenceNumber);\n }\n\n const receivedEvents = await receiver.receiveBatch(\n this._processorOptions.maxBatchSize,\n this._processorOptions.maxWaitTimeInSeconds,\n this._abortController.signal,\n );\n\n if (\n this._processorOptions.trackLastEnqueuedEventProperties &&\n receiver.lastEnqueuedEventProperties\n ) {\n this._partitionProcessor.lastEnqueuedEventProperties =\n receiver.lastEnqueuedEventProperties;\n }\n // avoid calling user's processEvents handler if the pump was stopped while receiving events\n if (!this._isReceiving) {\n return;\n }\n\n if (receivedEvents.length) {\n lastSeenSequenceNumber = receivedEvents[receivedEvents.length - 1].sequenceNumber;\n }\n\n await tracingClient.withSpan(\n \"PartitionPump.process\",\n {},\n () => this._partitionProcessor.processEvents(receivedEvents),\n toProcessingSpanOptions(receivedEvents, this._context.config),\n );\n } catch (err: any) {\n // check if this pump is still receiving\n // it may not be if the EventProcessor was stopped during processEvents\n if (!this._isReceiving) {\n // no longer receiving, so close was called from somewhere else\n return;\n }\n\n logger.warning(\n `An error was thrown while receiving or processing events on partition \"${this._partitionProcessor.partitionId}\"`,\n );\n logErrorStackTrace(err);\n // forward error to user's processError and swallow errors they may throw\n try {\n await this._partitionProcessor.processError(err as Error);\n } catch (errorFromUser) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\"An error was thrown by user's processError method: \", errorFromUser);\n }\n\n // close the partition processor if a non-retryable error was encountered\n if (typeof err !== \"object\" || !(err as MessagingError).retryable) {\n try {\n // If the exception indicates that the partition was stolen (i.e some other consumer with same ownerlevel\n // started consuming the partition), update the closeReason\n if (err.code === \"ReceiverDisconnectedError\") {\n return await this.stop(CloseReason.OwnershipLost);\n }\n // this will close the pump and will break us out of the while loop\n return await this.stop(CloseReason.Shutdown);\n } catch (errorFromStop) {\n // Using verbose over warning because this error is swallowed.\n logger.verbose(\n `An error occurred while closing the receiver with reason ${CloseReason.Shutdown}: `,\n errorFromStop,\n );\n }\n }\n }\n }\n }\n\n async stop(reason: CloseReason): Promise<void> {\n if (this._isStopped) {\n return;\n }\n this._isStopped = true;\n this._isReceiving = false;\n try {\n // Trigger the cancellation before closing the receiver,\n // otherwise the receiver will remove the listener on the abortSignal\n // before it has a chance to be emitted.\n this._abortController.abort();\n await this._receiver?.close();\n await this._partitionProcessor.close(reason);\n } catch (err: any) {\n logger.warning(`An error occurred while closing the receiver: ${err?.name}: ${err?.message}`);\n logErrorStackTrace(err);\n this._partitionProcessor.processError(err);\n throw err;\n }\n }\n}\n\n/**\n * @internal\n */\nexport function toProcessingSpanOptions(\n receivedEvents: ReceivedEventData[],\n eventHubProperties: Pick<EventHubConnectionConfig, \"entityPath\" | \"host\">,\n): TracingSpanOptions {\n const spanLinks: TracingSpanLink[] = [];\n for (const receivedEvent of receivedEvents) {\n const tracingContext = extractSpanContextFromEventData(receivedEvent);\n if (tracingContext) {\n spanLinks.push({\n tracingContext,\n attributes: {\n enqueuedTime: receivedEvent.enqueuedTimeUtc.getTime(),\n },\n });\n }\n }\n return {\n spanLinks,\n spanKind: \"consumer\",\n ...toSpanOptions(eventHubProperties, \"process\"),\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { logErrorStackTrace, logger } from \"./logger\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { CloseReason } from \"./models/public\";\nimport { CommonEventProcessorOptions } from \"./models/private\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { EventPosition } from \"./eventPosition\";\nimport { PartitionProcessor } from \"./partitionProcessor\";\nimport { PartitionPump } from \"./partitionPump\";\n\n/**\n * The PumpManager handles the creation and removal of PartitionPumps.\n * It also starts a PartitionPump when it is created, and stops a\n * PartitionPump when it is removed.\n * @internal\n */\nexport interface PumpManager {\n /**\n * Creates and starts a PartitionPump.\n * @param startPosition - The position in the partition to start reading from.\n * @param eventHubClient - The EventHubClient to forward to the PartitionPump.\n * @param partitionProcessor - The PartitionProcessor to forward to the PartitionPump.\n * @param abortSignal - Used to cancel pump creation.\n */\n createPump(\n startPosition: EventPosition,\n connectionContext: ConnectionContext,\n partitionProcessor: PartitionProcessor,\n abortSignal: AbortSignalLike,\n ): Promise<void>;\n\n /**\n * Indicates whether the pump manager is actively receiving events from a given partition.\n * @param partitionId - The partition to check.\n */\n isReceivingFromPartition(partitionId: string): boolean;\n\n /**\n * Stops all PartitionPumps and removes them from the internal map.\n * @param reason - The reason for removing the pump.\n */\n removeAllPumps(reason: CloseReason): Promise<void>;\n}\n\n/**\n * The PumpManager handles the creation and removal of PartitionPumps.\n * It also starts a PartitionPump when it is created, and stops a\n * PartitionPump when it is removed.\n * @internal\n */\nexport class PumpManagerImpl implements PumpManager {\n private readonly _eventProcessorName: string;\n private readonly _options: CommonEventProcessorOptions;\n private _partitionIdToPumps: {\n [partitionId: string]: PartitionPump | undefined;\n } = {};\n\n constructor(eventProcessorName: string, eventProcessorOptions: CommonEventProcessorOptions) {\n this._eventProcessorName = eventProcessorName;\n this._options = eventProcessorOptions;\n }\n\n /**\n * Returns a list of partitionIds that are actively receiving messages.\n */\n public receivingFromPartitions(): string[] {\n return Object.keys(this._partitionIdToPumps).filter((id) => {\n const pump = this._partitionIdToPumps[id];\n return Boolean(pump && pump.isReceiving);\n });\n }\n\n /**\n * Indicates whether the pump manager is actively receiving events from a given partition.\n * @internal\n */\n public isReceivingFromPartition(partitionId: string): boolean {\n const pump = this._partitionIdToPumps[partitionId];\n return Boolean(pump && pump.isReceiving);\n }\n\n /**\n * Creates and starts a PartitionPump.\n * @param startPosition - The position in the partition to start reading from.\n * @param connectionContext - The ConnectionContext to forward to the PartitionPump.\n * @param partitionProcessor - The PartitionProcessor to forward to the PartitionPump.\n */\n public async createPump(\n startPosition: EventPosition,\n connectionContext: ConnectionContext,\n partitionProcessor: PartitionProcessor,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n const partitionId = partitionProcessor.partitionId;\n if (abortSignal.aborted) {\n logger.verbose(\n `${this._eventProcessorName}] The subscription was closed before creating the pump for partition ${partitionId}.`,\n );\n return;\n }\n // attempt to get an existing pump\n const existingPump = this._partitionIdToPumps[partitionId];\n if (existingPump) {\n if (existingPump.isReceiving) {\n logger.verbose(\n `[${this._eventProcessorName}] [${partitionId}] The existing pump is running.`,\n );\n return;\n }\n logger.verbose(\n `[${this._eventProcessorName}] [${partitionId}] The existing pump is not running.`,\n );\n await this.removePump(partitionId, CloseReason.OwnershipLost);\n }\n\n logger.verbose(`[${this._eventProcessorName}] [${partitionId}] Creating a new pump.`);\n\n const pump = new PartitionPump(\n connectionContext,\n partitionProcessor,\n startPosition,\n this._options,\n );\n\n try {\n // Set the pump before starting it in case the user\n // closes the subscription while `start()` is in progress.\n this._partitionIdToPumps[partitionId] = pump;\n await pump.start();\n } catch (err: any) {\n logger.verbose(\n `[${this._eventProcessorName}] [${partitionId}] An error occured while adding/updating a pump: ${err}`,\n );\n logErrorStackTrace(err);\n }\n }\n\n /**\n * Stop a PartitionPump and removes it from the internal map.\n * @param partitionId - The partitionId to remove the associated PartitionPump from.\n * @param reason - The reason for removing the pump.\n */\n public async removePump(partitionId: string, reason: CloseReason): Promise<void> {\n try {\n const pump = this._partitionIdToPumps[partitionId];\n if (pump) {\n delete this._partitionIdToPumps[partitionId];\n logger.verbose(`[${this._eventProcessorName}] [${partitionId}] Stopping the pump.`);\n await pump.stop(reason);\n } else {\n logger.verbose(\n `[${this._eventProcessorName}] [${partitionId}] No pump was found to remove.`,\n );\n }\n } catch (err: any) {\n logger.verbose(\n `[${this._eventProcessorName}] [${partitionId}] An error occured while removing a pump: ${err}`,\n );\n logErrorStackTrace(err);\n }\n }\n\n /**\n * Stops all PartitionPumps and removes them from the internal map.\n * @param reason - The reason for removing the pump.\n */\n public async removeAllPumps(reason: CloseReason): Promise<void> {\n const partitionIds = Object.keys(this._partitionIdToPumps);\n\n logger.verbose(`[${this._eventProcessorName}] Removing all pumps due to reason ${reason}.`);\n\n const tasks: PromiseLike<void>[] = [];\n for (const partitionId of partitionIds) {\n const pump = this._partitionIdToPumps[partitionId];\n if (pump) {\n tasks.push(pump.stop(reason));\n }\n }\n\n try {\n await Promise.all(tasks);\n } catch (err: any) {\n logger.verbose(\n `[${this._eventProcessorName}] An error occured while removing all pumps: ${err}`,\n );\n logErrorStackTrace(err);\n } finally {\n this._partitionIdToPumps = {};\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { delay } from \"@azure/core-amqp\";\n\n/**\n * @param delayInMs - The number of milliseconds to be delayed.\n * @param abortSignal - The abortSignal associated with the containing operation.\n * @internal\n */\nexport async function delayWithoutThrow(\n delayInMs: number,\n abortSignal?: AbortSignalLike,\n): Promise<void> {\n try {\n await delay(delayInMs, abortSignal);\n } catch {\n /* no-op to swallow AbortError */\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortController, AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport { Checkpoint, PartitionProcessor } from \"./partitionProcessor\";\nimport { EventPosition, isEventPosition, latestEventPosition } from \"./eventPosition\";\nimport { PumpManager, PumpManagerImpl } from \"./pumpManager\";\nimport { logErrorStackTrace, logger } from \"./logger\";\nimport { CloseReason } from \"./models/public\";\nimport { CommonEventProcessorOptions } from \"./models/private\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { LoadBalancingStrategy } from \"./loadBalancerStrategies/loadBalancingStrategy\";\nimport { OperationOptions } from \"./util/operationOptions\";\nimport { SubscriptionEventHandlers } from \"./eventHubConsumerClientModels\";\nimport { delayWithoutThrow } from \"./util/delayWithoutThrow\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * An interface representing the details on which instance of a `EventProcessor` owns processing\n * of a given partition from a consumer group of an Event Hub instance.\n *\n * **Note**: This is used internally by the `EventProcessor` and user never has to create it directly.\n */\nexport interface PartitionOwnership {\n /**\n * The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n */\n fullyQualifiedNamespace: string;\n /**\n * The event hub name\n */\n eventHubName: string;\n /**\n * The consumer group name\n */\n consumerGroup: string;\n /**\n * The identifier of the Event Hub partition.\n */\n partitionId: string;\n /**\n * The unique identifier of the event processor.\n */\n ownerId: string;\n /**\n * The last modified time.\n */\n lastModifiedTimeInMs?: number;\n /**\n * The unique identifier for the operation.\n */\n etag?: string;\n}\n\n/**\n * A checkpoint store stores and retrieves partition ownership information and checkpoint details\n * for each partition in a given consumer group of an event hub instance.\n *\n * Users are not meant to implement an `CheckpointStore`.\n * Users are expected to choose existing implementations of this interface, instantiate it, and pass\n * it to the `EventHubConsumerClient` class constructor when instantiating a client.\n * Users are not expected to use any of the methods on a checkpoint store, these are used internally by\n * the client.\n *\n * Implementations of `CheckpointStore` can be found on npm by searching for packages with the prefix &commat;azure/eventhub-checkpointstore-.\n */\nexport interface CheckpointStore {\n /**\n * Called to get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partition ownership details of all the partitions that have/had an owner.\n */\n listOwnership(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n /**\n * Called to claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of partitions this instance successfully claimed ownership.\n */\n claimOwnership(\n partitionOwnership: PartitionOwnership[],\n options?: OperationOptions,\n ): Promise<PartitionOwnership[]>;\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n */\n updateCheckpoint(checkpoint: Checkpoint, options?: OperationOptions): Promise<void>;\n\n /**\n * Lists all the checkpoints in a data store for a given namespace, eventhub and consumer group.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @param options - A set of options that can be specified to influence the behavior of this method.\n * - `abortSignal`: A signal used to request operation cancellation.\n * - `tracingOptions`: Options for configuring tracing.\n * @returns A list of checkpoints for a given namespace, eventhub, and consumer group.\n */\n listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n options?: OperationOptions,\n ): Promise<Checkpoint[]>;\n}\n\n/**\n * A set of options to pass to the constructor of `EventProcessor`.\n * You can specify\n * - `maxBatchSize`: The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds`: The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n *\n * Example usage with default values:\n * ```ts\n * {\n * maxBatchSize: 1,\n * maxWaitTimeInSeconds: 60,\n * }\n * ```\n * @internal\n */\nexport interface FullEventProcessorOptions extends CommonEventProcessorOptions {\n /**\n * An optional pump manager to use, rather than instantiating one internally\n * @internal\n */\n pumpManager?: PumpManager;\n /**\n * The amount of time between load balancing attempts.\n */\n loopIntervalInMs: number;\n /**\n * A specific partition to target.\n */\n processingTarget?: string;\n}\n\n/**\n * Event Processor based applications consist of one or more instances of EventProcessor which have been\n * configured to consume events from the same Event Hub and consumer group. They balance the\n * workload across different instances by distributing the partitions to be processed among themselves.\n * They also allow the user to track progress when events are processed using checkpoints.\n *\n * A checkpoint is meant to represent the last successfully processed event by the user from a particular\n * partition of a consumer group in an Event Hub instance.\n *\n * @internal\n */\nexport class EventProcessor {\n private _processorOptions: FullEventProcessorOptions;\n private _pumpManager: PumpManager;\n private _id: string;\n private _isRunning: boolean = false;\n private _loopTask?: PromiseLike<void>;\n private _abortController?: AbortController;\n /**\n * A specific partition to target.\n */\n private _processingTarget?: string;\n /**\n * Determines which partitions to claim as part of load balancing.\n */\n private _loadBalancingStrategy: LoadBalancingStrategy;\n /**\n * The amount of time between load balancing attempts.\n */\n private _loopIntervalInMs: number;\n private _eventHubName: string;\n private _fullyQualifiedNamespace: string;\n\n /**\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param eventHubClient - An instance of `EventHubClient` that was created for the Event Hub instance.\n * @param PartitionProcessorClass - A user-provided class that extends the `PartitionProcessor` class.\n * This class will be responsible for processing and checkpointing events.\n * @param checkpointStore - An instance of `CheckpointStore`. See &commat;azure/eventhubs-checkpointstore-blob for an implementation.\n * For production, choose an implementation that will store checkpoints and partition ownership details to a durable store.\n * @param options - A set of options to configure the Event Processor\n * - `maxBatchSize` : The max size of the batch of events passed each time to user code for processing.\n * - `maxWaitTimeInSeconds` : The maximum amount of time to wait to build up the requested message count before\n * passing the data to user code for processing. If not provided, it defaults to 60 seconds.\n */\n constructor(\n private _consumerGroup: string,\n private _context: ConnectionContext,\n private _subscriptionEventHandlers: SubscriptionEventHandlers,\n private _checkpointStore: CheckpointStore,\n options: FullEventProcessorOptions,\n ) {\n if (options.ownerId) {\n this._id = options.ownerId;\n logger.verbose(`Starting event processor with ID ${this._id}`);\n } else {\n this._id = getRandomName();\n logger.verbose(`Starting event processor with autogenerated ID ${this._id}`);\n }\n\n this._eventHubName = this._context.config.entityPath;\n this._fullyQualifiedNamespace = this._context.config.host;\n this._processorOptions = options;\n this._pumpManager =\n options.pumpManager || new PumpManagerImpl(this._id, this._processorOptions);\n this._processingTarget = options.processingTarget;\n this._loopIntervalInMs = options.loopIntervalInMs;\n this._loadBalancingStrategy = options.loadBalancingStrategy;\n }\n\n /**\n * The unique identifier for the EventProcessor.\n */\n get id(): string {\n return this._id;\n }\n\n private _createPartitionOwnershipRequest(\n partitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIdToClaim: string,\n ): PartitionOwnership {\n const previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);\n const partitionOwnership: PartitionOwnership = {\n ownerId: this._id,\n partitionId: partitionIdToClaim,\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n consumerGroup: this._consumerGroup,\n eventHubName: this._eventHubName,\n etag: previousPartitionOwnership ? previousPartitionOwnership.etag : undefined,\n };\n\n return partitionOwnership;\n }\n\n /*\n * Claim ownership of the given partition if it's available\n */\n private async _claimOwnership(\n ownershipRequest: PartitionOwnership,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] Subscription was closed before claiming ownership of ${ownershipRequest.partitionId}.`,\n );\n return;\n }\n logger.info(\n `[${this._id}] Attempting to claim ownership of partition ${ownershipRequest.partitionId}.`,\n );\n try {\n const claimedOwnerships = await this._checkpointStore.claimOwnership([ownershipRequest]);\n\n // can happen if the partition was claimed out from underneath us - we shouldn't\n // attempt to spin up a processor.\n if (!claimedOwnerships.length) {\n return;\n }\n\n logger.info(\n `[${this._id}] Successfully claimed ownership of partition ${ownershipRequest.partitionId}.`,\n );\n\n await this._startPump(ownershipRequest.partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] Failed to claim ownership of partition ${ownershipRequest.partitionId}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n }\n }\n\n private async _startPump(partitionId: string, abortSignal: AbortSignalLike): Promise<void> {\n if (abortSignal.aborted) {\n logger.verbose(\n `[${this._id}] The subscription was closed before starting to read from ${partitionId}.`,\n );\n return;\n }\n\n if (this._pumpManager.isReceivingFromPartition(partitionId)) {\n logger.verbose(\n `[${this._id}] There is already an active partitionPump for partition \"${partitionId}\", skipping pump creation.`,\n );\n return;\n }\n\n logger.verbose(\n `[${this._id}] [${partitionId}] Calling user-provided PartitionProcessorFactory.`,\n );\n\n const partitionProcessor = new PartitionProcessor(\n this._subscriptionEventHandlers,\n this._checkpointStore,\n {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: partitionId,\n eventProcessorId: this._id,\n },\n );\n\n const eventPosition = await this._getStartingPosition(partitionId);\n await this._pumpManager.createPump(\n eventPosition,\n this._context,\n partitionProcessor,\n abortSignal,\n );\n\n logger.verbose(`[${this._id}] PartitionPump created successfully.`);\n }\n\n private async _getStartingPosition(partitionIdToClaim: string): Promise<EventPosition> {\n const availableCheckpoints = await this._checkpointStore.listCheckpoints(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n const validCheckpoints = availableCheckpoints.filter(\n (chk) => chk.partitionId === partitionIdToClaim,\n );\n\n if (validCheckpoints.length > 0) {\n return { offset: validCheckpoints[0].offset };\n }\n\n logger.verbose(\n `No checkpoint found for partition ${partitionIdToClaim}. Looking for fallback.`,\n );\n return getStartPosition(partitionIdToClaim, this._processorOptions.startPosition);\n }\n\n private async _runLoopForSinglePartition(\n partitionId: string,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n while (!abortSignal.aborted) {\n try {\n await this._startPump(partitionId, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occured within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n await this._handleSubscriptionError(err);\n } finally {\n // sleep for some time after which we can attempt to create a pump again.\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${this._loopIntervalInMs} ms.`,\n );\n // swallow errors from delay since it's fine for delay to exit early\n await delayWithoutThrow(this._loopIntervalInMs, abortSignal);\n }\n }\n this._isRunning = false;\n }\n\n /**\n * Every loop to this method will result in this EventProcessor owning at most one new partition.\n *\n * The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active\n * EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,\n * this algorithm converges gradually towards a steady state.\n *\n * When a new partition is claimed, this method is also responsible for starting a partition pump that creates an\n * EventHubConsumer for processing events from that partition.\n */\n private async _runLoopWithLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n let cancelLoopResolver;\n // This provides a mechanism for exiting the loop early\n // if the subscription has had `close` called.\n const cancelLoopPromise = new Promise<void>((resolve) => {\n cancelLoopResolver = resolve;\n if (abortSignal.aborted) {\n resolve();\n return;\n }\n\n abortSignal.addEventListener(\"abort\", resolve);\n });\n\n // Periodically check if any partitions need to be claimed and claim them.\n while (!abortSignal.aborted) {\n const iterationStartTimeInMs = Date.now();\n try {\n const { partitionIds } = await this._context.managementSession!.getEventHubProperties({\n abortSignal: abortSignal,\n });\n await this._performLoadBalancing(loadBalancingStrategy, partitionIds, abortSignal);\n } catch (err: any) {\n logger.warning(\n `[${this._id}] An error occurred within the EventProcessor loop: ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n // Protect against the scenario where the user awaits on subscription.close() from inside processError.\n await Promise.race([this._handleSubscriptionError(err), cancelLoopPromise]);\n } finally {\n // Sleep for some time, then continue the loop.\n const iterationDeltaInMs = Date.now() - iterationStartTimeInMs;\n const delayDurationInMs = Math.max(this._loopIntervalInMs - iterationDeltaInMs, 0);\n logger.verbose(\n `[${this._id}] Pausing the EventProcessor loop for ${delayDurationInMs} ms.`,\n );\n // Swallow the error since it's fine to exit early from the delay.\n await delayWithoutThrow(delayDurationInMs, abortSignal);\n }\n }\n\n if (cancelLoopResolver) {\n abortSignal.removeEventListener(\"abort\", cancelLoopResolver);\n }\n this._isRunning = false;\n }\n\n private async _performLoadBalancing(\n loadBalancingStrategy: LoadBalancingStrategy,\n partitionIds: string[],\n abortSignal: AbortSignalLike,\n ): Promise<void> {\n if (abortSignal.aborted) throw new AbortError(\"The operation was aborted.\");\n\n // Retrieve current partition ownership details from the datastore.\n const partitionOwnership = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n\n if (abortSignal.aborted) throw new AbortError(\"The operation was aborted.\");\n\n const { partitionOwnershipMap, partitionsToClaim } = computePartitionsToClaim({\n id: this._id,\n isReceivingFromPartition: (partitionId: string) =>\n this._pumpManager.isReceivingFromPartition(partitionId),\n loadBalancingStrategy,\n partitionIds,\n partitionOwnership,\n });\n\n for (const partitionToClaim of partitionsToClaim) {\n const partitionOwnershipRequest = this._createPartitionOwnershipRequest(\n partitionOwnershipMap,\n partitionToClaim,\n );\n\n await this._claimOwnership(partitionOwnershipRequest, abortSignal);\n }\n }\n\n /**\n * This is called when there are errors that are not specific to a partition (ex: load balancing)\n */\n private async _handleSubscriptionError(err: Error): Promise<void> {\n // filter out any internal \"expected\" errors\n if (err.name === \"AbortError\") {\n return;\n }\n\n if (this._subscriptionEventHandlers.processError) {\n try {\n await this._subscriptionEventHandlers.processError(err, {\n fullyQualifiedNamespace: this._fullyQualifiedNamespace,\n eventHubName: this._eventHubName,\n consumerGroup: this._consumerGroup,\n partitionId: \"\",\n updateCheckpoint: async () => {\n /* no-op */\n },\n });\n } catch (errorFromUser: any) {\n logger.verbose(\n `[${this._id}] An error was thrown from the user's processError handler: ${errorFromUser}`,\n );\n }\n }\n }\n\n /**\n * Starts the `EventProcessor`. Based on the number of instances of `EventProcessor` that are running for the\n * same consumer group, the partitions are distributed among these instances to process events.\n *\n * For each partition, the user provided `PartitionProcessor` is instantiated.\n *\n * Subsequent calls to start will be ignored if this event processor is already running.\n * Calling `start()` after `stop()` is called will restart this event processor.\n *\n */\n start(): void {\n if (this._isRunning) {\n logger.verbose(`[${this._id}] Attempted to start an already running EventProcessor.`);\n return;\n }\n\n this._isRunning = true;\n this._abortController = new AbortController();\n logger.verbose(`[${this._id}] Starting an EventProcessor.`);\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] Single partition target: ${this._processingTarget}`);\n this._loopTask = this._runLoopForSinglePartition(\n this._processingTarget,\n this._abortController.signal,\n );\n } else {\n logger.verbose(`[${this._id}] Multiple partitions, using load balancer`);\n this._loopTask = this._runLoopWithLoadBalancing(\n this._loadBalancingStrategy,\n this._abortController.signal,\n );\n }\n }\n\n isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Stops processing events for all partitions owned by this event processor.\n * All `PartitionProcessor` will be shutdown and any open resources will be closed.\n *\n * Subsequent calls to stop will be ignored if the event processor is not running.\n *\n */\n async stop(): Promise<void> {\n logger.verbose(`[${this._id}] Stopping an EventProcessor.`);\n if (this._abortController) {\n // cancel the event processor loop\n this._abortController.abort();\n }\n\n try {\n // remove all existing pumps\n await this._pumpManager.removeAllPumps(CloseReason.Shutdown);\n\n // waits for the event processor loop to complete\n // will complete immediately if _loopTask is undefined\n if (this._loopTask) {\n await this._loopTask;\n }\n } catch (err: any) {\n logger.verbose(`[${this._id}] An error occured while stopping the EventProcessor: ${err}`);\n } finally {\n logger.verbose(`[${this._id}] EventProcessor stopped.`);\n }\n\n if (this._processingTarget) {\n logger.verbose(`[${this._id}] No partitions owned, skipping abandoning.`);\n } else {\n await this.abandonPartitionOwnerships();\n }\n }\n\n private async abandonPartitionOwnerships(): Promise<PartitionOwnership[]> {\n logger.verbose(`[${this._id}] Abandoning owned partitions`);\n const allOwnerships = await this._checkpointStore.listOwnership(\n this._fullyQualifiedNamespace,\n this._eventHubName,\n this._consumerGroup,\n );\n const ourOwnerships = allOwnerships.filter((ownership) => ownership.ownerId === this._id);\n // unclaim any partitions that we currently own\n for (const ownership of ourOwnerships) {\n ownership.ownerId = \"\";\n }\n return this._checkpointStore.claimOwnership(ourOwnerships);\n }\n}\n\nfunction isAbandoned(ownership: PartitionOwnership): boolean {\n return ownership.ownerId === \"\";\n}\n\nfunction getStartPosition(\n partitionIdToClaim: string,\n startPositions?: EventPosition | { [partitionId: string]: EventPosition },\n): EventPosition {\n if (startPositions == null) {\n return latestEventPosition;\n }\n\n if (isEventPosition(startPositions)) {\n return startPositions;\n }\n\n const startPosition = (startPositions as { [partitionId: string]: EventPosition })[\n partitionIdToClaim\n ];\n\n if (startPosition == null) {\n return latestEventPosition;\n }\n\n return startPosition;\n}\n\nfunction computePartitionsToClaim(inputs: {\n partitionOwnership: PartitionOwnership[];\n id: string;\n isReceivingFromPartition: (id: string) => boolean;\n loadBalancingStrategy: LoadBalancingStrategy;\n partitionIds: string[];\n}): {\n partitionsToClaim: Set<string>;\n partitionOwnershipMap: Map<string, PartitionOwnership>;\n} {\n const { partitionOwnership, id, isReceivingFromPartition, loadBalancingStrategy, partitionIds } =\n inputs;\n\n const partitionOwnershipMap = new Map<string, PartitionOwnership>();\n const nonAbandonedPartitionOwnershipMap = new Map<string, PartitionOwnership>();\n const partitionsToRenew: string[] = [];\n\n // Separate abandoned ownerships from claimed ownerships.\n // We only want to pass active partition ownerships to the\n // load balancer, but we need to hold onto the abandoned\n // partition ownerships because we need the etag to claim them.\n for (const ownership of partitionOwnership) {\n partitionOwnershipMap.set(ownership.partitionId, ownership);\n if (!isAbandoned(ownership)) {\n nonAbandonedPartitionOwnershipMap.set(ownership.partitionId, ownership);\n }\n if (ownership.ownerId === id && isReceivingFromPartition(ownership.partitionId)) {\n partitionsToRenew.push(ownership.partitionId);\n }\n }\n\n // Pass the list of all the partition ids and the collection of claimed partition ownerships\n // to the load balance strategy.\n // The load balancing strategy only needs to know the full list of partitions,\n // and which of those are currently claimed.\n // Since abandoned partitions are no longer claimed, we exclude them.\n const partitionsToClaim = loadBalancingStrategy.getPartitionsToClaim(\n id,\n nonAbandonedPartitionOwnershipMap,\n partitionIds,\n );\n partitionsToClaim.push(...partitionsToRenew);\n\n return {\n partitionsToClaim: new Set(partitionsToClaim),\n partitionOwnershipMap,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { parseConnectionString } from \"@azure/core-amqp\";\n\n/**\n * The set of properties that comprise an Event Hub connection string.\n */\nexport interface EventHubConnectionStringProperties {\n /**\n * The fully qualified Event Hub namespace extracted from the \"Endpoint\" in the\n * connection string. This is likely to be similar to `{yournamespace}.servicebus.windows.net`.\n * This is typically used to construct an EventHubProducerClient or an EventHubConsumerClient.\n */\n fullyQualifiedNamespace: string;\n /**\n * The value for \"Endpoint\" in the connection string.\n */\n endpoint: string;\n /**\n * The value for \"EntityPath\" in the connection string which would be the name of the event hub instance associated with the connection string.\n * Connection string from a Shared Access Policy created at the namespace level\n * will not have the EntityPath in it.\n */\n eventHubName?: string;\n /**\n * The value for \"SharedAccessKey\" in the connection string. This along with the \"SharedAccessKeyName\"\n * in the connection string is used to generate a SharedAccessSignature which can be used authorize\n * the connection to the service.\n */\n sharedAccessKey?: string;\n /**\n * The value for \"SharedAccessKeyName\" in the connection string. This along with the \"SharedAccessKey\"\n * in the connection string is used to generate a SharedAccessSignature which can be used authorize\n * the connection to the service.\n */\n sharedAccessKeyName?: string;\n /**\n * The value for \"SharedAccessSignature\" in the connection string. This is typically not present in the\n * connection string generated for a Shared Access Policy. It is instead generated by the\n * user and appended to the connection string for ease of use.\n */\n sharedAccessSignature?: string;\n /**\n * This should be true only if the connection string contains the slug \";UseDevelopmentEmulator=true\"\n * and the endpoint is a loopback address.\n */\n useDevelopmentEmulator?: boolean;\n}\n\n/**\n * Parses given connection string into the different properties applicable to Azure Event Hubs.\n * The properties are useful to then construct an EventHubProducerClient or an EventHubConsumerClient.\n * @param connectionString - The connection string associated with the Shared Access Policy created\n * for the Event Hubs namespace.\n */\nexport function parseEventHubConnectionString(\n connectionString: string,\n): Readonly<EventHubConnectionStringProperties> {\n const parsedResult = parseConnectionString<{\n Endpoint: string;\n EntityPath?: string;\n SharedAccessSignature?: string;\n SharedAccessKey?: string;\n SharedAccessKeyName?: string;\n UseDevelopmentEmulator?: string;\n }>(connectionString);\n\n validateProperties(\n parsedResult.Endpoint,\n parsedResult.SharedAccessSignature,\n parsedResult.SharedAccessKey,\n parsedResult.SharedAccessKeyName,\n );\n\n const output: EventHubConnectionStringProperties = {\n fullyQualifiedNamespace: (parsedResult.Endpoint.match(\".*://([^/]*)\") || [])[1],\n endpoint: parsedResult.Endpoint,\n };\n\n if (parsedResult.EntityPath) {\n output.eventHubName = parsedResult.EntityPath;\n }\n\n if (parsedResult.SharedAccessSignature) {\n output.sharedAccessSignature = parsedResult.SharedAccessSignature;\n }\n\n if (parsedResult.SharedAccessKey && parsedResult.SharedAccessKeyName) {\n output.sharedAccessKey = parsedResult.SharedAccessKey;\n output.sharedAccessKeyName = parsedResult.SharedAccessKeyName;\n }\n\n return output;\n}\n\n/**\n * @internal\n */\nfunction validateProperties(\n endpoint?: string,\n sharedAccessSignature?: string,\n sharedAccessKey?: string,\n sharedAccessKeyName?: string,\n): void {\n if (!endpoint) {\n throw new Error(\"Connection string should have an Endpoint key.\");\n }\n\n if (sharedAccessSignature) {\n if (sharedAccessKey || sharedAccessKeyName) {\n throw new Error(\n \"Connection string cannot have both SharedAccessSignature and SharedAccessKey keys.\",\n );\n }\n } else if (sharedAccessKey && !sharedAccessKeyName) {\n throw new Error(\"Connection string with SharedAccessKey should have SharedAccessKeyName.\");\n } else if (!sharedAccessKey && sharedAccessKeyName) {\n throw new Error(\n \"Connection string with SharedAccessKeyName should have SharedAccessKey as well.\",\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { logErrorStackTrace, logger } from \"../logger\";\nimport { ConnectionContext } from \"../connectionContext\";\nimport { isDefined } from \"@azure/core-util\";\nimport { AmqpError, isAmqpError } from \"rhea-promise\";\nimport { isMessagingError, MessagingError, translate } from \"@azure/core-amqp\";\n\n/**\n * @internal\n * Logs and throws Error if the current AMQP connection is closed.\n * @param context - The ConnectionContext associated with the current AMQP connection.\n */\nexport function throwErrorIfConnectionClosed(context: ConnectionContext): void {\n if (context && context.wasConnectionCloseCalled) {\n const errorMessage = \"The underlying AMQP connection is closed.\";\n const error = new Error(errorMessage);\n logger.warning(`[${context.connectionId}] ${error.name}: ${error.message}`);\n logErrorStackTrace(error);\n throw error;\n }\n}\n\n/**\n * @internal\n * Logs and Throws TypeError if given parameter is undefined or null\n * @param connectionId - Id of the underlying AMQP connection used for logging\n * @param methodName - Name of the method that was passed the parameter\n * @param parameterName - Name of the parameter to check\n * @param parameterValue - Value of the parameter to check\n */\nexport function throwTypeErrorIfParameterMissing(\n connectionId: string,\n methodName: string,\n parameterName: string,\n parameterValue: unknown,\n): void {\n if (!isDefined(parameterValue)) {\n const error = new TypeError(\n `${methodName} called without required argument \"${parameterName}\"`,\n );\n logger.warning(`[${connectionId}] ${error.name}: ${error.message}`);\n logErrorStackTrace(error);\n throw error;\n }\n}\n\n/**\n * Maps the amqp error conditions to the Error names.\n * @internal\n */\nenum ConditionErrorNameMapper {\n /**\n * Indicates that a sequenc enumber was out of order.\n */\n \"com.microsoft:out-of-order-sequence\" = \"SequenceOutOfOrderError\",\n /**\n * Error is thrown when two or more instances connect to the same partition\n * with different epoch values.\n */\n \"com.microsoft:producer-epoch-stolen\" = \"ProducerDisconnectedError\",\n}\n\n/**\n * @internal\n */\nconst nonRetryableErrors: Set<string> = new Set([\n \"ProducerDisconnectedError\",\n \"SequenceOutOfOrderError\",\n]);\n\n/**\n * @internal\n */\nexport function translateError(err: AmqpError | Error): MessagingError | Error {\n const translatedError = translate(err);\n // If we're not dealing with a messaging error, or the original error wasn't an AMQP error,\n // or we have a resolved code on the messaging error, just return the translated error.\n if (!isMessagingError(translatedError) || !isAmqpError(err) || translatedError.code) {\n return translatedError;\n }\n\n const amqpError = err as AmqpError;\n const condition = amqpError.condition;\n\n // If we don't have a condition, we can't map the condition to a code.\n if (!condition) {\n return translatedError;\n }\n\n // Attempt to resolve codes core-amqp doesn't know about.\n translatedError.code =\n ConditionErrorNameMapper[condition as keyof typeof ConditionErrorNameMapper];\n if (translatedError.code) {\n translatedError.retryable = !nonRetryableErrors.has(translatedError.code);\n }\n\n return translatedError;\n}\n\n/**\n * @internal\n */\nexport const idempotentAlreadyPublished =\n \"These events have already been successfully published. When idempotent publishing is enabled, events that were acknowledged by the Event Hubs service may not be published again.\";\n\n/**\n * @internal\n */\nexport const idempotentSomeAlreadyPublished =\n \"1 or more of these events have already been successfully published. When idempotent publishing is enabled, events that were acknowledged by the Event Hubs service may not be published again.\";\n\n/**\n * @internal\n */\nexport function validateProducerPartitionSettings({\n enableIdempotentRetries,\n partitionId,\n partitionKey,\n}: {\n enableIdempotentRetries?: boolean;\n partitionId?: string;\n partitionKey?: string;\n}): void {\n if (enableIdempotentRetries && (isDefined(partitionKey) || !isDefined(partitionId))) {\n throw new Error(\n `The \"partitionId\" must be supplied and \"partitionKey\" must not be provided when the EventHubProducerClient has \"enableIdempotentRetries\" set to true.`,\n );\n }\n\n if (isDefined(partitionId) && isDefined(partitionKey)) {\n throw new Error(\n `The partitionId (${partitionId}) and partitionKey (${partitionKey}) cannot both be specified.`,\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Constants,\n RequestResponseLink,\n RetryConfig,\n RetryOperationType,\n RetryOptions,\n SendRequestOptions,\n defaultCancellableLock,\n isSasTokenProvider,\n retry,\n translate,\n} from \"@azure/core-amqp\";\nimport {\n EventContext,\n Message,\n ReceiverEvents,\n ReceiverOptions,\n SenderEvents,\n SenderOptions,\n} from \"rhea-promise\";\nimport {\n logErrorStackTrace,\n createSimpleLogger,\n logger,\n SimpleLogger,\n createManagementLogPrefix,\n} from \"./logger\";\nimport { throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing } from \"./util/error\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AccessToken } from \"@azure/core-auth\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { OperationOptions } from \"./util/operationOptions\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries\";\nimport { TimerLoop } from \"./util/timerLoop\";\nimport { withAuth } from \"./withAuth\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * Describes the runtime information of an Event Hub.\n */\nexport interface EventHubProperties {\n /**\n * The name of the event hub.\n */\n name: string;\n /**\n * The date and time the hub was created in UTC.\n */\n createdOn: Date;\n /**\n * The slice of string partition identifiers.\n */\n partitionIds: string[];\n /**\n * Whether the hub has geographical disaster recovery enabled.\n */\n isGeoDrEnabled: boolean;\n}\n\n/**\n * Describes the runtime information of an EventHub Partition.\n */\nexport interface PartitionProperties {\n /**\n * The name of the Event Hub.\n */\n eventHubName: string;\n /**\n * Identifier of the partition within the Event Hub.\n */\n partitionId: string;\n /**\n * The starting sequence number of the partition's message log.\n */\n beginningSequenceNumber: number;\n /**\n * The last sequence number of the partition's message log.\n */\n lastEnqueuedSequenceNumber: number;\n /**\n * The offset of the last enqueued message in the partition's message log.\n */\n lastEnqueuedOffset: string;\n /**\n * The time of the last enqueued message in the partition's message log in UTC.\n */\n lastEnqueuedOnUtc: Date;\n /**\n * Indicates whether the partition is empty.\n */\n isEmpty: boolean;\n}\n\n/**\n * @internal\n */\nexport interface ManagementClientOptions {\n address?: string;\n audience?: string;\n}\n\n/**\n * @internal\n * Describes the EventHubs Management Client that talks\n * to the $management endpoint over AMQP connection.\n */\nexport class ManagementClient {\n readonly managementLock: string = getRandomName(Constants.managementRequestKey);\n /**\n * The name/path of the entity (hub name) for which the management\n * request needs to be made.\n */\n private readonly entityPath: string;\n /**\n * The reply to Guid for the management client.\n */\n private readonly replyTo: string = getRandomName();\n /**\n * $management sender, receiver on the same session.\n */\n private _mgmtReqResLink?: RequestResponseLink;\n /**\n * The address in the following form:\n * `\"$management\"`.\n */\n private readonly address: string;\n /**\n * The token audience in the following form:\n * `\"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management\"`.\n */\n private readonly audience: string;\n /**\n * Provides relevant information about the amqp connection,\n * cbs and $management sessions, token provider, sender and receivers.\n */\n private readonly _context: ConnectionContext;\n /**\n * The authentication loop that keeps the token refreshed.\n */\n private authLoop?: TimerLoop;\n private readonly logger: SimpleLogger;\n\n /**\n * Instantiates the management client.\n * @param context - The connection context.\n * @param address - The address for the management endpoint. For IotHub it will be\n * `/messages/events/$management`.\n */\n constructor(context: ConnectionContext, { address, audience }: ManagementClientOptions = {}) {\n this.address = address ?? Constants.management;\n this.audience = audience ?? context.config.getManagementAudience();\n this._context = context;\n const logPrefix = createManagementLogPrefix(this._context.connectionId);\n this.logger = createSimpleLogger(logger, logPrefix);\n this.entityPath = context.config.entityPath as string;\n }\n\n /**\n * Gets the security token for the management application properties.\n * @internal\n */\n async getSecurityToken(): Promise<AccessToken | null> {\n if (isSasTokenProvider(this._context.tokenCredential)) {\n // the security_token has the $management address removed from the end of the audience\n // expected audience: sb://fully.qualified.namespace/event-hub-name/$management\n const audienceParts = this.audience.split(\"/\");\n // for management links, address should be '$management'\n if (audienceParts[audienceParts.length - 1] === this.address) {\n audienceParts.pop();\n }\n const audience = audienceParts.join(\"/\");\n return this._context.tokenCredential.getToken(audience);\n }\n\n // aad credentials use the aad scope\n return this._context.tokenCredential.getToken(Constants.aadEventHubsScope);\n }\n\n /**\n * Provides the eventhub runtime information.\n */\n async getEventHubProperties(\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<EventHubProperties> {\n throwErrorIfConnectionClosed(this._context);\n return tracingClient.withSpan(\n \"ManagementClient.getEventHubProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.eventHub}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getHubRuntimeInformation\",\n });\n const runtimeInfo: EventHubProperties = {\n name: info.name,\n createdOn: new Date(info.created_at),\n partitionIds: info.partition_ids,\n isGeoDrEnabled: info.georeplication_factor > 1,\n };\n logger.verbose(\"the hub runtime info is: %O\", runtimeInfo);\n\n return runtimeInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the hub runtime information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Provides information about the specified partition.\n * @param partitionId - Partition ID for which partition information is required.\n */\n async getPartitionProperties(\n partitionId: string,\n options: OperationOptions & { retryOptions?: RetryOptions } = {},\n ): Promise<PartitionProperties> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(\n this._context.connectionId,\n \"getPartitionProperties\",\n \"partitionId\",\n partitionId,\n );\n partitionId = String(partitionId);\n\n return tracingClient.withSpan(\n \"ManagementClient.getPartitionProperties\",\n options,\n async (updatedOptions) => {\n try {\n const securityToken = await this.getSecurityToken();\n const request: Message = {\n body: Buffer.from(JSON.stringify([])),\n message_id: getRandomName(),\n reply_to: this.replyTo,\n application_properties: {\n operation: Constants.readOperation,\n name: this.entityPath as string,\n type: `${Constants.vendorString}:${Constants.partition}`,\n partition: `${partitionId}`,\n security_token: securityToken?.token,\n },\n };\n\n const info: any = await this._makeManagementRequest(request, {\n ...updatedOptions,\n requestName: \"getPartitionInformation\",\n });\n\n const partitionInfo: PartitionProperties = {\n beginningSequenceNumber: info.begin_sequence_number,\n eventHubName: info.name,\n lastEnqueuedOffset: info.last_enqueued_offset,\n lastEnqueuedOnUtc: new Date(info.last_enqueued_time_utc),\n lastEnqueuedSequenceNumber: info.last_enqueued_sequence_number,\n partitionId: info.partition,\n isEmpty: info.is_partition_empty,\n };\n logger.verbose(\"the partition info is: %O.\", partitionInfo);\n return partitionInfo;\n } catch (error: any) {\n logger.warning(\n `an error occurred while getting the partition information: ${error?.name}: ${error?.message}`,\n );\n logErrorStackTrace(error);\n throw error;\n }\n },\n toSpanOptions(this._context.config),\n );\n }\n\n /**\n * Closes the AMQP management session to the Event Hub for this client,\n * returning a promise that will be resolved when disconnection is completed.\n */\n async close(): Promise<void> {\n try {\n // Always stop the auth loop when closing the management link.\n this.authLoop?.stop();\n if (this._isMgmtRequestResponseLinkOpen()) {\n const mgmtLink = this._mgmtReqResLink;\n this._mgmtReqResLink = undefined;\n await mgmtLink!.close();\n logger.info(\"successfully closed the management session.\");\n }\n } catch (err: any) {\n const msg = `an error occurred while closing the management session: ${err?.name}: ${err?.message}`;\n logger.warning(msg);\n logErrorStackTrace(err);\n throw new Error(msg);\n }\n }\n\n private async _init({\n abortSignal,\n timeoutInMs,\n }: {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n }): Promise<void> {\n const createLink = async () => {\n const rxopt: ReceiverOptions = {\n source: { address: this.address },\n name: this.replyTo,\n target: { address: this.replyTo },\n onSessionError: (context: EventContext) => {\n const ehError = translate(context.session!.error!);\n logger.verbose(\n \"an error occurred on the session for request/response links for \" + \"$management: %O\",\n ehError,\n );\n },\n };\n const sropt: SenderOptions = {\n target: { address: this.address },\n };\n logger.verbose(\n \"creating sender/receiver links with \" + \"srOpts: %o, receiverOpts: %O.\",\n sropt,\n rxopt,\n );\n this._mgmtReqResLink = await RequestResponseLink.create(\n this._context.connection,\n sropt,\n rxopt,\n { abortSignal },\n );\n this._mgmtReqResLink.sender.on(SenderEvents.senderError, (context: EventContext) => {\n const ehError = translate(context.sender!.error!);\n logger.verbose(\"an error occurred on the $management sender link.. %O\", ehError);\n });\n this._mgmtReqResLink.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => {\n const ehError = translate(context.receiver!.error!);\n logger.verbose(\"an error occurred on the $management receiver link.. %O\", ehError);\n });\n logger.verbose(\n \"created sender '%s' and receiver '%s' links\",\n this._mgmtReqResLink.sender.name,\n this._mgmtReqResLink.receiver.name,\n );\n };\n try {\n if (!this._isMgmtRequestResponseLinkOpen()) {\n // Wait for the connectionContext to be ready to open the link.\n await this._context.readyToOpenLink();\n this.authLoop = await withAuth(\n createLink,\n this._context,\n this.audience,\n timeoutInMs,\n this.logger,\n { abortSignal },\n );\n }\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n `an error occurred while establishing the links: ${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Helper method to make the management request\n * @param request - The AMQP message to send\n * @param options - The options to use when sending a request over a $management link\n */\n private async _makeManagementRequest(\n request: Message,\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n requestName?: string;\n } = {},\n ): Promise<any> {\n const retryOptions = options.retryOptions || {};\n try {\n const abortSignal: AbortSignalLike | undefined = options && options.abortSignal;\n\n const sendOperationPromise = async (): Promise<Message> => {\n let count = 0;\n\n const retryTimeoutInMs = getRetryAttemptTimeoutInMs(options.retryOptions);\n let timeTakenByInit = 0;\n\n if (!this._isMgmtRequestResponseLinkOpen()) {\n logger.verbose(\"acquiring lock to get the management req res link.\");\n\n const initOperationStartTime = Date.now();\n try {\n await defaultCancellableLock.acquire(\n this.managementLock,\n () => {\n const acquireLockEndTime = Date.now();\n const timeoutInMs =\n retryTimeoutInMs - (acquireLockEndTime - initOperationStartTime);\n return this._init({ abortSignal, timeoutInMs });\n },\n { abortSignal, timeoutInMs: retryTimeoutInMs },\n );\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred while creating the link: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n timeTakenByInit = Date.now() - initOperationStartTime;\n }\n\n const remainingOperationTimeoutInMs = retryTimeoutInMs - timeTakenByInit;\n\n const sendRequestOptions: SendRequestOptions = {\n abortSignal: options.abortSignal,\n requestName: options.requestName,\n timeoutInMs: remainingOperationTimeoutInMs,\n };\n\n count++;\n if (count !== 1) {\n // Generate a new message_id every time after the first attempt\n request.message_id = getRandomName();\n } else if (!request.message_id) {\n // Set the message_id in the first attempt only if it is not set\n request.message_id = getRandomName();\n }\n\n return this._mgmtReqResLink!.sendRequest(request, sendRequestOptions);\n };\n\n const config: RetryConfig<Message> = Object.defineProperties(\n {\n operation: sendOperationPromise,\n operationType: RetryOperationType.management,\n abortSignal: abortSignal,\n retryOptions: retryOptions,\n },\n {\n connectionId: {\n enumerable: true,\n get: () => {\n return this._context.connectionId;\n },\n },\n },\n ) as RetryConfig<Message>;\n return (await retry<Message>(config)).body;\n } catch (err) {\n const translatedError = translate(err);\n logger.warning(\n \"an error occurred during send on management request-response link with address: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n private _isMgmtRequestResponseLinkOpen(): boolean {\n return this._mgmtReqResLink! && this._mgmtReqResLink!.isOpen();\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Parses the host, hostname, and port from an endpoint.\n * @param endpoint - And endpoint to parse.\n * @internal\n */\nexport function parseEndpoint(endpoint: string): { host: string; hostname: string; port?: string } {\n const hostMatch = endpoint.match(/.*:\\/\\/([^/]*)/);\n if (!hostMatch) {\n throw new TypeError(`Invalid endpoint missing host: ${endpoint}`);\n }\n\n const [, host] = hostMatch;\n const [hostname, port] = host.split(\":\");\n\n return { host, hostname, port };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/* eslint-disable eqeqeq */\n\nimport { ConnectionConfig } from \"@azure/core-amqp\";\nimport { parseEndpoint } from \"./util/parseEndpoint\";\n\n/**\n * Describes the connection config object that is created after parsing an EventHub connection\n * string. It also provides some convenience methods for getting the address and audience for\n * different entities.\n * @internal\n */\nexport interface EventHubConnectionConfig extends ConnectionConfig {\n /**\n * The name/path of the entity (event hub name) to which the\n * connection needs to happen.\n */\n entityPath: string;\n /**\n * Provides the EventHub Sender address in one of the following forms based on the input:\n * - `\"<hubName>\"`\n * - `\"<hubName>/Partitions/<partitionId>\"`\n *\n * @param partitionId - The partitionId in the EventHub to which messages will be sent.\n */\n getSenderAddress(partitionId?: string | number): string;\n /**\n * Provides the EventHub Sender audience in one of the following forms based on the input:\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>\"`\n *\n * @param partitionId - The partitionId in the EventHub to which messages will be sent.\n */\n getSenderAudience(partitionId?: string | number): string;\n /**\n * Provides the EventHub Receiver address:\n * - `\"<hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>\"`\n *\n * @param partitionId - The partitionId in the EventHub from which messages will be received.\n * @param consumergroup - The consumergroup in the EventHub from which the messages will\n * be received. Default: `$default`.\n */\n getReceiverAddress(partitionId: string | number, consumergroup?: string): string;\n /**\n * Provides the EventHub Receiver audience.\n * - `\"sb://<your-namespace>.servicebus.windows.net/<hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>\"`\n *\n * @param partitionId - The partitionId in the EventHub from which messages will be received.\n * @param consumergroup - The consumergroup in the EventHub from which the messages will\n * be received. Default: `$default`.\n */\n getReceiverAudience(partitionId: string | number, consumergroup?: string): string;\n /**\n * Provides the EventHub Management address.\n * - `\"<hub-name>/$management\"`\n */\n getManagementAddress(): string;\n /**\n * Provides the EventHub Management audience.\n * - `\"sb://<your-namespace>.servicebus.windows.net/<hub-name>/$management\"`\n */\n getManagementAudience(): string;\n}\n\n/**\n * Describes the connection config object that is created after parsing an EventHub connection\n * string. It also provides some convenience methods for getting the address and audience for\n * different entities.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const EventHubConnectionConfig = {\n /**\n * Creates the connection config.\n * @param connectionString - The connection string for a given service like\n * EventHub/ServiceBus.\n * @param path - The name/path of the entity (hub name) to which the\n * connection needs to happen. This will override the EntityPath in the connectionString\n * if present.\n * @returns EventHubConnectionConfig\n */\n create(connectionString: string, path?: string): EventHubConnectionConfig {\n const config = ConnectionConfig.create(connectionString, path);\n if (!config.entityPath) {\n throw new TypeError(\n `Either provide \"path\" or the \"connectionString\": \"${connectionString}\", ` +\n `must contain EntityPath=\"<path-to-the-entity>\".`,\n );\n }\n return EventHubConnectionConfig.createFromConnectionConfig(config);\n },\n\n /**\n * Creates an EventHubConnectionConfig from the provided base ConnectionConfig.\n * @param config - The base connection config from which the EventHubConnectionConfig needs to be\n * created.\n * @returns EventHubConnectionConfig\n */\n createFromConnectionConfig(config: ConnectionConfig): EventHubConnectionConfig {\n ConnectionConfig.validate(config, { isEntityPathRequired: true });\n\n (config as EventHubConnectionConfig).getManagementAudience = () => {\n return `${config.endpoint}${config.entityPath}/$management`;\n };\n (config as EventHubConnectionConfig).getManagementAddress = () => {\n return `${config.entityPath}/$management`;\n };\n\n (config as EventHubConnectionConfig).getSenderAudience = (partitionId?: string | number) => {\n if (partitionId != undefined) {\n return `${config.endpoint}${config.entityPath}/Partitions/${partitionId}`;\n } else {\n return `${config.endpoint}${config.entityPath}`;\n }\n };\n\n (config as EventHubConnectionConfig).getSenderAddress = (partitionId?: string | number) => {\n if (partitionId != undefined) {\n return `${config.entityPath}/Partitions/${partitionId}`;\n } else {\n return `${config.entityPath}`;\n }\n };\n\n (config as EventHubConnectionConfig).getReceiverAudience = (\n partitionId: string | number,\n consumergroup?: string,\n ) => {\n if (!consumergroup) consumergroup = \"$default\";\n return (\n `${config.endpoint}${config.entityPath}/ConsumerGroups/${consumergroup}/` +\n `Partitions/${partitionId}`\n );\n };\n\n (config as EventHubConnectionConfig).getReceiverAddress = (\n partitionId: string | number,\n consumergroup?: string,\n ) => {\n if (!consumergroup) consumergroup = \"$default\";\n return `${config.entityPath}/ConsumerGroups/${consumergroup}/Partitions/${partitionId}`;\n };\n return config as EventHubConnectionConfig;\n },\n\n /**\n * Updates the provided EventHubConnectionConfig to use the custom endpoint address.\n * @param config - An existing connection configuration to be updated.\n * @param customEndpointAddress - The custom endpoint address to use.\n */\n setCustomEndpointAddress(config: EventHubConnectionConfig, customEndpointAddress: string): void {\n // The amqpHostname should match the host prior to using the custom endpoint.\n config.amqpHostname = config.host;\n const { hostname, port } = parseEndpoint(customEndpointAddress);\n // Since we specify the port separately, set host to the customEndpointAddress hostname.\n config.host = hostname;\n if (port) {\n config.port = parseInt(port, 10);\n }\n },\n\n /**\n * Validates the properties of connection config.\n * @param config - The connection config to be validated.\n * @returns void\n */\n validate(config: EventHubConnectionConfig): void {\n return ConnectionConfig.validate(config, { isEntityPathRequired: true });\n },\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as os from \"os\";\n\n/**\n * Returns information about the platform this function is being run on.\n * @internal\n */\nexport function getRuntimeInfo(): string {\n return `NODE-VERSION ${process.version}; ${os.type()} ${os.release()}`;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n NamedKeyCredential,\n SASCredential,\n TokenCredential,\n isNamedKeyCredential,\n isSASCredential,\n isTokenCredential,\n} from \"@azure/core-auth\";\n\n/**\n * Typeguard that checks if the input is a credential type the clients accept.\n * @param thing - Any object.\n * @internal\n */\nexport function isCredential(\n thing: unknown,\n): thing is TokenCredential | NamedKeyCredential | SASCredential {\n return isTokenCredential(thing) || isNamedKeyCredential(thing) || isSASCredential(thing);\n}\n","// 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 { Connection, ConnectionEvents, Dictionary, EventContext, OnAmqpEvent } from \"rhea-promise\";\nimport {\n ConnectionConfig,\n ConnectionContextBase,\n Constants,\n CreateConnectionContextBaseParameters,\n SasTokenProvider,\n createSasTokenProvider,\n} from \"@azure/core-amqp\";\nimport {\n EventHubConnectionStringProperties,\n parseEventHubConnectionString,\n} from \"./util/connectionStringUtils\";\nimport { ManagementClient, ManagementClientOptions } from \"./managementClient\";\nimport {\n NamedKeyCredential,\n SASCredential,\n TokenCredential,\n isNamedKeyCredential,\n isSASCredential,\n} from \"@azure/core-auth\";\nimport { logErrorStackTrace, logger } from \"./logger\";\nimport { EventHubClientOptions } from \"./models/public\";\nimport { EventHubConnectionConfig } from \"./eventhubConnectionConfig\";\nimport { PartitionReceiver } from \"./partitionReceiver\";\nimport { EventHubSender } from \"./eventHubSender\";\nimport { getRuntimeInfo } from \"./util/runtimeInfo\";\nimport { isCredential } from \"./util/typeGuards\";\nimport { packageJsonInfo } from \"./util/constants\";\nimport { 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/ban-types\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 const onDisconnected: OnAmqpEvent = async (context: EventContext) => {\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 && 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 protocolError: OnAmqpEvent = async (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 = async (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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { PartitionOwnership } from \"../eventProcessor\";\nimport { logger } from \"../logger\";\n\n/**\n * Determines which partitions to claim as part of load balancing.\n * @internal\n */\nexport interface LoadBalancingStrategy {\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n getPartitionsToClaim(\n ownerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[];\n}\n\n/**\n * Counts of the EventProcessors that currently own partitions.\n * @internal\n */\ninterface EventProcessorCounts {\n /**\n * The # of EventProcessors that only own the required # of\n * partitions.\n */\n haveRequiredPartitions: number;\n /**\n * The # of EventProcessors that currently own the required #\n * of partitions + 1 additional (ie, handling the case where\n * the number of partitions is not evenly divisible by the # of\n * EventProcessors).\n */\n haveAdditionalPartition: number;\n /**\n * EventProcessors which have more than the required or even required + 1\n * number of partitions. These will eventually be downsized by other\n * EventProcessors as they acquire their required number of partitions.\n */\n haveTooManyPartitions: number;\n}\n\n/**\n * This method will create a new map of partition id and PartitionOwnership containing only those partitions\n * that are actively owned.\n * All entries in the original map that haven't been modified for a duration of time greater than the allowed\n * inactivity time limit are assumed to be owned by dead event processors.\n * These will not be included in the map returned by this method.\n *\n * @param partitionOwnershipMap - The existing PartitionOwnerships mapped by partition.\n * @param expirationIntervalInMs - The length of time a PartitionOwnership claim is valid.\n */\nfunction getActivePartitionOwnerships(\n partitionOwnershipMap: Map<string, PartitionOwnership>,\n expirationIntervalInMs: number,\n): Map<string, PartitionOwnership> {\n const activePartitionOwnershipMap: Map<string, PartitionOwnership> = new Map();\n partitionOwnershipMap.forEach((partitionOwnership: PartitionOwnership, partitionId: string) => {\n // If lastModifiedtimeInMs is missing, assume it is inactive.\n if (\n typeof partitionOwnership.lastModifiedTimeInMs === \"undefined\" ||\n partitionOwnership.lastModifiedTimeInMs === null\n ) {\n return;\n }\n\n const timeSincePartitionClaimed = Date.now() - partitionOwnership.lastModifiedTimeInMs;\n if (timeSincePartitionClaimed < expirationIntervalInMs && partitionOwnership.ownerId) {\n activePartitionOwnershipMap.set(partitionId, partitionOwnership);\n }\n });\n\n return activePartitionOwnershipMap;\n}\n\n/**\n * Calculates the minimum number of partitions each EventProcessor should own,\n * and the number of EventProcessors that should have an extra partition assigned.\n * @param ownerToOwnershipMap - The current ownerships for partitions.\n * @param partitionIds - The full list of the Event Hub's partition ids.\n * @internal\n */\nfunction calculateBalancedLoadCounts(\n ownerToOwnershipMap: Map<string, PartitionOwnership[]>,\n partitionIds: string[],\n): { minPartitionsPerOwner: number; requiredNumberOfOwnersWithExtraPartition: number } {\n // Calculate the minimum number of partitions every EventProcessor should own when the load\n // is evenly distributed.\n const minPartitionsPerOwner = Math.floor(partitionIds.length / ownerToOwnershipMap.size);\n\n // If the number of partitions in the Event Hub is not evenly divisible by the number of active\n // EventProcesrrors, some EventProcessors may own 1 partition in addition to the minimum when the\n // load is balanced.\n // Calculate the number of EventProcessors that can own an additional partition.\n const requiredNumberOfOwnersWithExtraPartition = partitionIds.length % ownerToOwnershipMap.size;\n\n return {\n minPartitionsPerOwner,\n requiredNumberOfOwnersWithExtraPartition,\n };\n}\n\n/**\n * Counts the EventProcessors and tallies them by type.\n *\n * To be in balance we need to make sure that each EventProcessor is only consuming\n * their fair share.\n *\n * When the partitions are divvied up we will sometimes end up with some EventProcessors\n * that will have 1 more partition than others.\n * This can happen if the number of partitions is not evenly divisible by the number of EventProcessors.\n *\n * So this function largely exists to support isLoadBalanced() and\n * shouldOwnMorePartitions(), both of which depend on knowing if our current list\n * of EventProcessors is actually in the proper state.\n *\n * @param minPartitionsPerOwner - The number of required partitions per EventProcessor.\n * @param ownerToOwnershipMap - The current ownerships for partitions.\n * @internal\n */\nfunction getEventProcessorCounts(\n minPartitionsPerOwner: number,\n ownerToOwnershipMap: Map<string, PartitionOwnership[]>,\n): EventProcessorCounts {\n const counts: EventProcessorCounts = {\n haveRequiredPartitions: 0,\n haveAdditionalPartition: 0,\n haveTooManyPartitions: 0,\n };\n\n for (const ownershipList of ownerToOwnershipMap.values()) {\n const numberOfPartitions = ownershipList.length;\n\n // there are basically three kinds of partition counts\n // for a processor:\n\n if (numberOfPartitions === minPartitionsPerOwner) {\n // 1. Has _exactly_ the required number of partitions\n counts.haveRequiredPartitions++;\n } else if (numberOfPartitions === minPartitionsPerOwner + 1) {\n // 2. Has the required number plus one extra (correct in cases)\n // where the # of partitions is not evenly divisible by the\n // number of processors.\n counts.haveAdditionalPartition++;\n } else if (numberOfPartitions > minPartitionsPerOwner + 1) {\n // 3. has more than the possible # of partitions required\n counts.haveTooManyPartitions++;\n }\n }\n\n return counts;\n}\n\n/**\n * Validates that we are currently in a balanced state - all EventProcessors own the\n * minimum required number of partitions (and additional partitions, if the # of partitions\n * is not evenly divisible by the # of EventProcessors).\n *\n * @param requiredNumberOfOwnersWithExtraPartition - The # of EventProcessors that process an additional partition, in addition to the required minimum.\n * @param totalExpectedProcessors - The total # of EventProcessors we expect.\n * @param eventProcessorCounts - EventProcessor counts, grouped by criteria.\n * @internal\n */\nfunction isLoadBalanced(\n requiredNumberOfOwnersWithExtraPartition: number,\n totalExpectedEventProcessors: number,\n { haveAdditionalPartition, haveRequiredPartitions }: EventProcessorCounts,\n): boolean {\n return (\n haveAdditionalPartition === requiredNumberOfOwnersWithExtraPartition &&\n haveRequiredPartitions + haveAdditionalPartition === totalExpectedEventProcessors\n );\n}\n\n/**\n * Determines the number of new partitions to claim for this particular processor.\n *\n * @param minRequired - The minimum required number of partitions.\n * @param requiredNumberOfOwnersWithExtraPartition - The current number of processors that should have an additional partition.\n * @param numPartitionsOwnedByUs - The number of partitions we currently own.\n * @param eventProcessorCounts - Processors, grouped by criteria.\n * @internal\n */\nfunction getNumberOfPartitionsToClaim(\n minRequiredPartitionCount: number,\n requiredNumberOfOwnersWithExtraPartition: number,\n numPartitionsOwnedByUs: number,\n { haveAdditionalPartition, haveTooManyPartitions }: EventProcessorCounts,\n): number {\n let actualRequiredPartitionCount = minRequiredPartitionCount;\n\n if (\n requiredNumberOfOwnersWithExtraPartition > 0 &&\n // Eventually the `haveTooManyPartitions` will decay into `haveAdditionalPartition`\n // EventProcessors as partitions are balanced to consumers that aren't at par.\n // We can consider them to be `haveAdditionalPartition` EventProcessors for our purposes.\n haveAdditionalPartition + haveTooManyPartitions < requiredNumberOfOwnersWithExtraPartition\n ) {\n // Overall we don't have enough EventProcessors that are taking on an additional partition\n // so we should attempt to.\n actualRequiredPartitionCount = minRequiredPartitionCount + 1;\n }\n return actualRequiredPartitionCount - numPartitionsOwnedByUs;\n}\n\n/**\n * Determines which partitions can be stolen from other owners while maintaining\n * a balanced state.\n * @param numberOfPartitionsToClaim - The number of partitions the owner needs to claim to reach a balanced state.\n * @param minPartitionsPerOwner - The minimum number of partitions each owner needs for the partition load to be balanced.\n * @param requiredNumberOfOwnersWithExtraPartition - The number of owners that should have 1 extra partition.\n * @param ourOwnerId - The id of _our_ owner.\n * @param ownerToOwnershipMap - The current ownerships for partitions.\n * @internal\n */\nfunction findPartitionsToSteal(\n numberOfPartitionsToClaim: number,\n minPartitionsPerOwner: number,\n requiredNumberOfOwnersWithExtraPartition: number,\n ourOwnerId: string,\n ownerToOwnershipMap: Map<string, PartitionOwnership[]>,\n): string[] {\n const partitionsToSteal: string[] = [];\n // Create a list of PartitionOwnership lists that we can steal from.\n const listOfPartitionOwnerships: Array<PartitionOwnership[]> = [];\n ownerToOwnershipMap.forEach((partitionOwnerships, ownerId) => {\n if (ownerId === ourOwnerId || partitionOwnerships.length <= minPartitionsPerOwner) return;\n listOfPartitionOwnerships.push(partitionOwnerships);\n });\n\n // Sort the list in descending order based on the length of each element.\n listOfPartitionOwnerships.sort((a, b) => {\n if (a.length > b.length) return -1;\n if (a.length < b.length) return 1;\n return 0;\n });\n\n // Attempt to steal partitions from EventProcessors that have the most partitions 1st,\n // then work our way down.\n let ownersEncounteredWithExtraPartitions = 0;\n let currentPartitionOwnershipList = listOfPartitionOwnerships.shift();\n while (numberOfPartitionsToClaim > 0 && currentPartitionOwnershipList) {\n let ownersExpectedPartitionCount = minPartitionsPerOwner;\n // Determine if the current owner should be allowed to have an extra partition.\n if (ownersEncounteredWithExtraPartitions < requiredNumberOfOwnersWithExtraPartition) {\n ownersExpectedPartitionCount++;\n }\n ownersEncounteredWithExtraPartitions++;\n\n let numberAvailableToSteal =\n currentPartitionOwnershipList.length - ownersExpectedPartitionCount;\n // Claim as many random partitions as possible.\n while (Math.min(numberOfPartitionsToClaim, numberAvailableToSteal)) {\n const indexToClaim = Math.floor(Math.random() * currentPartitionOwnershipList.length);\n partitionsToSteal.push(currentPartitionOwnershipList.splice(indexToClaim, 1)[0].partitionId);\n numberOfPartitionsToClaim--;\n numberAvailableToSteal--;\n }\n\n // Move on to the next list of PartitionOwnership.\n currentPartitionOwnershipList = listOfPartitionOwnerships.shift();\n }\n\n return partitionsToSteal;\n}\n\n/**\n * Identifies all of the partitions that can be claimed by the specified owner for\n * that owner to reach a balanced state.\n * @param OwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @param expirationIntervalInMs - The length of time a partition claim is valid.\n * @returns Partition ids that may be claimed.\n * @internal\n */\nexport function listAvailablePartitions(\n ownerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n expirationIntervalInMs: number,\n): string[] {\n if (!partitionIds.length) {\n return [];\n }\n\n // Collect only the PartitionOwnership that have been updated within the expiration interval.\n // Any PartitionOwnership that has been updated outside the expiration interval can be claimed.\n const activePartitionOwnershipMap = getActivePartitionOwnerships(\n claimedPartitionOwnershipMap,\n expirationIntervalInMs,\n );\n logger.verbose(\n `[${ownerId}] Number of active ownership records: ${activePartitionOwnershipMap.size}.`,\n );\n\n if (activePartitionOwnershipMap.size === 0) {\n // All partitions in this Event Hub are available to claim.\n return partitionIds;\n }\n\n // Map ownerIds to the partitions they own so that we can determine how many each owner has.\n const ownerToOwnershipMap = new Map<string, PartitionOwnership[]>();\n for (const activeOwnership of activePartitionOwnershipMap.values()) {\n const partitionOwnershipList = ownerToOwnershipMap.get(activeOwnership.ownerId) || [];\n\n partitionOwnershipList.push(activeOwnership);\n ownerToOwnershipMap.set(activeOwnership.ownerId, partitionOwnershipList);\n }\n\n // Add the current EventProcessor to the map of owners to ownerships if it doesn't exist.\n if (!ownerToOwnershipMap.has(ownerId)) {\n ownerToOwnershipMap.set(ownerId, []);\n }\n\n logger.info(`[${ownerId}] Number of active event processors: ${ownerToOwnershipMap.size}.`);\n\n const { minPartitionsPerOwner, requiredNumberOfOwnersWithExtraPartition } =\n calculateBalancedLoadCounts(ownerToOwnershipMap, partitionIds);\n\n logger.verbose(\n `[${ownerId}] Expected minimum number of partitions per event processor: ${minPartitionsPerOwner},` +\n `expected number of event processors with additional partition: ${requiredNumberOfOwnersWithExtraPartition}.`,\n );\n\n // Get some stats representing the current state the world with regards to how balanced the\n // partitions are across EventProcessors.\n const eventProcessorCounts = getEventProcessorCounts(minPartitionsPerOwner, ownerToOwnershipMap);\n\n if (\n isLoadBalanced(\n requiredNumberOfOwnersWithExtraPartition,\n ownerToOwnershipMap.size,\n eventProcessorCounts,\n )\n ) {\n // When the partitions are evenly distributed, no change required.\n return [];\n }\n\n let numberOfPartitionsToClaim = getNumberOfPartitionsToClaim(\n minPartitionsPerOwner,\n requiredNumberOfOwnersWithExtraPartition,\n ownerToOwnershipMap.get(ownerId)!.length,\n eventProcessorCounts,\n );\n\n if (numberOfPartitionsToClaim <= 0) {\n return [];\n }\n\n const partitionsToClaim: string[] = [];\n const unclaimedPartitionIds = partitionIds.filter((id) => !activePartitionOwnershipMap.has(id));\n\n // Prioritize getting unclaimed partitions first.\n while (Math.min(numberOfPartitionsToClaim, unclaimedPartitionIds.length)) {\n const indexToClaim = Math.floor(Math.random() * unclaimedPartitionIds.length);\n partitionsToClaim.push(unclaimedPartitionIds.splice(indexToClaim, 1)[0]);\n numberOfPartitionsToClaim--;\n }\n\n if (numberOfPartitionsToClaim === 0) {\n return partitionsToClaim;\n }\n\n // Find partitions that can be stolen from other EventProcessors.\n const partitionsToSteal = findPartitionsToSteal(\n numberOfPartitionsToClaim,\n minPartitionsPerOwner,\n requiredNumberOfOwnersWithExtraPartition,\n ownerId,\n ownerToOwnershipMap,\n );\n\n return partitionsToClaim.concat(partitionsToSteal);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LoadBalancingStrategy, listAvailablePartitions } from \"./loadBalancingStrategy\";\nimport { PartitionOwnership } from \"../eventProcessor\";\n\n/**\n * The BalancedLoadBalancerStrategy is meant to be used when the user\n * wants to reach a load balanced state with less partition 'thrashing'.\n *\n * Partition thrashing - where a partition changes owners - is minimized\n * by only returning a single partition to claim at a time.\n * This minimizes the number of times a partition should need to be stolen.\n * @internal\n */\nexport class BalancedLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of BalancedLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n const claimablePartitions = listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n\n if (!claimablePartitions.length) {\n return [];\n }\n\n const randomIndex = Math.floor(Math.random() * claimablePartitions.length);\n return [claimablePartitions[randomIndex]];\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LoadBalancingStrategy, listAvailablePartitions } from \"./loadBalancingStrategy\";\nimport { PartitionOwnership } from \"../eventProcessor\";\n\n/**\n * @internal\n */\nexport class GreedyLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Creates an instance of GreedyLoadBalancingStrategy.\n *\n * @param _partitionOwnershipExpirationIntervalInMs - The length of time a partition claim is valid.\n */\n constructor(private readonly _partitionOwnershipExpirationIntervalInMs: number) {}\n\n /**\n * Implements load balancing by taking into account current ownership and\n * the new set of partitions to add.\n * @param ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n ourOwnerId: string,\n claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n return listAvailablePartitions(\n ourOwnerId,\n claimedPartitionOwnershipMap,\n partitionIds,\n this._partitionOwnershipExpirationIntervalInMs,\n );\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CheckpointStore, PartitionOwnership } from \"./eventProcessor\";\nimport { Checkpoint } from \"./partitionProcessor\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * The `EventProcessor` relies on a `CheckpointStore` to store checkpoints and handle partition\n * ownerships. `InMemoryCheckpointStore` is simple partition manager that stores checkpoints and\n * partition ownerships in memory of your program.\n *\n * You can use the `InMemoryCheckpointStore` to get started with using the `EventProcessor`.\n * But in production, you should choose an implementation of the `CheckpointStore` interface that will\n * store the checkpoints and partition ownerships to a durable store instead.\n *\n * @internal\n */\nexport class InMemoryCheckpointStore implements CheckpointStore {\n private _partitionOwnershipMap: Map<string, PartitionOwnership> = new Map();\n private _committedCheckpoints: Map<string, Map<string, Checkpoint>> = new Map();\n\n /**\n * Get the list of all existing partition ownership from the underlying data store. Could return empty\n * results if there are is no existing ownership information.\n *\n * @param fullyQualifiedNamespace - The fully qualified Event Hubs namespace. This is likely to be similar to\n * <yournamespace>.servicebus.windows.net.\n * @param eventHubName - The event hub name.\n * @param consumerGroup - The consumer group name.\n * @returns Partition ownership details of all the partitions that have/had an owner..\n */\n async listOwnership(\n _fullyQualifiedNamespace: string,\n _eventHubName: string,\n _consumerGroup: string,\n ): Promise<PartitionOwnership[]> {\n const ownerships = [];\n\n for (const value of this._partitionOwnershipMap.values()) {\n ownerships.push({ ...value });\n }\n\n return ownerships;\n }\n\n /**\n * Claim ownership of a list of partitions. This will return the list of partitions that were owned\n * successfully.\n *\n * @param partitionOwnership - The list of partition ownership this instance is claiming to own.\n * @returns A list partitions this instance successfully claimed ownership.\n */\n async claimOwnership(partitionOwnership: PartitionOwnership[]): Promise<PartitionOwnership[]> {\n const claimedOwnerships = [];\n\n for (const ownership of partitionOwnership) {\n if (\n !this._partitionOwnershipMap.has(ownership.partitionId) ||\n this._partitionOwnershipMap.get(ownership.partitionId)!.etag === ownership.etag\n ) {\n const date = new Date();\n\n const newOwnership = {\n ...ownership,\n etag: getRandomName(),\n lastModifiedTimeInMs: date.getTime(),\n };\n\n this._partitionOwnershipMap.set(newOwnership.partitionId, newOwnership);\n claimedOwnerships.push(newOwnership);\n }\n }\n return claimedOwnerships;\n }\n\n /**\n * Updates the checkpoint in the data store for a partition.\n *\n * @param checkpoint - The checkpoint.\n */\n async updateCheckpoint(checkpoint: Checkpoint): Promise<void> {\n throwTypeErrorIfParameterMissing(\n \"\",\n \"updateCheckpoint\",\n \"sequenceNumber\",\n checkpoint.sequenceNumber,\n );\n throwTypeErrorIfParameterMissing(\"\", \"updateCheckpoint\", \"offset\", checkpoint.offset);\n\n checkpoint = { ...checkpoint };\n\n const partitionOwnership = this._partitionOwnershipMap.get(checkpoint.partitionId);\n if (partitionOwnership) {\n partitionOwnership.etag = getRandomName();\n\n const key = `${checkpoint.fullyQualifiedNamespace}:${checkpoint.eventHubName}:${checkpoint.consumerGroup}`;\n let partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n partitionMap = new Map();\n this._committedCheckpoints.set(key, partitionMap);\n }\n\n partitionMap.set(checkpoint.partitionId, checkpoint);\n }\n }\n\n async listCheckpoints(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n consumerGroup: string,\n ): Promise<Checkpoint[]> {\n const key = `${fullyQualifiedNamespace}:${eventHubName}:${consumerGroup}`;\n\n const partitionMap = this._committedCheckpoints.get(key);\n\n if (partitionMap == null) {\n return [];\n }\n\n const checkpoints = [];\n\n for (const value of partitionMap.values()) {\n checkpoints.push({ ...value });\n }\n\n return checkpoints;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Used by EventHubConsumerClient to prevent accidentally spinning up multiple\n * subscriptions against the same set of partitions.\n *\n * This is needed now that EventHubConsumerClient only uses a single CheckpointStore\n * instance - otherwise users will see unpredictable results as their event processor\n * continually steals/overwrites checkpointing and ownership with itself.\n *\n * @internal\n */\nexport class PartitionGate {\n private _partitions = new Set<string>();\n\n /**\n * Adds a partition, throwing an Error if there is a conflict with partitions (including \"all\")\n * that are already added.\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n add(partitionId: string | \"all\"): void {\n if (\n (partitionId === \"all\" && this._partitions.size > 0) ||\n this._partitions.has(partitionId) ||\n this._partitions.has(\"all\")\n ) {\n throw new Error(`Partition already has a subscriber.`);\n }\n\n this._partitions.add(partitionId);\n }\n\n /**\n * Removes a partition\n *\n * @param partitionId - A partition ID or the constant \"all\"\n */\n remove(partitionId: string | \"all\"): void {\n this._partitions.delete(partitionId);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { LoadBalancingStrategy } from \"./loadBalancingStrategy\";\nimport { PartitionOwnership } from \"../eventProcessor\";\n\n/**\n * The UnbalancedLoadBalancingStrategy does no actual load balancing.\n * It is intended to be used when you want to avoid load balancing\n * and consume a set of partitions.\n * @internal\n */\nexport class UnbalancedLoadBalancingStrategy implements LoadBalancingStrategy {\n /**\n * Implements load balancing by taking into account current ownership and\n * the full set of partitions in the Event Hub.\n * @param _ourOwnerId - The id we should assume is _our_ id when checking for ownership.\n * @param _claimedPartitionOwnershipMap - The current claimed ownerships for partitions.\n * @param partitionIds - Partitions to assign owners to.\n * @returns Partition ids to claim.\n */\n public getPartitionsToClaim(\n _ourOwnerId: string,\n _claimedPartitionOwnershipMap: Map<string, PartitionOwnership>,\n partitionIds: string[],\n ): string[] {\n return partitionIds;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CheckpointStore, EventProcessor, FullEventProcessorOptions } from \"./eventProcessor\";\nimport { ConnectionContext, createConnectionContext } from \"./connectionContext\";\nimport {\n EventHubConsumerClientOptions,\n GetEventHubPropertiesOptions,\n GetPartitionIdsOptions,\n GetPartitionPropertiesOptions,\n LoadBalancingOptions,\n} from \"./models/public\";\nimport { EventHubProperties, PartitionProperties } from \"./managementClient\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport {\n SubscribeOptions,\n Subscription,\n SubscriptionEventHandlers,\n} from \"./eventHubConsumerClientModels\";\nimport { BalancedLoadBalancingStrategy } from \"./loadBalancerStrategies/balancedStrategy\";\nimport { Constants } from \"@azure/core-amqp\";\nimport { GreedyLoadBalancingStrategy } from \"./loadBalancerStrategies/greedyStrategy\";\nimport { InMemoryCheckpointStore } from \"./inMemoryCheckpointStore\";\nimport { LoadBalancingStrategy } from \"./loadBalancerStrategies/loadBalancingStrategy\";\nimport { PartitionGate } from \"./impl/partitionGate\";\nimport { UnbalancedLoadBalancingStrategy } from \"./loadBalancerStrategies/unbalancedStrategy\";\nimport { isCredential } from \"./util/typeGuards\";\nimport { logger } from \"./logger\";\nimport { validateEventPositions } from \"./eventPosition\";\nimport { getRandomName } from \"./util/utils\";\n\nconst defaultConsumerClientOptions: Required<\n Pick<FullEventProcessorOptions, \"maxWaitTimeInSeconds\" | \"maxBatchSize\">\n> = {\n // to support our current \"process single event only\" workflow we'll also purposefully\n // only request a single event at a time.\n maxBatchSize: 1,\n maxWaitTimeInSeconds: 60,\n};\n\n/**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n *\n * There are multiple ways to create an `EventHubConsumerClient`\n * - Use the connection string from the SAS policy created for your Event Hub instance.\n * - Use the connection string from the SAS policy created for your Event Hub namespace,\n * and the name of the Event Hub instance\n * - Use the full namespace like `<yournamespace>.servicebus.windows.net`, and a credentials object.\n *\n * Optionally, you can also pass:\n * - An options bag to configure the retry policy or proxy settings.\n * - A checkpoint store that is used by the client to read checkpoints to determine the position from where it should\n * resume receiving events when your application gets restarted. The checkpoint store is also used by the client\n * to load balance multiple instances of your application.\n */\nexport class EventHubConsumerClient {\n /**\n * Describes the amqp connection context for the client.\n */\n private _context: ConnectionContext;\n /**\n * The options passed by the user when creating the EventHubClient instance.\n */\n private _clientOptions: EventHubConsumerClientOptions;\n private _partitionGate = new PartitionGate();\n\n /**\n * The Subscriptions that were spawned by calling `subscribe()`.\n * Subscriptions that have been stopped by the user will not\n * be present in this set.\n */\n private _subscriptions = new Set<Subscription>();\n\n /**\n * The name of the default consumer group in the Event Hubs service.\n */\n static defaultConsumerGroupName: string = Constants.defaultConsumerGroup;\n\n private _checkpointStore: CheckpointStore;\n private _userChoseCheckpointStore: boolean;\n\n /**\n * Options for configuring load balancing.\n */\n private readonly _loadBalancingOptions: Required<LoadBalancingOptions>;\n\n /**\n * @readonly\n * The name of the Event Hub instance for which this client is created.\n */\n get eventHubName(): string {\n return this._context.config.entityPath;\n }\n\n /**\n * @readonly\n * The fully qualified namespace of the Event Hub instance for which this client is created.\n * This is likely to be similar to <yournamespace>.servicebus.windows.net.\n */\n get fullyQualifiedNamespace(): string {\n return this._context.config.host;\n }\n\n /**\n * The name used to identify this EventHubConsumerClient.\n * If not specified or empty, a random unique one will be generated.\n */\n public readonly identifier: string;\n\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n connectionString: string,\n options?: EventHubConsumerClientOptions,\n ); // #1\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param checkpointStore - A checkpoint store that is used by the client to read checkpoints to determine\n * the position from where it should resume receiving events when your application gets restarted.\n * It is also used by the client to load balance multiple instances of your application.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n connectionString: string,\n checkpointStore: CheckpointStore,\n options?: EventHubConsumerClientOptions,\n ); // #1.1\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n connectionString: string,\n eventHubName: string,\n options?: EventHubConsumerClientOptions,\n ); // #2\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param checkpointStore - A checkpoint store that is used by the client to read checkpoints to determine\n * the position from where it should resume receiving events when your application gets restarted.\n * It is also used by the client to load balance multiple instances of your application.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n connectionString: string,\n eventHubName: string,\n checkpointStore: CheckpointStore,\n options?: EventHubConsumerClientOptions,\n ); // #2.1\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n options?: EventHubConsumerClientOptions,\n ); // #3\n /**\n * The `EventHubConsumerClient` class is used to consume events from an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param consumerGroup - The name of the consumer group from which you want to process events.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param checkpointStore - A checkpoint store that is used by the client to read checkpoints to determine\n * the position from where it should resume receiving events when your application gets restarted.\n * It is also used by the client to load balance multiple instances of your application.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n consumerGroup: string,\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n checkpointStore: CheckpointStore,\n options?: EventHubConsumerClientOptions,\n ); // #3.1\n constructor(\n private _consumerGroup: string,\n connectionStringOrFullyQualifiedNamespace2: string,\n checkpointStoreOrEventHubNameOrOptions3?:\n | CheckpointStore\n | EventHubConsumerClientOptions\n | string,\n checkpointStoreOrCredentialOrOptions4?:\n | CheckpointStore\n | EventHubConsumerClientOptions\n | TokenCredential\n | NamedKeyCredential\n | SASCredential,\n checkpointStoreOrOptions5?: CheckpointStore | EventHubConsumerClientOptions,\n options6?: EventHubConsumerClientOptions,\n ) {\n if (isCredential(checkpointStoreOrCredentialOrOptions4)) {\n // #3 or 3.1\n logger.info(\"Creating EventHubConsumerClient with TokenCredential.\");\n\n if (isCheckpointStore(checkpointStoreOrOptions5)) {\n // 3.1\n this._checkpointStore = checkpointStoreOrOptions5;\n this._userChoseCheckpointStore = true;\n this._clientOptions = options6 || {};\n } else {\n this._checkpointStore = new InMemoryCheckpointStore();\n this._userChoseCheckpointStore = false;\n this._clientOptions = checkpointStoreOrOptions5 || {};\n }\n\n this._context = createConnectionContext(\n connectionStringOrFullyQualifiedNamespace2,\n checkpointStoreOrEventHubNameOrOptions3 as string,\n checkpointStoreOrCredentialOrOptions4,\n this._clientOptions,\n );\n } else if (typeof checkpointStoreOrEventHubNameOrOptions3 === \"string\") {\n // #2 or 2.1\n logger.info(\"Creating EventHubConsumerClient with connection string and event hub name.\");\n\n if (isCheckpointStore(checkpointStoreOrCredentialOrOptions4)) {\n // 2.1\n this._checkpointStore = checkpointStoreOrCredentialOrOptions4;\n this._userChoseCheckpointStore = true;\n this._clientOptions = (checkpointStoreOrOptions5 as EventHubConsumerClientOptions) || {};\n } else {\n // 2\n this._checkpointStore = new InMemoryCheckpointStore();\n this._userChoseCheckpointStore = false;\n this._clientOptions = checkpointStoreOrCredentialOrOptions4 || {};\n }\n\n this._context = createConnectionContext(\n connectionStringOrFullyQualifiedNamespace2,\n checkpointStoreOrEventHubNameOrOptions3,\n this._clientOptions,\n );\n } else {\n // #1 or 1.1\n logger.info(\"Creating EventHubConsumerClient with connection string.\");\n\n if (isCheckpointStore(checkpointStoreOrEventHubNameOrOptions3)) {\n // 1.1\n this._checkpointStore = checkpointStoreOrEventHubNameOrOptions3;\n this._userChoseCheckpointStore = true;\n this._clientOptions =\n (checkpointStoreOrCredentialOrOptions4 as EventHubConsumerClientOptions) || {};\n } else {\n // 1\n this._checkpointStore = new InMemoryCheckpointStore();\n this._userChoseCheckpointStore = false;\n this._clientOptions =\n (checkpointStoreOrEventHubNameOrOptions3 as EventHubConsumerClientOptions) || {};\n }\n\n this._context = createConnectionContext(\n connectionStringOrFullyQualifiedNamespace2,\n this._clientOptions,\n );\n }\n this.identifier = this._clientOptions.identifier ?? getRandomName();\n this._loadBalancingOptions = {\n // default options\n strategy: \"balanced\",\n updateIntervalInMs: 10000,\n partitionOwnershipExpirationIntervalInMs: 60000,\n // options supplied by user\n ...this._clientOptions?.loadBalancingOptions,\n };\n }\n\n /**\n * Closes the AMQP connection to the Event Hub instance,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns Promise<void>\n * @throws Error if the underlying connection encounters an error while closing.\n */\n async close(): Promise<void> {\n // Stop all the actively running subscriptions.\n const activeSubscriptions = Array.from(this._subscriptions);\n await Promise.all(\n activeSubscriptions.map((subscription) => {\n return subscription.close();\n }),\n );\n // Close the connection via the connection context.\n return this._context.close();\n }\n\n /**\n * Provides the id for each partition associated with the Event Hub.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with an Array of strings representing the id for\n * each partition associated with the Event Hub.\n * @throws Error if the underlying connection has been closed, create a new EventHubConsumerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionIds(options: GetPartitionIdsOptions = {}): Promise<Array<string>> {\n return this._context\n .managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n })\n .then((eventHubProperties) => {\n return eventHubProperties.partitionIds;\n });\n }\n\n /**\n * Provides information about the state of the specified partition.\n * @param partitionId - The id of the partition for which information is required.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the state of the partition .\n * @throws Error if the underlying connection has been closed, create a new EventHubConsumerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionProperties(\n partitionId: string,\n options: GetPartitionPropertiesOptions = {},\n ): Promise<PartitionProperties> {\n return this._context.managementSession!.getPartitionProperties(partitionId, {\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n\n /**\n * Provides the Event Hub runtime information.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the Event Hub instance.\n * @throws Error if the underlying connection has been closed, create a new EventHubConsumerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getEventHubProperties(options: GetEventHubPropertiesOptions = {}): Promise<EventHubProperties> {\n return this._context.managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n\n /**\n * Subscribe to events from all partitions.\n *\n * If checkpoint store is provided to the `EventHubConsumerClient` and there are multiple\n * instances of your application, then each instance will subscribe to a subset of the\n * partitions such that the load is balanced amongst them.\n *\n * Call close() on the returned object to stop receiving events.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);\n * const subscription = client.subscribe(\n * {\n * processEvents: (events, context) => { console.log(\"Received event count: \", events.length) },\n * processError: (err, context) => { console.log(\"Error: \", err) }\n * },\n * { startPosition: earliestEventPosition }\n * );\n * ```\n *\n * @param handlers - Handlers for the lifecycle of the subscription - subscription initialization\n * per partition, receiving events, handling errors and the closing\n * of a subscription per partition.\n * @param options - Configures the way events are received.\n * Most common are `maxBatchSize` and `maxWaitTimeInSeconds` that control the flow of\n * events to the handler provided to receive events as well as the start position. For example,\n * `{ maxBatchSize: 20, maxWaitTimeInSeconds: 120, startPosition: { sequenceNumber: 123 } }`\n */\n subscribe(handlers: SubscriptionEventHandlers, options?: SubscribeOptions): Subscription; // #1\n /**\n * Subscribe to events from a single partition.\n * Call close() on the returned object to stop receiving events.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);\n * const subscription = client.subscribe(\n * partitionId,\n * {\n * processEvents: (events, context) => { console.log(\"Received event count: \", events.length) },\n * processError: (err, context) => { console.log(\"Error: \", err) }\n * },\n * { startPosition: earliestEventPosition }\n * );\n * ```\n *\n * @param partitionId - The id of the partition to subscribe to.\n * @param handlers - Handlers for the lifecycle of the subscription - subscription initialization\n * of the partition, receiving events, handling errors and the closing\n * of a subscription to the partition.\n * @param options - Configures the way events are received.\n * Most common are `maxBatchSize` and `maxWaitTimeInSeconds` that control the flow of\n * events to the handler provided to receive events as well as the start position. For example,\n * `{ maxBatchSize: 20, maxWaitTimeInSeconds: 120, startPosition: { sequenceNumber: 123 } }`\n */\n\n subscribe(\n partitionId: string,\n handlers: SubscriptionEventHandlers,\n options?: SubscribeOptions,\n ): Subscription; // #2\n subscribe(\n handlersOrPartitionId1?: SubscriptionEventHandlers | string,\n optionsOrHandlers2?: SubscribeOptions | SubscriptionEventHandlers,\n possibleOptions3?: SubscribeOptions,\n ): Subscription {\n let eventProcessor: EventProcessor;\n let targetedPartitionId: string;\n\n if (isSubscriptionEventHandlers(handlersOrPartitionId1)) {\n // #1: subscribe overload - read from all partitions\n const options = optionsOrHandlers2 as SubscribeOptions | undefined;\n if (options && options.startPosition) {\n validateEventPositions(options.startPosition);\n }\n ({ targetedPartitionId, eventProcessor } = this.createEventProcessorForAllPartitions(\n handlersOrPartitionId1,\n options,\n ));\n } else if (isSubscriptionEventHandlers(optionsOrHandlers2)) {\n // #2: subscribe overload (read from specific partition IDs), don't coordinate\n const options = possibleOptions3 as SubscribeOptions | undefined;\n if (options && options.startPosition) {\n validateEventPositions(options.startPosition);\n }\n ({ targetedPartitionId, eventProcessor } = this.createEventProcessorForSinglePartition(\n // cast to string as downstream code expects partitionId to be string, but JS users could have given us anything.\n // we don't validate the user input and instead rely on service throwing errors if any\n String(handlersOrPartitionId1),\n optionsOrHandlers2,\n possibleOptions3,\n ));\n } else {\n throw new TypeError(\"Unhandled subscribe() overload\");\n }\n\n eventProcessor.start();\n\n const subscription = {\n get isRunning() {\n return eventProcessor.isRunning();\n },\n close: () => {\n this._partitionGate.remove(targetedPartitionId);\n this._subscriptions.delete(subscription);\n return eventProcessor.stop();\n },\n };\n this._subscriptions.add(subscription);\n return subscription;\n }\n\n /**\n * Gets the LoadBalancing strategy that should be used based on what the user provided.\n */\n private _getLoadBalancingStrategy(): LoadBalancingStrategy {\n if (!this._userChoseCheckpointStore) {\n // The default behavior when a checkpointstore isn't provided\n // is to always grab all the partitions.\n return new UnbalancedLoadBalancingStrategy();\n }\n\n const partitionOwnershipExpirationIntervalInMs =\n this._loadBalancingOptions.partitionOwnershipExpirationIntervalInMs;\n if (this._loadBalancingOptions?.strategy === \"greedy\") {\n return new GreedyLoadBalancingStrategy(partitionOwnershipExpirationIntervalInMs);\n }\n\n // The default behavior when a checkpointstore is provided is\n // to grab one partition at a time.\n return new BalancedLoadBalancingStrategy(partitionOwnershipExpirationIntervalInMs);\n }\n\n private createEventProcessorForAllPartitions(\n subscriptionEventHandlers: SubscriptionEventHandlers,\n options?: SubscribeOptions,\n ): { targetedPartitionId: string; eventProcessor: EventProcessor } {\n this._partitionGate.add(\"all\");\n\n if (this._userChoseCheckpointStore) {\n logger.verbose(\n \"EventHubConsumerClient subscribing to all partitions, using a checkpoint store.\",\n );\n } else {\n logger.verbose(\"EventHubConsumerClient subscribing to all partitions, no checkpoint store.\");\n }\n\n const loadBalancingStrategy = this._getLoadBalancingStrategy();\n const eventProcessor = this._createEventProcessor(\n this._context,\n subscriptionEventHandlers,\n this._checkpointStore,\n {\n ...defaultConsumerClientOptions,\n ...(options as SubscribeOptions),\n ownerLevel: getOwnerLevel(options, this._userChoseCheckpointStore),\n // make it so all the event processors process work with the same overarching owner ID\n // this allows the EventHubConsumer to unify all the work for any processors that it spawns\n ownerId: this.identifier,\n retryOptions: this._clientOptions.retryOptions,\n loadBalancingStrategy,\n loopIntervalInMs: this._loadBalancingOptions.updateIntervalInMs,\n },\n );\n\n return { targetedPartitionId: \"all\", eventProcessor };\n }\n\n private createEventProcessorForSinglePartition(\n partitionId: string,\n eventHandlers: SubscriptionEventHandlers,\n options?: SubscribeOptions,\n ): { targetedPartitionId: string; eventProcessor: EventProcessor } {\n this._partitionGate.add(partitionId);\n\n const subscribeOptions = options as SubscribeOptions | undefined;\n\n if (this._userChoseCheckpointStore) {\n logger.verbose(\n `EventHubConsumerClient subscribing to specific partition (${partitionId}), using a checkpoint store.`,\n );\n } else {\n logger.verbose(\n `EventHubConsumerClient subscribing to specific partition (${partitionId}), no checkpoint store.`,\n );\n }\n\n const eventProcessor = this._createEventProcessor(\n this._context,\n eventHandlers,\n this._checkpointStore,\n {\n ...defaultConsumerClientOptions,\n ...options,\n processingTarget: partitionId,\n ownerLevel: getOwnerLevel(subscribeOptions, this._userChoseCheckpointStore),\n retryOptions: this._clientOptions.retryOptions,\n loadBalancingStrategy: new UnbalancedLoadBalancingStrategy(),\n loopIntervalInMs: this._loadBalancingOptions.updateIntervalInMs ?? 10000,\n },\n );\n\n return { targetedPartitionId: partitionId, eventProcessor };\n }\n\n private _createEventProcessor(\n connectionContext: ConnectionContext,\n subscriptionEventHandlers: SubscriptionEventHandlers,\n checkpointStore: CheckpointStore,\n options: FullEventProcessorOptions,\n ): EventProcessor {\n return new EventProcessor(\n this._consumerGroup,\n connectionContext,\n subscriptionEventHandlers,\n checkpointStore,\n options,\n );\n }\n}\n\n/**\n * @internal\n */\nexport function isCheckpointStore(possible: CheckpointStore | any): possible is CheckpointStore {\n if (!possible) {\n return false;\n }\n\n const checkpointStore = possible as CheckpointStore;\n\n return (\n typeof checkpointStore.claimOwnership === \"function\" &&\n typeof checkpointStore.listCheckpoints === \"function\" &&\n typeof checkpointStore.listOwnership === \"function\" &&\n typeof checkpointStore.updateCheckpoint === \"function\"\n );\n}\n\n/**\n * @internal\n */\nfunction isSubscriptionEventHandlers(\n possible: any | SubscriptionEventHandlers,\n): possible is SubscriptionEventHandlers {\n return typeof (possible as SubscriptionEventHandlers).processEvents === \"function\";\n}\n\nfunction getOwnerLevel(\n options: SubscribeOptions | undefined,\n userChoseCheckpointStore: boolean,\n): number | undefined {\n if (options && options.ownerLevel) {\n return options.ownerLevel;\n }\n\n if (userChoseCheckpointStore) {\n return 0;\n } else {\n return undefined;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { EventData, populateIdempotentMessageAnnotations, toRheaMessage } from \"./eventData\";\nimport { ConnectionContext } from \"./connectionContext\";\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\";\nimport { throwTypeErrorIfParameterMissing } from \"./util/error\";\nimport { PartitionPublishingProperties } from \"./models/private\";\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AmqpError,\n AwaitableSender,\n AwaitableSenderOptions,\n EventContext,\n OnAmqpEvent,\n Message as RheaMessage,\n message,\n types,\n} from \"rhea-promise\";\nimport {\n Constants,\n ErrorNameConditionMapper,\n RetryConfig,\n RetryOperationType,\n RetryOptions,\n defaultCancellableLock,\n delay,\n retry,\n translate,\n} from \"@azure/core-amqp\";\nimport {\n EventData,\n EventDataInternal,\n populateIdempotentMessageAnnotations,\n toRheaMessage,\n} from \"./eventData\";\nimport { EventDataBatch, EventDataBatchImpl, isEventDataBatch } from \"./eventDataBatch\";\nimport {\n logErrorStackTrace,\n createSimpleLogger,\n logger,\n SimpleLogger,\n createSenderLogPrefix,\n} from \"./logger\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { ConnectionContext } from \"./connectionContext\";\nimport { EventHubProducerOptions, IdempotentLinkProperties } from \"./models/private\";\nimport { SendOptions } from \"./models/public\";\nimport { PartitionPublishingOptions, PartitionPublishingProperties } from \"./models/private\";\nimport { getRetryAttemptTimeoutInMs } from \"./util/retries\";\nimport {\n idempotentProducerAmqpPropertyNames,\n PENDING_PUBLISH_SEQ_NUM_SYMBOL,\n} from \"./util/constants\";\nimport { isDefined } from \"@azure/core-util\";\nimport { translateError } from \"./util/error\";\nimport { TimerLoop } from \"./util/timerLoop\";\nimport { withAuth } from \"./withAuth\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * @internal\n */\nexport interface EventHubSenderOptions {\n /**\n * Indicates whether or not the sender should enable idempotent publishing to Event Hub partitions.\n */\n enableIdempotentProducer: boolean;\n /**\n * The EventHub partition id to which the sender wants to send the event data.\n */\n partitionId?: string;\n /**\n * The set of options that can be specified to influence publishing behavior\n * specific to a partition.\n */\n partitionPublishingOptions?: PartitionPublishingOptions;\n}\n\n/**\n * Describes the EventHubSender that will send event data to EventHub.\n * @internal\n */\nexport class EventHubSender {\n /**\n * The unique lock name per connection that is used to acquire the\n * lock for establishing a sender link by an entity on that connection.\n */\n private readonly senderLock: string = getRandomName(\"sender\");\n /**\n * The handler function to handle errors that happen on the\n * underlying sender.\n */\n private readonly _onAmqpError: OnAmqpEvent;\n /**\n * The handler function to handle \"sender_close\" event\n * that happens on the underlying sender.\n */\n private readonly _onAmqpClose: OnAmqpEvent;\n /**\n * The message handler that will be set as the handler on\n * the underlying rhea sender's session for the \"session_error\" event.\n */\n private _onSessionError: OnAmqpEvent;\n /**\n * The message handler that will be set as the handler on\n * the underlying rhea sender's session for the \"session_close\" event.\n */\n private _onSessionClose: OnAmqpEvent;\n /**\n * The AMQP sender link.\n */\n private _sender?: AwaitableSender;\n /**\n * The partition ID.\n */\n private readonly partitionId?: string;\n /**\n * Indicates whether the sender is configured for idempotent publishing.\n */\n private _isIdempotentProducer: boolean;\n /**\n * Indicates whether the sender has an in-flight send while idempotent\n * publishing is enabled.\n */\n private _hasPendingSend?: boolean;\n /**\n * A local copy of the PartitionPublishingProperties that can be mutated to\n * keep track of the lastSequenceNumber used.\n */\n private _localPublishingProperties?: PartitionPublishingProperties;\n /**\n * The user-provided set of options that can be specified to influence\n * publishing behavior specific to a partition.\n */\n private _userProvidedPublishingOptions?: PartitionPublishingOptions;\n /**\n * Indicates whether the link is in the process of connecting\n * (establishing) itself. Default value: `false`.\n */\n private isConnecting: boolean = false;\n /**\n * The unique name for the entity (mostly a guid).\n */\n private readonly name: string;\n /**\n * The address in the following form:\n * - `\"<hubName>\"`\n * - `\"<hubName>/Partitions/<partitionId>\"`.\n */\n private readonly address: string;\n /**\n * The token audience in the following form:\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>\"`\n * - `\"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>\"`.\n */\n private readonly audience: string;\n /**\n * Provides relevant information about the amqp connection,\n * cbs and $management sessions, token provider, sender and receivers.\n */\n private readonly _context: ConnectionContext;\n /**\n * The auth loop.\n */\n private authLoop?: TimerLoop;\n /**\n * The logger.\n */\n private readonly logger: SimpleLogger;\n\n /** The client identifier */\n private _id: string;\n\n /**\n * Creates a new EventHubSender instance.\n * @param context - The connection context.\n * @param options - Options used to configure the EventHubSender.\n */\n constructor(\n context: ConnectionContext,\n senderId: string,\n { partitionId, enableIdempotentProducer, partitionPublishingOptions }: EventHubSenderOptions,\n ) {\n this.address = context.config.getSenderAddress(partitionId);\n this.name = this.address;\n this._id = senderId;\n this.audience = context.config.getSenderAudience(partitionId);\n this._context = context;\n this.partitionId = partitionId;\n this._isIdempotentProducer = enableIdempotentProducer;\n this._userProvidedPublishingOptions = partitionPublishingOptions;\n const logPrefix = createSenderLogPrefix(this.name, this._context.connectionId);\n this.logger = createSimpleLogger(logger, logPrefix);\n\n this._onAmqpError = (eventContext: EventContext) => {\n const senderError = eventContext.sender && eventContext.sender.error;\n this.logger.verbose(\n \"'sender_error' event occurred. The associated error is: %O\",\n senderError,\n );\n // TODO: Consider rejecting promise in trySendBatch() or createBatch()\n };\n\n this._onSessionError = (eventContext: EventContext) => {\n const sessionError = eventContext.session && eventContext.session.error;\n this.logger.verbose(\n \"'session_error' event occurred. The associated error is: %O\",\n sessionError,\n );\n // TODO: Consider rejecting promise in trySendBatch() or createBatch()\n };\n\n this._onAmqpClose = async (eventContext: EventContext) => {\n const sender = this._sender || eventContext.sender!;\n this.logger.verbose(\n \"'sender_close' event occurred. Value for isItselfClosed on the receiver is: '%s' \" +\n \"Value for isConnecting on the session is: '%s'.\",\n sender?.isItselfClosed().toString(),\n this.isConnecting,\n );\n if (sender && !this.isConnecting) {\n // Call close to clean up timers & other resources\n await sender.close().catch((err) => {\n this.logger.verbose(\"error when closing after 'sender_close' event: %O\", err);\n });\n }\n };\n\n this._onSessionClose = async (eventContext: EventContext) => {\n const sender = this._sender || eventContext.sender!;\n this.logger.verbose(\n \"'session_close' event occurred. Value for isSessionItselfClosed on the session is: '%s' \" +\n \"Value for isConnecting on the session is: '%s'.\",\n sender?.isSessionItselfClosed().toString(),\n this.isConnecting,\n );\n if (sender && !this.isConnecting) {\n // Call close to clean up timers & other resources\n await sender.close().catch((err) => {\n this.logger.verbose(\"error when closing after 'session_close' event: %O\", err);\n });\n }\n };\n }\n\n /**\n * Deletes the sender from the context. Clears the token renewal timer. Closes the sender link.\n */\n async close(): Promise<void> {\n try {\n if (this._sender) {\n this.logger.info(\"closing\");\n const senderLink = this._sender;\n this._deleteFromCache();\n await senderLink.close();\n this.authLoop?.stop();\n this.logger.verbose(\"closed.\");\n }\n } catch (err: any) {\n const msg = `an error occurred while closing: ${err?.name}: ${err?.message}`;\n this.logger.warning(msg);\n logErrorStackTrace(err);\n throw err;\n }\n }\n\n /**\n * Determines whether the AMQP sender link is open. If open then returns true else returns false.\n * @returns boolean\n */\n isOpen(): boolean {\n const result = Boolean(this._sender && this._sender.isOpen());\n this.logger.verbose(\"is open? -> %s\", result);\n return result;\n }\n /**\n * Returns maximum message size on the AMQP sender link.\n * @param abortSignal - An implementation of the `AbortSignalLike` interface to signal the request to cancel the operation.\n * For example, use the &commat;azure/abort-controller to create an `AbortSignal`.\n * @returns Promise<number>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n async getMaxMessageSize(\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n } = {},\n ): Promise<number> {\n const sender = await this._getLink(options);\n\n return sender.maxMessageSize;\n }\n\n /**\n * Get the information about the state of publishing for a partition as observed by the `EventHubSender`.\n * This data can always be read, but will only be populated with information relevant to the active features\n * for the producer client.\n */\n async getPartitionPublishingProperties(\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n } = {},\n ): Promise<PartitionPublishingProperties> {\n if (this._localPublishingProperties) {\n // Send a copy of the properties so it can't be mutated downstream.\n return { ...this._localPublishingProperties };\n }\n\n const properties: PartitionPublishingProperties = {\n isIdempotentPublishingEnabled: this._isIdempotentProducer,\n partitionId: this.partitionId ?? \"\",\n };\n\n if (this._isIdempotentProducer) {\n this._sender = await this._getLink(options);\n // await this._createLinkIfNotOpen(options);\n if (!this._sender) {\n // createLinkIfNotOpen should throw if `this._sender` can't be created, but just in case it gets\n // deleted while setting up token refreshing, make sure it exists.\n throw new Error(\n `Failed to retrieve partition publishing properties for partition \"${this.partitionId}\".`,\n );\n }\n\n const {\n [idempotentProducerAmqpPropertyNames.epoch]: ownerLevel,\n [idempotentProducerAmqpPropertyNames.producerId]: producerGroupId,\n [idempotentProducerAmqpPropertyNames.producerSequenceNumber]: lastPublishedSequenceNumber,\n } = this._sender.properties ?? {};\n\n properties.ownerLevel = parseInt(ownerLevel, 10);\n properties.producerGroupId = parseInt(producerGroupId, 10);\n properties.lastPublishedSequenceNumber = parseInt(lastPublishedSequenceNumber, 10);\n }\n\n this._localPublishingProperties = properties;\n\n // Send a copy of the properties so it can't be mutated downstream.\n return { ...properties };\n }\n\n /**\n * Send a batch of EventData to the EventHub. The \"message_annotations\",\n * \"application_properties\" and \"properties\" of the first message will be set as that\n * of the envelope (batch message).\n * @param events - An array of EventData objects to be sent in a Batch message.\n * @param options - Options to control the way the events are batched along with request options\n */\n async send(\n events: EventData[] | EventDataBatch,\n options?: SendOptions &\n EventHubProducerOptions & { tracingProperties?: Array<EventData[\"properties\"]> },\n ): Promise<void> {\n try {\n this.logger.info(\"trying to send EventData[].\");\n if (this._isIdempotentProducer && this._hasPendingSend) {\n throw new Error(\n `There can only be 1 \"sendBatch\" call in-flight per partition while \"enableIdempotentRetries\" is set to true.`,\n );\n }\n\n const eventCount = isEventDataBatch(events) ? events.count : events.length;\n if (eventCount === 0) {\n this.logger.info(`no events were passed to sendBatch.`);\n return;\n }\n\n if (this._isIdempotentProducer) {\n this._hasPendingSend = true;\n }\n\n this.logger.info(\"sending encoded batch message.\");\n await this._trySendBatch(events, options);\n if (this._isIdempotentProducer) {\n commitIdempotentSequenceNumbers(events);\n if (this._localPublishingProperties) {\n const { lastPublishedSequenceNumber = 0 } = this._localPublishingProperties;\n // Increment the lastPublishedSequenceNumber based on the number of events published.\n this._localPublishingProperties.lastPublishedSequenceNumber =\n lastPublishedSequenceNumber + eventCount;\n }\n }\n return;\n } catch (err: any) {\n rollbackIdempotentSequenceNumbers(events);\n this.logger.warning(\n `an error occurred while sending the batch message ${err?.name}: ${err?.message}`,\n );\n logErrorStackTrace(err);\n throw err;\n } finally {\n if (this._isIdempotentProducer) {\n this._hasPendingSend = false;\n }\n }\n }\n\n /**\n * @param sender - The rhea sender that contains the idempotent producer properties.\n */\n private _populateLocalPublishingProperties(sender: AwaitableSender): void {\n const {\n [idempotentProducerAmqpPropertyNames.epoch]: ownerLevel,\n [idempotentProducerAmqpPropertyNames.producerId]: producerGroupId,\n [idempotentProducerAmqpPropertyNames.producerSequenceNumber]: lastPublishedSequenceNumber,\n } = sender.properties ?? {};\n\n this._localPublishingProperties = {\n isIdempotentPublishingEnabled: this._isIdempotentProducer,\n partitionId: this.partitionId ?? \"\",\n lastPublishedSequenceNumber,\n ownerLevel,\n producerGroupId,\n };\n }\n\n private _deleteFromCache(): void {\n this._sender = undefined;\n delete this._context.senders[this.name];\n this.logger.verbose(\"deleted from the client cache.\");\n }\n\n private _createSenderOptions(): AwaitableSenderOptions {\n const srOptions: AwaitableSenderOptions = {\n name: this.name,\n source: this._id,\n target: {\n address: this.address,\n },\n onError: this._onAmqpError,\n onClose: this._onAmqpClose,\n onSessionError: this._onSessionError,\n onSessionClose: this._onSessionClose,\n };\n\n srOptions.desired_capabilities = [Constants.geoReplication];\n if (this._isIdempotentProducer) {\n srOptions.desired_capabilities.push(idempotentProducerAmqpPropertyNames.capability);\n const idempotentProperties = generateIdempotentLinkProperties(\n this._userProvidedPublishingOptions,\n this._localPublishingProperties,\n );\n srOptions.properties = idempotentProperties;\n }\n this.logger.verbose(\"being created with options: %O\", srOptions);\n return srOptions;\n }\n\n /**\n * Tries to send the message to EventHub if there is enough credit to send them\n * and the circular buffer has available space to settle the message after sending them.\n *\n * We have implemented a synchronous send over here in the sense that we shall be waiting\n * for the message to be accepted or rejected and accordingly resolve or reject the promise.\n * @param rheaMessage - The message to be sent to EventHub.\n * @returns Promise<void>\n */\n private async _trySendBatch(\n events: EventData[] | EventDataBatch,\n options: SendOptions &\n EventHubProducerOptions & {\n /**\n * Tracing properties that are associated with EventData.\n */\n tracingProperties?: Array<EventData[\"properties\"]>;\n } = {},\n ): Promise<void> {\n const abortSignal: AbortSignalLike | undefined = options.abortSignal;\n const retryOptions = options.retryOptions || {};\n const timeoutInMs = getRetryAttemptTimeoutInMs(retryOptions);\n retryOptions.timeoutInMs = timeoutInMs;\n\n const sendEventPromise = async (): Promise<void> => {\n const initStartTime = Date.now();\n // TODO: (jeremymeng) A or B\n // variant A:\n const sender = await this._getLink(options);\n // variant B\n // await this._createLinkIfNotOpen(options);\n const publishingProps = await this.getPartitionPublishingProperties(options);\n const timeTakenByInit = Date.now() - initStartTime;\n\n this.logger.verbose(\n \"credit: %d available: %d\",\n sender.credit,\n sender.session.outgoing.available(),\n );\n\n let waitTimeForSendable = 1000;\n if (!sender.sendable() && timeoutInMs - timeTakenByInit > waitTimeForSendable) {\n this.logger.verbose(\"waiting for 1 second for sender to become sendable\");\n\n await delay(waitTimeForSendable);\n\n this.logger.verbose(\n \"after waiting for a second, credit: %d available: %d\",\n sender.credit,\n sender.session?.outgoing?.available(),\n );\n } else {\n waitTimeForSendable = 0;\n }\n\n if (!sender.sendable()) {\n // let us retry to send the message after some time.\n const msg = `cannot send the message right now. Please try later.`;\n this.logger.warning(msg);\n const amqpError: AmqpError = {\n condition: ErrorNameConditionMapper.SenderBusyError,\n description: msg,\n };\n throw translate(amqpError);\n }\n\n if (timeoutInMs <= timeTakenByInit + waitTimeForSendable) {\n const desc: string =\n `was not able to send the message right now, due ` + `to operation timeout.`;\n this.logger.warning(desc);\n const e: AmqpError = {\n condition: ErrorNameConditionMapper.ServiceUnavailableError,\n description: desc,\n };\n throw translate(e);\n }\n\n try {\n const encodedMessage = transformEventsForSend(events, publishingProps, options);\n const delivery = await sender.send(encodedMessage, {\n format: 0x80013700,\n timeoutInSeconds: (timeoutInMs - timeTakenByInit - waitTimeForSendable) / 1000,\n abortSignal,\n });\n this.logger.info(\"sent message with delivery id: %d\", delivery.id);\n } catch (err: any) {\n const error = err.innerError || err;\n const translatedError = translateError(error);\n throw translatedError;\n }\n };\n\n const config: RetryConfig<void> = {\n operation: sendEventPromise,\n connectionId: this._context.connectionId,\n operationType: RetryOperationType.sendMessage,\n abortSignal: abortSignal,\n retryOptions: retryOptions,\n };\n\n try {\n await retry<void>(config);\n } catch (err: any) {\n const translatedError = translate(err);\n this.logger.warning(\n \"an error occurred while sending the message %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n private async _getLink(\n options: {\n retryOptions?: RetryOptions;\n abortSignal?: AbortSignalLike;\n } = {},\n ): Promise<AwaitableSender> {\n if (this.isOpen() && this._sender) {\n return this._sender;\n }\n const retryOptions = options.retryOptions || {};\n const timeoutInMs = getRetryAttemptTimeoutInMs(retryOptions);\n retryOptions.timeoutInMs = timeoutInMs;\n const senderOptions = this._createSenderOptions();\n\n const startTime = Date.now();\n const createLinkPromise = async (): Promise<AwaitableSender> => {\n return defaultCancellableLock.acquire(\n this.senderLock,\n () => {\n const taskStartTime = Date.now();\n const taskTimeoutInMs = timeoutInMs - (taskStartTime - startTime);\n return this._init({\n ...senderOptions,\n abortSignal: options.abortSignal,\n timeoutInMs: taskTimeoutInMs,\n });\n },\n { abortSignal: options.abortSignal, timeoutInMs: timeoutInMs },\n );\n };\n\n const config: RetryConfig<AwaitableSender> = {\n operation: createLinkPromise,\n connectionId: this._context.connectionId,\n operationType: RetryOperationType.senderLink,\n abortSignal: options.abortSignal,\n retryOptions: retryOptions,\n };\n\n try {\n return await retry<AwaitableSender>(config);\n } catch (err: any) {\n const translatedError = translate(err);\n this.logger.warning(\n \"an error occurred while creating: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Initializes the sender session on the connection.\n * Should only be called from _createLinkIfNotOpen\n */\n private async _init(\n options: AwaitableSenderOptions & {\n abortSignal: AbortSignalLike | undefined;\n timeoutInMs: number;\n },\n ): Promise<AwaitableSender> {\n const createSender = async () => {\n this.logger.verbose(\"trying to be created...\");\n\n const sender = await this._context.connection.createAwaitableSender(options);\n this._sender = sender;\n this._populateLocalPublishingProperties(this._sender);\n this.isConnecting = false;\n this.logger.verbose(\"created with options: %O\", options);\n\n // It is possible for someone to close the sender and then start it again.\n // Thus make sure that the sender is present in the client cache.\n if (!this._context.senders[this.name]) this._context.senders[this.name] = this;\n };\n try {\n if (!this.isOpen() || !this._sender) {\n await this._context.readyToOpenLink();\n this.authLoop = await withAuth(\n createSender,\n this._context,\n this.audience,\n options.timeoutInMs,\n this.logger,\n { abortSignal: options.abortSignal },\n );\n // it is guaranteed to be defined at this point, otherwise, an error would\n // have been thrown.\n return this._sender!;\n } else {\n this.logger.verbose(\"is open -> %s. Hence not reconnecting.\", this.isOpen());\n return this._sender;\n }\n } catch (err) {\n const translatedError = translate(err);\n this.logger.warning(\n \"an error occurred while being created: %s\",\n `${translatedError?.name}: ${translatedError?.message}`,\n );\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }\n\n /**\n * Creates a new sender to the given event hub, and optionally to a given partition if it is\n * not present in the context or returns the one present in the context.\n * @hidden\n * @param options - Options used to configure the EventHubSender.\n */\n static create(\n context: ConnectionContext,\n senderId: string,\n options: EventHubSenderOptions,\n ): EventHubSender {\n const ehSender: EventHubSender = new EventHubSender(context, senderId, options);\n if (!context.senders[ehSender.name]) {\n context.senders[ehSender.name] = ehSender;\n }\n return context.senders[ehSender.name];\n }\n}\n\n/**\n * Generates the link properties for an indemopotent sender given\n * based on the user-provided and locally-cached publishing options.\n *\n * Note: The set of idempotent properties a user specifies at EventHubProducerClient instantiation-time\n * is slightly different than what the service returns and the EventHubSender keeps track of locally.\n *\n * The difference is that the user specifies the `startingSequenceNumber`, whereas the local options\n * (those returned by getPartitionPublishingProperties) specifies `lastPublishedSequenceNumber`.\n *\n * These _can_ be the same, but the user is technically free to set any `startingSequenceNumber` they want.\n * @internal\n */\nexport function generateIdempotentLinkProperties(\n userProvidedPublishingOptions: PartitionPublishingOptions | undefined,\n localPublishingOptions: PartitionPublishingProperties | undefined,\n): IdempotentLinkProperties | Record<string, never> {\n let ownerLevel: number | undefined;\n let producerGroupId: number | undefined;\n let sequenceNumber: number | undefined;\n\n // Prefer local publishing options since this is the up-to-date state of the sender.\n // Only use user-provided publishing options the first time we create the link.\n if (localPublishingOptions) {\n ownerLevel = localPublishingOptions.ownerLevel;\n producerGroupId = localPublishingOptions.producerGroupId;\n sequenceNumber = localPublishingOptions.lastPublishedSequenceNumber;\n } else if (userProvidedPublishingOptions) {\n ownerLevel = userProvidedPublishingOptions.ownerLevel;\n producerGroupId = userProvidedPublishingOptions.producerGroupId;\n sequenceNumber = userProvidedPublishingOptions.startingSequenceNumber;\n } else {\n // If we don't have any properties at all, send an empty object.\n // This will cause the service to generate a new producer-id for our client.\n return {};\n }\n\n // The service requires that if ANY_ of these properties are defined,\n // they _ALL_ have to be defined.\n // If we don't have one of the required values, use `null` and the\n // service will provide it.\n const idempotentLinkProperties: IdempotentLinkProperties = {\n [idempotentProducerAmqpPropertyNames.epoch]: isDefined(ownerLevel)\n ? types.wrap_short(ownerLevel)\n : null,\n [idempotentProducerAmqpPropertyNames.producerId]: isDefined(producerGroupId)\n ? types.wrap_long(producerGroupId)\n : null,\n [idempotentProducerAmqpPropertyNames.producerSequenceNumber]: isDefined(sequenceNumber)\n ? types.wrap_int(sequenceNumber)\n : null,\n };\n\n return idempotentLinkProperties;\n}\n\n/**\n * Encodes a list or batch of events into a single binary message that can be sent to the service.\n *\n * Prior to encoding, any special properties not specified by the user, such as tracing or idempotent\n * properties, are assigned to the list or batch of events as needed.\n *\n * @internal\n * @param events - Events to transform for sending to the service.\n * @param publishingProps - Describes the current publishing state for the partition.\n * @param options - Options used to configure this function.\n */\nexport function transformEventsForSend(\n events: EventData[] | EventDataBatch,\n publishingProps: PartitionPublishingProperties,\n options: SendOptions & {\n /**\n * A list containing the `Diagnostic-Id` tracing property that is associated with each EventData.\n * The index of tracingProperties corresponds to the same index in `events` when `events` is EventData[].\n */\n tracingProperties?: Array<EventData[\"properties\"]>;\n } = {},\n): Buffer {\n if (isEventDataBatch(events)) {\n return (events as EventDataBatchImpl)._generateMessage(publishingProps);\n } else {\n const eventCount = events.length;\n // convert events to rhea messages\n const rheaMessages: RheaMessage[] = [];\n const tracingProperties = options.tracingProperties ?? [];\n for (let i = 0; i < eventCount; i++) {\n const originalEvent = events[i];\n const tracingProperty = tracingProperties[i];\n // Create a copy of the user's event so we can add the tracing property.\n const event: EventData = {\n ...originalEvent,\n properties: { ...originalEvent.properties, ...tracingProperty },\n };\n const rheaMessage = toRheaMessage(event, options.partitionKey);\n\n // populate idempotent message annotations\n const { lastPublishedSequenceNumber = 0 } = publishingProps;\n const startingSequenceNumber = lastPublishedSequenceNumber + 1;\n const pendingPublishSequenceNumber = startingSequenceNumber + i;\n populateIdempotentMessageAnnotations(rheaMessage, {\n ...publishingProps,\n publishSequenceNumber: pendingPublishSequenceNumber,\n });\n\n if (publishingProps.isIdempotentPublishingEnabled) {\n // Set pending seq number on user's event.\n (originalEvent as EventDataInternal)[PENDING_PUBLISH_SEQ_NUM_SYMBOL] =\n pendingPublishSequenceNumber;\n }\n\n rheaMessages.push(rheaMessage);\n }\n\n // Encode every amqp message and then convert every encoded message to amqp data section\n const batchMessage: RheaMessage = {\n body: message.data_sections(rheaMessages.map(message.encode)),\n };\n\n // Set message_annotations of the first message as\n // that of the envelope (batch message).\n if (rheaMessages[0].message_annotations) {\n batchMessage.message_annotations = { ...rheaMessages[0].message_annotations };\n }\n\n // Finally encode the envelope (batch message).\n return message.encode(batchMessage);\n }\n}\n\n/**\n * Commits the pending publish sequence number events.\n * EventDataBatch exposes this as `startingPublishSequenceNumber`,\n * EventData not in a batch exposes this as `publishedSequenceNumber`.\n */\nfunction commitIdempotentSequenceNumbers(\n events: Omit<EventDataInternal, \"getRawAmqpMessage\">[] | EventDataBatch,\n): void {\n if (isEventDataBatch(events)) {\n (events as EventDataBatchImpl)._commitPublish();\n } else {\n // For each event, set the `publishedSequenceNumber` equal to the sequence number\n // we set when we attempted to send the events to the service.\n for (const event of events) {\n event._publishedSequenceNumber = event[PENDING_PUBLISH_SEQ_NUM_SYMBOL];\n delete event[PENDING_PUBLISH_SEQ_NUM_SYMBOL];\n }\n }\n}\n\n/**\n * Rolls back any pending publish sequence number in the events.\n */\nfunction rollbackIdempotentSequenceNumbers(\n events: Omit<EventDataInternal, \"getRawAmqpMessage\">[] | EventDataBatch,\n): void {\n if (isEventDataBatch(events)) {\n /* No action required. */\n } else {\n for (const event of events) {\n delete event[PENDING_PUBLISH_SEQ_NUM_SYMBOL];\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ConnectionContext, createConnectionContext } from \"./connectionContext\";\nimport {\n CreateBatchOptions,\n EventHubClientOptions,\n GetEventHubPropertiesOptions,\n GetPartitionIdsOptions,\n GetPartitionPropertiesOptions,\n SendBatchOptions,\n} from \"./models/public\";\nimport { PartitionPublishingOptions, PartitionPublishingProperties } from \"./models/private\";\nimport { EventDataBatch, EventDataBatchImpl, isEventDataBatch } from \"./eventDataBatch\";\nimport { EventHubProperties, PartitionProperties } from \"./managementClient\";\nimport { TracingContext, TracingSpanLink } from \"@azure/core-tracing\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport { isDefined } from \"@azure/core-util\";\nimport { isCredential } from \"./util/typeGuards\";\nimport { logErrorStackTrace, logger } from \"./logger\";\nimport {\n idempotentAlreadyPublished,\n idempotentSomeAlreadyPublished,\n throwErrorIfConnectionClosed,\n throwTypeErrorIfParameterMissing,\n validateProducerPartitionSettings,\n} from \"./util/error\";\nimport { AmqpAnnotatedMessage } from \"@azure/core-amqp\";\nimport { EventData, EventDataInternal } from \"./eventData\";\nimport { EventHubSender } from \"./eventHubSender\";\nimport { OperationOptions } from \"./util/operationOptions\";\nimport { toSpanOptions, tracingClient } from \"./diagnostics/tracing\";\nimport { instrumentEventData } from \"./diagnostics/instrumentEventData\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n *\n * There are multiple ways to create an `EventHubProducerClient`\n * - Use the connection string from the SAS policy created for your Event Hub instance.\n * - Use the connection string from the SAS policy created for your Event Hub namespace,\n * and the name of the Event Hub instance\n * - Use the full namespace like `<yournamespace>.servicebus.windows.net`, and a credentials object.\n *\n * Optionally, you can also pass an options bag to configure the retry policy or proxy settings.\n *\n */\nexport class EventHubProducerClient {\n /**\n * Describes the amqp connection context for the client.\n */\n private _context: ConnectionContext;\n\n /**\n * The options passed by the user when creating the EventHubClient instance.\n */\n private _clientOptions: EventHubClientOptions;\n /**\n * Map of partitionId to senders\n */\n private _sendersMap: Map<string, EventHubSender>;\n /**\n * Indicates whether or not the EventHubProducerClient should enable idempotent publishing to Event Hub partitions.\n * If enabled, the producer will only be able to publish directly to partitions;\n * it will not be able to publish to the Event Hubs gateway for automatic partition routing\n * nor will it be able to use a partition key.\n * Default: false\n */\n private _enableIdempotentRetries?: boolean;\n /**\n * The set of options that can be specified to influence publishing behavior specific to the configured Event Hub partition.\n * These options are not necessary in the majority of scenarios and are intended for use with specialized scenarios,\n * such as when recovering the state used for idempotent publishing.\n */\n private _partitionOptions?: Record<string, PartitionPublishingOptions>;\n /**\n * @readonly\n * The name of the Event Hub instance for which this client is created.\n */\n get eventHubName(): string {\n return this._context.config.entityPath;\n }\n\n /**\n * @readonly\n * The fully qualified namespace of the Event Hub instance for which this client is created.\n * This is likely to be similar to <yournamespace>.servicebus.windows.net.\n */\n get fullyQualifiedNamespace(): string {\n return this._context.config.host;\n }\n\n /**\n * The name used to identify this EventHubProducerClient.\n * If not specified or empty, a random unique one will be generated.\n */\n public readonly identifier: string;\n\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, eventHubName: string, options?: EventHubClientOptions); // eslint-disable-line @azure/azure-sdk/ts-naming-options\n /**\n * The `EventHubProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n options?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n );\n constructor(\n fullyQualifiedNamespaceOrConnectionString1: string,\n eventHubNameOrOptions2?: string | EventHubClientOptions,\n credentialOrOptions3?:\n | TokenCredential\n | NamedKeyCredential\n | SASCredential\n | EventHubClientOptions,\n options4?: EventHubClientOptions, // eslint-disable-line @azure/azure-sdk/ts-naming-options\n ) {\n this._context = createConnectionContext(\n fullyQualifiedNamespaceOrConnectionString1,\n eventHubNameOrOptions2,\n credentialOrOptions3,\n options4,\n );\n if (typeof eventHubNameOrOptions2 !== \"string\") {\n this._clientOptions = eventHubNameOrOptions2 || {};\n } else if (!isCredential(credentialOrOptions3)) {\n this._clientOptions = credentialOrOptions3 || {};\n } else {\n this._clientOptions = options4 || {};\n }\n this.identifier = this._clientOptions.identifier ?? getRandomName();\n this._sendersMap = new Map();\n }\n\n /**\n * Creates an instance of `EventDataBatch` to which one can add events until the maximum supported size is reached.\n * The batch can be passed to the {@link sendBatch} method of the `EventHubProducerClient` to be sent to Azure Event Hubs.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n *\n * @param options - Configures the behavior of the batch.\n * - `partitionKey` : A value that is hashed and used by the Azure Event Hubs service to determine the partition to which\n * the events need to be sent.\n * - `partitionId` : Id of the partition to which the batch of events need to be sent.\n * - `maxSizeInBytes`: The upper limit for the size of batch. The `tryAdd` function will return `false` after this limit is reached.\n * - `abortSignal` : A signal the request to cancel the operation.\n * @returns Promise<EventDataBatch>\n * @throws Error if both `partitionId` and `partitionKey` are set in the options.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal in the options.\n */\n async createBatch(options: CreateBatchOptions = {}): Promise<EventDataBatch> {\n throwErrorIfConnectionClosed(this._context);\n\n const partitionId = isDefined(options.partitionId) ? String(options.partitionId) : undefined;\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey: options.partitionKey,\n });\n\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n let maxMessageSize = await sender.getMaxMessageSize({\n retryOptions: this._clientOptions.retryOptions,\n abortSignal: options.abortSignal,\n });\n\n if (options.maxSizeInBytes) {\n if (options.maxSizeInBytes > maxMessageSize) {\n const error = new Error(\n `Max message size (${options.maxSizeInBytes} bytes) is greater than maximum message size (${maxMessageSize} bytes) on the AMQP sender link.`,\n );\n logger.warning(`[${this._context.connectionId}] ${error.message}`);\n logErrorStackTrace(error);\n throw error;\n }\n maxMessageSize = options.maxSizeInBytes;\n }\n return new EventDataBatchImpl(\n this._context,\n maxMessageSize,\n Boolean(this._enableIdempotentRetries),\n options.partitionKey,\n partitionId,\n );\n }\n\n /**\n * Get the information about the state of publishing for a partition as observed by the `EventHubProducerClient`.\n * This data can always be read, but will only be populated with information relevant to the active features\n * for the producer client.\n *\n * @param partitionId - Id of the partition from which to retrieve publishing properties.\n * @param options - The set of options to apply to the operation call.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore this is called in EventHubBufferedProducerClient via cast-to-any workaround\n private async getPartitionPublishingProperties(\n partitionId: string,\n options: OperationOptions = {},\n ): Promise<PartitionPublishingProperties> {\n if (!isDefined(partitionId)) {\n throw new TypeError(\n `getPartitionPublishingProperties called without required argument \"partitionId\"`,\n );\n }\n\n if (typeof partitionId === \"number\") {\n partitionId = String(partitionId);\n }\n\n let sender = this._sendersMap.get(partitionId);\n if (!sender) {\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions: this._partitionOptions?.[partitionId],\n });\n this._sendersMap.set(partitionId, sender);\n }\n\n return sender.getPartitionPublishingProperties(options);\n }\n\n /**\n * Sends an array of events as a batch to the associated Event Hub.\n *\n * Azure Event Hubs has a limit on the size of the batch that can be sent which if exceeded\n * will result in an error with code `MessageTooLargeError`.\n * To safely send within batch size limits, use `EventHubProducerClient.createBatch()` or\n * `EventHubBufferedProducerClient` instead.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * await client.sendBatch(messages);\n * ```\n *\n * @param batch - An array of {@link EventData} or `AmqpAnnotatedMessage`.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n * - `partitionId` : The partition this batch will be sent to. If set, `partitionKey` can not be set.\n * - `partitionKey` : A value that is hashed to produce a partition assignment. If set, `partitionId` can not be set.\n *\n * @returns Promise<void>\n * @throws MessageTooLargeError if all the events in the input array cannot be fit into a batch.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(\n batch: EventData[] | AmqpAnnotatedMessage[],\n options?: SendBatchOptions,\n ): Promise<void>;\n /**\n * Sends a batch of events created using `EventHubProducerClient.createBatch()` to the associated Event Hub.\n *\n * Events with different values for partitionKey or partitionId will need to be put into different batches.\n * To simplify such batch management across partitions or to have the client automatically batch events\n * and send them in specific intervals, use `EventHubBufferedProducerClient` instead.\n *\n * The below example assumes you have an array of events at hand to be batched safely.\n * If you have events coming in one by one, `EventHubBufferedProducerClient` is recommended instead\n * for effecient management of batches.\n *\n * Example usage:\n * ```ts\n * const client = new EventHubProducerClient(connectionString);\n * let batch = await client.createBatch();\n * for (let i = 0; i < messages.length; i++) {\n * if (!batch.tryAdd(messages[i])) {\n * await client.sendBatch(batch);\n * batch = await client.createBatch();\n * if (!batch.tryAdd(messages[i])) {\n * throw new Error(\"Message too big to fit\")\n * }\n * if (i === messages.length - 1) {\n * await client.sendBatch(batch);\n * }\n * }\n * }\n * ```\n * @param batch - A batch of events that you can create using the {@link createBatch} method.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal the request to cancel the send operation.\n *\n * @returns Promise<void>\n * @throws AbortError if the operation is cancelled via the abortSignal.\n * @throws MessagingError if an error is encountered while sending a message.\n * @throws Error if the underlying connection or sender has been closed.\n */\n async sendBatch(batch: EventDataBatch, options?: OperationOptions): Promise<void>; // eslint-disable-line @azure/azure-sdk/ts-naming-options\n async sendBatch(\n batch: EventDataBatch | EventData[],\n options: SendBatchOptions | OperationOptions = {},\n ): Promise<void> {\n throwErrorIfConnectionClosed(this._context);\n throwTypeErrorIfParameterMissing(this._context.connectionId, \"sendBatch\", \"batch\", batch);\n\n let partitionId: string | undefined;\n let partitionKey: string | undefined;\n\n // Holds an EventData properties object containing tracing properties.\n // This lets us avoid cloning batch when it is EventData[], which is\n // important as the idempotent EventHubSender needs to decorate the\n // original EventData passed through.\n const eventDataTracingProperties: Array<EventData[\"properties\"]> = [];\n\n // link message span contexts\n let spanContextsToLink: TracingContext[] = [];\n\n if (isEventDataBatch(batch)) {\n if (\n this._enableIdempotentRetries &&\n isDefined((batch as EventDataBatchImpl).startingPublishedSequenceNumber)\n ) {\n throw new Error(idempotentAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromBatch(batch, options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n spanContextsToLink = (batch as EventDataBatchImpl)._messageSpanContexts;\n } else {\n if (!Array.isArray(batch)) {\n batch = [batch];\n }\n if (batch.some((event) => isDefined((event as EventDataInternal)._publishedSequenceNumber))) {\n throw new Error(idempotentSomeAlreadyPublished);\n }\n const partitionAssignment = extractPartitionAssignmentFromOptions(options);\n partitionId = partitionAssignment.partitionId;\n partitionKey = partitionAssignment.partitionKey;\n\n for (let i = 0; i < batch.length; i++) {\n batch[i] = instrumentEventData(\n batch[i],\n options,\n this._context.config.entityPath,\n this._context.config.host,\n \"publish\",\n ).event;\n eventDataTracingProperties[i] = batch[i].properties;\n }\n }\n\n validateProducerPartitionSettings({\n enableIdempotentRetries: this._enableIdempotentRetries,\n partitionId,\n partitionKey,\n });\n\n return tracingClient.withSpan(\n `${EventHubProducerClient.name}.${this.sendBatch.name}`,\n options,\n (updatedOptions) => {\n let sender = this._sendersMap.get(partitionId || \"\");\n if (!sender) {\n const partitionPublishingOptions = isDefined(partitionId)\n ? this._partitionOptions?.[partitionId]\n : undefined;\n sender = EventHubSender.create(this._context, this.identifier, {\n enableIdempotentProducer: Boolean(this._enableIdempotentRetries),\n partitionId,\n partitionPublishingOptions,\n });\n this._sendersMap.set(partitionId || \"\", sender);\n }\n\n return sender.send(batch, {\n ...updatedOptions,\n partitionId,\n partitionKey,\n retryOptions: this._clientOptions.retryOptions,\n });\n },\n {\n spanLinks: spanContextsToLink.map<TracingSpanLink>((tracingContext) => {\n return { tracingContext };\n }),\n ...toSpanOptions(this._context.config, \"publish\", \"client\"),\n },\n );\n }\n\n /**\n * Closes the AMQP connection to the Event Hub instance,\n * returning a promise that will be resolved when disconnection is completed.\n * @returns Promise<void>\n * @throws Error if the underlying connection encounters an error while closing.\n */\n async close(): Promise<void> {\n await this._context.close();\n\n for (const pair of this._sendersMap) {\n await pair[1].close();\n }\n this._sendersMap.clear();\n }\n\n /**\n * Provides the Event Hub runtime information.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the Event Hub instance.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getEventHubProperties(options: GetEventHubPropertiesOptions = {}): Promise<EventHubProperties> {\n return this._context.managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n\n /**\n * Provides the id for each partition associated with the Event Hub.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with an Array of strings representing the id for\n * each partition associated with the Event Hub.\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionIds(options: GetPartitionIdsOptions = {}): Promise<Array<string>> {\n return this._context\n .managementSession!.getEventHubProperties({\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n })\n .then((eventHubProperties) => {\n return eventHubProperties.partitionIds;\n });\n }\n\n /**\n * Provides information about the state of the specified partition.\n * @param partitionId - The id of the partition for which information is required.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the state of the partition .\n * @throws Error if the underlying connection has been closed, create a new EventHubProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionProperties(\n partitionId: string,\n options: GetPartitionPropertiesOptions = {},\n ): Promise<PartitionProperties> {\n return this._context.managementSession!.getPartitionProperties(partitionId, {\n ...options,\n retryOptions: this._clientOptions.retryOptions,\n });\n }\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromOptions(options: SendBatchOptions = {}): {\n partitionKey?: string;\n partitionId?: string;\n} {\n const result: ReturnType<typeof extractPartitionAssignmentFromOptions> = {};\n const { partitionId, partitionKey } = options;\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n\n/**\n * @internal\n */\nfunction extractPartitionAssignmentFromBatch(\n batch: EventDataBatch,\n options: SendBatchOptions,\n): { partitionKey?: string; partitionId?: string } {\n const result: ReturnType<typeof extractPartitionAssignmentFromBatch> = {};\n const partitionId = batch.partitionId;\n const partitionKey = batch.partitionKey;\n\n const { partitionId: unexpectedPartitionId, partitionKey: unexpectedPartitionKey } =\n extractPartitionAssignmentFromOptions(options);\n if (unexpectedPartitionKey && partitionKey !== unexpectedPartitionKey) {\n throw new Error(\n `The partitionKey (${unexpectedPartitionKey}) set on sendBatch does not match the partitionKey (${partitionKey}) set when creating the batch.`,\n );\n }\n if (unexpectedPartitionId && unexpectedPartitionId !== partitionId) {\n throw new Error(\n `The partitionId (${unexpectedPartitionId}) set on sendBatch does not match the partitionId (${partitionId}) set when creating the batch.`,\n );\n }\n\n if (isDefined(partitionId)) {\n result.partitionId = String(partitionId);\n }\n if (isDefined(partitionKey)) {\n result.partitionKey = String(partitionKey);\n }\n\n return result;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortOptions, createAbortablePromise } from \"@azure/core-util\";\n\n/**\n * `AwaitableQueue` stores items in the order that they are received.\n *\n * This differs from ordinary Queues in that `shift` returns a Promise for a value.\n * This allows a consumer of the queue to request an item that the queue does not yet have.\n *\n * @internal\n */\nexport class AwaitableQueue<T> {\n private readonly _items: T[];\n\n private readonly _resolvers: Array<(value: T) => void> = [];\n\n constructor() {\n this._items = [];\n }\n\n public size(): number {\n return this._items.length;\n }\n\n /**\n * Returns a Promise that will resolve with the next item in the queue.\n */\n public shift(options?: AbortOptions): Promise<T> {\n const item = this._items.shift();\n if (typeof item !== \"undefined\") {\n return Promise.resolve(item);\n }\n\n return createAbortablePromise<T>((resolve) => this._resolvers.push(resolve), {\n ...options,\n cleanupBeforeAbort: () => this._resolvers.pop(),\n });\n }\n\n /**\n * Appends new item to the queue.\n */\n public push(item: T): void {\n if (!this._resolveNextItem(item)) {\n this._items.push(item);\n }\n }\n\n private _resolveNextItem(item: T) {\n const resolver = this._resolvers.shift();\n if (!resolver) {\n return false;\n }\n\n resolver(item);\n return true;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * @internal\n * Returns a promise and the promise's resolve and reject methods.\n */\nexport function getPromiseParts<T = unknown>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason: Error) => void;\n} {\n let resolver: (value: T) => void;\n let rejector: (reason?: any) => void;\n const promise = new Promise<T>((resolve, reject) => {\n resolver = resolve;\n rejector = reject;\n });\n return {\n promise,\n resolve: resolver!,\n reject: rejector!,\n };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AmqpAnnotatedMessage, delay } from \"@azure/core-amqp\";\nimport {\n EventData,\n EventDataBatch,\n EventHubBufferedProducerClientOptions,\n EventHubProducerClient,\n OperationOptions,\n} from \"./index\";\nimport { isDefined, isObjectWithProperties, AbortOptions } from \"@azure/core-util\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { AwaitableQueue } from \"./impl/awaitableQueue\";\nimport { getPromiseParts } from \"./util/getPromiseParts\";\nimport { logger } from \"./logger\";\nimport { cancelablePromiseRace } from \"@azure/core-util\";\n\nexport interface BatchingPartitionChannelProps {\n loopAbortSignal: AbortSignalLike;\n maxBufferSize: number;\n maxWaitTimeInMs: number;\n partitionId: string;\n producer: EventHubProducerClient;\n /**\n * The handler to call once a batch has successfully published.\n */\n onSendEventsSuccessHandler?: EventHubBufferedProducerClientOptions[\"onSendEventsSuccessHandler\"];\n /**\n * The handler to call when a batch fails to publish.\n */\n onSendEventsErrorHandler: EventHubBufferedProducerClientOptions[\"onSendEventsErrorHandler\"];\n}\n\n/**\n * The `BatchingPartitionChannel` is responsible for accepting enqueued events\n * and optimally batching and sending them to an Event Hub.\n * @internal\n */\nexport class BatchingPartitionChannel {\n private _eventQueue = new AwaitableQueue<EventData | AmqpAnnotatedMessage>();\n private _batchedEvents: Array<EventData | AmqpAnnotatedMessage> = [];\n private _bufferCount: number = 0;\n private _readyQueue: Array<{\n resolve: (value: void) => void;\n reject: (reason?: any) => void;\n }> = [];\n private _flushState:\n | { isFlushing: false }\n | { isFlushing: true; currentPromise: Promise<void>; resolve: () => void } = {\n isFlushing: false,\n };\n private _isRunning: boolean = false;\n private _lastBatchCreationTime: number = 0;\n private _loopAbortSignal: AbortSignalLike;\n private _maxBufferSize: number;\n private _maxWaitTimeInMs: number;\n private _onSendEventsErrorHandler: EventHubBufferedProducerClientOptions[\"onSendEventsErrorHandler\"];\n private _onSendEventsSuccessHandler?: EventHubBufferedProducerClientOptions[\"onSendEventsSuccessHandler\"];\n\n private _partitionId: string;\n private _producer: EventHubProducerClient;\n\n constructor({\n loopAbortSignal,\n maxBufferSize,\n maxWaitTimeInMs,\n onSendEventsErrorHandler,\n onSendEventsSuccessHandler,\n partitionId,\n producer,\n }: BatchingPartitionChannelProps) {\n this._loopAbortSignal = loopAbortSignal;\n this._maxBufferSize = maxBufferSize;\n this._maxWaitTimeInMs = maxWaitTimeInMs;\n this._onSendEventsErrorHandler = onSendEventsErrorHandler;\n this._onSendEventsSuccessHandler = onSendEventsSuccessHandler;\n this._partitionId = partitionId;\n this._producer = producer;\n }\n\n getCurrentBufferedCount(): number {\n return this._bufferCount;\n }\n\n async enqueueEvent(event: EventData | AmqpAnnotatedMessage): Promise<void> {\n await this._ready();\n this._eventQueue.push(event);\n this._bufferCount++;\n\n if (!this._isRunning) {\n this._isRunning = true;\n this._startPublishLoop().catch((e) => {\n logger.error(\n `The following error occured during batch creation or sending: ${JSON.stringify(\n e,\n undefined,\n \" \",\n )}`,\n );\n });\n }\n }\n\n /**\n * Sets the flush state so that no new events can be enqueued until\n * all the currently buffered events are sent to the Event Hub.\n *\n * Returns a promise that resolves once flushing is complete.\n */\n async flush(_options: OperationOptions = {}): Promise<void> {\n const state = this._flushState;\n if (state.isFlushing) {\n return state.currentPromise;\n }\n\n if (this.getCurrentBufferedCount() === 0) {\n return Promise.resolve();\n }\n\n const { promise, resolve } = getPromiseParts<void>();\n this._flushState = { isFlushing: true, currentPromise: promise, resolve };\n\n return promise;\n }\n\n /**\n * Returns a promise that resolves once there is room for events to be added\n * to the buffer.\n */\n private _ready(): Promise<void> {\n const currentBufferedCount = this.getCurrentBufferedCount();\n\n // If the buffer isn't full and we don't have any pending `ready()` calls,\n // then it's safe to return right away.\n if (\n currentBufferedCount < this._maxBufferSize &&\n !this._readyQueue.length &&\n !this._flushState.isFlushing\n ) {\n return Promise.resolve();\n }\n\n const { promise: readyPromise, reject, resolve } = getPromiseParts<void>();\n this._readyQueue.push({ resolve, reject });\n\n return readyPromise;\n }\n\n /**\n * Starts the loop that creates batches and sends them to the Event Hub.\n *\n * The loop will run until the `_loopAbortSignal` is aborted.\n */\n private async _startPublishLoop() {\n let batch: EventDataBatch | undefined;\n // `eventToAddToBatch` is used to keep track of an event that has been removed\n // from the queue, but has not yet been added to a batch.\n // This prevents losing an event if a `sendBatch` or `createBatch` call fails\n // before the event is added to a batch.\n let eventToAddToBatch: EventData | AmqpAnnotatedMessage | undefined;\n while (!this._loopAbortSignal.aborted) {\n try {\n if (!isDefined(batch)) {\n batch = await this._createBatch();\n }\n const timeSinceLastBatchCreation = Date.now() - this._lastBatchCreationTime;\n const maximumTimeToWaitForEvent = batch.count\n ? Math.max(this._maxWaitTimeInMs - timeSinceLastBatchCreation, 0)\n : this._maxWaitTimeInMs;\n\n const event =\n eventToAddToBatch ??\n (await cancelablePromiseRace<[EventData | AmqpAnnotatedMessage, void]>(\n [\n (abortOptions: AbortOptions) => this._eventQueue.shift(abortOptions),\n (abortOptions: AbortOptions) =>\n delay<void>(\n maximumTimeToWaitForEvent,\n abortOptions.abortSignal,\n abortOptions.abortErrorMsg,\n ),\n ],\n { abortSignal: this._loopAbortSignal },\n ));\n\n if (!event) {\n // We didn't receive an event within the allotted time.\n // Send the existing batch if it has events in it.\n if (batch.count) {\n await this._producer.sendBatch(batch);\n this._reportSuccess();\n batch = await this._createBatch();\n }\n continue;\n } else if (!eventToAddToBatch) {\n eventToAddToBatch = event;\n }\n\n const didAdd = batch.tryAdd(event);\n if (didAdd) {\n // This event will definitely make it to one of the user-provided handlers\n // since it was added to a batch.\n // Store it so we can return it in a handler later.\n this._batchedEvents.push(event);\n // Clear reference to existing event since it has been added to the batch.\n eventToAddToBatch = undefined;\n }\n\n if (didAdd && batch.count >= this._maxBufferSize) {\n // Whenever batch.count exceeds the max count of buffered events, send the batch.\n await this._producer.sendBatch(batch);\n this._reportSuccess();\n batch = await this._createBatch();\n } else if (!didAdd && batch.count) {\n // If the event wasn't able to be added and the current batch isn't empty,\n // attempt to send the current batch and add the event to a new batch.\n await this._producer.sendBatch(batch);\n this._reportSuccess();\n batch = await this._createBatch();\n }\n\n if (!didAdd && !batch.tryAdd(event)) {\n // TODO: Report MaxMesageSizeExceeded error. Mimic service's error.\n this._reportFailure(new Error(\"Placeholder for max message size exceeded\"), event);\n } else if (!didAdd) {\n // Handles the case where the event _was_ successfull added to the new batch.\n this._batchedEvents.push(event);\n }\n // Clear reference to existing event since it has been added to the batch.\n eventToAddToBatch = undefined;\n } catch (err: any) {\n if (!isObjectWithProperties(err, [\"name\"]) || err.name !== \"AbortError\") {\n this._reportFailure(err);\n batch = undefined;\n this._batchedEvents = [];\n }\n }\n }\n }\n\n /**\n * Helper method that returns an `EventDataBatch`.\n * This also has the side effects of\n * - keeping track of batch creation time: needed for maxWaitTime calculations.\n * - clearing reference to batched events.\n * - incrementing the readiness: creating a new batch indicates the buffer\n * should have room, so we can resolve some pending `ready()` calls.\n */\n private async _createBatch(): Promise<EventDataBatch> {\n this._lastBatchCreationTime = Date.now();\n this._batchedEvents = [];\n const batch = await this._producer.createBatch({\n partitionId: this._partitionId,\n });\n this._incrementReadiness();\n return batch;\n }\n\n /**\n * This method will resolve as many pending `ready()` calls as it can\n * based on how much space remains in the buffer.\n *\n * If the channel is currently flushing, this is a no-op. This prevents\n * `enqueueEvent` calls from adding the event to the buffer until flushing\n * completes.\n */\n private _incrementReadiness() {\n if (this._flushState.isFlushing) {\n return;\n }\n const currentBufferedCount = this.getCurrentBufferedCount();\n const num = Math.min(this._maxBufferSize - currentBufferedCount, this._readyQueue.length);\n for (let i = 0; i < num; i++) {\n this._readyQueue.shift()?.resolve();\n }\n }\n\n /**\n * Calls the user-provided `onSendEventsSuccessHandler` with the events\n * that were successfully sent.\n */\n private _reportSuccess() {\n this._bufferCount = this._bufferCount - this._batchedEvents.length;\n this._updateFlushState();\n try {\n this._onSendEventsSuccessHandler?.({\n events: this._batchedEvents,\n partitionId: this._partitionId,\n });\n } catch (e: unknown) {\n logger.error(\n `The following error occurred in the onSendEventsSuccessHandler: ${JSON.stringify(\n e,\n undefined,\n \" \",\n )}`,\n );\n }\n }\n\n /**\n * Calls the user-provided `onSendEventsErrorHandler` with an error and the events\n * that were not successfully sent.\n */\n private _reportFailure(err: any, event?: EventData | AmqpAnnotatedMessage) {\n this._bufferCount = this._bufferCount - (event ? 1 : this._batchedEvents.length);\n this._updateFlushState();\n try {\n this._onSendEventsErrorHandler({\n error: err,\n events: event ? [event] : this._batchedEvents,\n partitionId: this._partitionId,\n });\n } catch (e: unknown) {\n logger.error(\n `The following error occurred in the onSendEventsErrorHandler: ${JSON.stringify(\n e,\n undefined,\n \" \",\n )}`,\n );\n }\n }\n\n /**\n * Updates the channel's flush state once the size of the\n * event buffer has decreased to 0.\n */\n private _updateFlushState() {\n const state = this._flushState;\n if (!state.isFlushing || this.getCurrentBufferedCount() !== 0) {\n return;\n }\n\n state.resolve();\n\n this._flushState = { isFlushing: false };\n this._incrementReadiness();\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/* eslint-disable no-fallthrough */\n\nexport function mapPartitionKeyToId(partitionKey: string, partitionCount: number): number {\n const hashedParitionKey = hashPartitionKey(partitionKey);\n return Math.abs(hashedParitionKey % partitionCount);\n}\n\n/**\n * @internal\n */\nexport function hashPartitionKey(partitionKey: string): number {\n const hash = computeHash(Buffer.from(partitionKey, \"utf8\"));\n return castToInt16(hash.c ^ hash.b);\n}\n\nfunction readUInt32(data: Buffer, offset: number): number {\n return data.readUInt32LE(offset);\n}\n\nfunction castToInt16(n: number): number {\n return new Int16Array([n])[0];\n}\n\nfunction computeHash(\n data: Buffer,\n seed1: number = 0,\n seed2: number = 0,\n): {\n b: number;\n c: number;\n} {\n let a: number, b: number, c: number;\n\n a = b = c = 0xdeadbeef + data.length + seed1;\n c += seed2;\n\n let index = 0,\n size = data.length;\n while (size > 12) {\n a += readUInt32(data, index);\n b += readUInt32(data, index + 4);\n c += readUInt32(data, index + 8);\n\n a -= c;\n a ^= (c << 4) | (c >>> 28);\n c += b;\n\n b -= a;\n b ^= (a << 6) | (a >>> 26);\n a += c;\n\n c -= b;\n c ^= (b << 8) | (b >>> 24);\n b += a;\n\n a -= c;\n a ^= (c << 16) | (c >>> 16);\n c += b;\n\n b -= a;\n b ^= (a << 19) | (a >>> 13);\n a += c;\n\n c -= b;\n c ^= (b << 4) | (b >>> 28);\n b += a;\n\n index += 12;\n size -= 12;\n }\n\n let curr = size;\n switch (curr) {\n case 12:\n a += readUInt32(data, index);\n b += readUInt32(data, index + 4);\n c += readUInt32(data, index + 8);\n break;\n case 11:\n c += data[index + 10] << 16;\n curr = 10;\n case 10:\n c += data[index + 9] << 8;\n curr = 9;\n case 9:\n c += data[index + 8];\n curr = 8;\n case 8:\n b += readUInt32(data, index + 4);\n a += readUInt32(data, index);\n break;\n case 7:\n b += data[index + 6] << 16;\n curr = 6;\n case 6:\n b += data[index + 5] << 8;\n curr = 5;\n case 5:\n b += data[index + 4];\n curr = 4;\n case 4:\n a += readUInt32(data, index);\n break;\n case 3:\n a += data[index + 2] << 16;\n curr = 2;\n case 2:\n a += data[index + 1] << 8;\n curr = 1;\n case 1:\n a += data[index];\n break;\n case 0:\n return { b: b >>> 0, c: c >>> 0 };\n }\n\n c ^= b;\n c -= (b << 14) | (b >>> 18);\n\n a ^= c;\n a -= (c << 11) | (c >>> 21);\n\n b ^= a;\n b -= (a << 25) | (a >>> 7);\n\n c ^= b;\n c -= (b << 16) | (b >>> 16);\n\n a ^= c;\n a -= (c << 4) | (c >>> 28);\n\n b ^= a;\n b -= (a << 14) | (a >>> 18);\n\n c ^= b;\n c -= (b << 24) | (b >>> 8);\n\n return { b: b >>> 0, c: c >>> 0 };\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isDefined } from \"@azure/core-util\";\nimport { mapPartitionKeyToId } from \"./partitionKeyToIdMapper\";\n\n/**\n * @internal\n * Assigns a partition based on the partition ids it knows about and an optional partition id or partition key.\n */\nexport class PartitionAssigner {\n private _partitions: string[] = [];\n\n private _lastRoundRobinPartitionIndex: number = -1;\n\n /**\n * Set the partition ids that can be used when assigning a partition.\n * @param partitionIds - All valid partition ids.\n */\n public setPartitionIds(partitionIds: string[]): void {\n this._partitions = partitionIds;\n }\n\n /**\n * Returns a partitionId from the list of partition ids set via `setPartitionIds`.\n *\n * If a partitionId is specified, then that will be returned directly.\n * If a partitionKey is specified, then a partitionId will be calculated based on the partitionKey.\n * Specifying both partitionId and partitionKey results in an error.\n *\n * If neither partitionId nor partitionKey are specified, then a partitionId will be selected\n * based on a round-robin approach.\n */\n assignPartition({\n partitionId,\n partitionKey,\n }: {\n partitionId?: string;\n partitionKey?: string;\n }): string {\n if (isDefined(partitionId) && isDefined(partitionKey)) {\n throw new Error(\n `The partitionId (${partitionId}) and partitionKey (${partitionKey}) cannot both be specified.`,\n );\n }\n\n if (!this._partitions.length) {\n throw new Error(`Unable to determine partitionIds, can't assign partitionId.`);\n }\n\n if (isDefined(partitionId) && this._partitions.includes(partitionId)) {\n return partitionId;\n }\n\n if (isDefined(partitionKey)) {\n return mapPartitionKeyToId(partitionKey, this._partitions.length).toString();\n }\n\n return this._assignRoundRobinPartition();\n }\n\n private _assignRoundRobinPartition(): string {\n const maxPartitionIndex = this._partitions.length - 1;\n const proposedPartitionIndex = this._lastRoundRobinPartitionIndex + 1;\n\n const nextPartitionIndex =\n proposedPartitionIndex > maxPartitionIndex ? 0 : proposedPartitionIndex;\n\n this._lastRoundRobinPartitionIndex = nextPartitionIndex;\n return this._partitions[nextPartitionIndex];\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { EventData } from \"./eventData\";\nimport { EventHubProducerClient } from \"./eventHubProducerClient\";\nimport { OperationOptions } from \"./util/operationOptions\";\nimport {\n EventHubClientOptions,\n GetEventHubPropertiesOptions,\n GetPartitionIdsOptions,\n GetPartitionPropertiesOptions,\n SendBatchOptions,\n} from \"./models/public\";\nimport { EventHubProperties, PartitionProperties } from \"./managementClient\";\nimport { NamedKeyCredential, SASCredential, TokenCredential } from \"@azure/core-auth\";\nimport { isDefined } from \"@azure/core-util\";\nimport { isCredential } from \"./util/typeGuards\";\nimport { AbortController } from \"@azure/abort-controller\";\nimport { AmqpAnnotatedMessage, delay } from \"@azure/core-amqp\";\nimport { BatchingPartitionChannel } from \"./batchingPartitionChannel\";\nimport { PartitionAssigner } from \"./impl/partitionAssigner\";\nimport { logger } from \"./logger\";\nimport { getRandomName } from \"./util/utils\";\n\n/**\n * Contains the events that were successfully sent to the Event Hub,\n * and the partition they were assigned to.\n */\nexport interface OnSendEventsSuccessContext {\n /**\n * The partition each event was assigned.\n */\n partitionId: string;\n /**\n * The array of {@link EventData} and/or `AmqpAnnotatedMessage` that were successfully sent to the Event Hub.\n */\n events: Array<EventData | AmqpAnnotatedMessage>;\n}\n\n/**\n * Contains the events that were not successfully sent to the Event Hub,\n * the partition they were assigned to, and the error that was encountered while sending.\n */\nexport interface OnSendEventsErrorContext {\n /**\n * The partition each event was assigned.\n */\n partitionId: string;\n /**\n * The array of {@link EventData} and/or `AmqpAnnotatedMessage` that were not successfully sent to the Event Hub.\n */\n events: Array<EventData | AmqpAnnotatedMessage>;\n /**\n * The error that occurred when sending the associated events to the Event Hub.\n */\n error: Error;\n}\n\n/**\n * Describes the options that can be provided while creating the `EventHubBufferedProducerClient`.\n */\nexport interface EventHubBufferedProducerClientOptions extends EventHubClientOptions {\n /**\n * The total number of events that can be buffered for publishing at a given time for a given partition.\n *\n * Default: 1500\n */\n maxEventBufferLengthPerPartition?: number;\n /**\n * The amount of time to wait for a new event to be enqueued in the buffer before publishing a partially full batch.\n *\n * Default: 1 second.\n */\n maxWaitTimeInMs?: number;\n /**\n * The handler to call once a batch has successfully published.\n */\n onSendEventsSuccessHandler?: (ctx: OnSendEventsSuccessContext) => void;\n /**\n * The handler to call when a batch fails to publish.\n */\n onSendEventsErrorHandler: (ctx: OnSendEventsErrorContext) => void;\n /**\n * Indicates whether or not the EventHubProducerClient should enable idempotent publishing to Event Hub partitions.\n * If enabled, the producer will only be able to publish directly to partitions;\n * it will not be able to publish to the Event Hubs gateway for automatic partition routing\n * nor will it be able to use a partition key.\n * Default: false\n */\n enableIdempotentRetries?: boolean;\n}\n\n/**\n * Options to configure the `flush` method on the `EventHubBufferedProducerClient`.\n */\nexport interface BufferedFlushOptions extends OperationOptions {}\n\n/**\n * Options to configure the `close` method on the `EventHubBufferedProducerClient`.\n */\nexport interface BufferedCloseOptions extends OperationOptions {\n /**\n * When `true`, all buffered events that are pending should be sent before closing.\n * When `false`, abandon all buffered events and close immediately.\n * Defaults to `true`.\n */\n flush?: boolean;\n}\n\n/**\n * Options to configure the `enqueueEvents` method on the `EventHubBufferedProducerClient`.\n */\nexport interface EnqueueEventOptions extends SendBatchOptions {}\n\n/**\n * The `EventHubBufferedProducerClient`is used to publish events to a specific Event Hub.\n *\n * The `EventHubBufferedProducerClient` does not publish events immediately.\n * Instead, events are buffered so they can be efficiently batched and published\n * when the batch is full or the `maxWaitTimeInMs` has elapsed with no new events\n * enqueued.\n *\n * Depending on the options specified when events are enqueued, they may be\n * automatically assigned to a partition, grouped according to the specified partition key,\n * or assigned a specifically requested partition.\n *\n * This model is intended to shift the burden of batch management from callers, at the cost of\n * non-deterministic timing, for when events will be published. There are additional trade-offs\n * to consider, as well:\n * - If the application crashes, events in the buffer will not have been published. To prevent\n * data loss, callers are encouraged to track publishing progress using the\n * `onSendEventsSuccessHandler` and `onSendEventsErrorHandler` handlers.\n * - Events specifying a partition key may be assigned a different partition than those using\n * the same key with other producers.\n * - In the unlikely event that a partition becomes temporarily unavailable, the\n * `EventHubBufferedProducerClient` may take longer to recover than other producers.\n *\n * In scenarios where it is important to have events published immediately with a deterministic\n * outcome, ensure that partition keys are assigned to a partition consistent with other\n * publishers, or where maximizing availability is a requirement, using the\n * `EventHubProducerClient` is recommended.\n */\nexport class EventHubBufferedProducerClient {\n /**\n * Controls the `abortSignal` passed to each `BatchingPartitionChannel`.\n * Used to signal when a channel should stop waiting for events.\n */\n private _abortController = new AbortController();\n\n /**\n * Indicates whether the client has been explicitly closed.\n */\n private _isClosed: boolean = false;\n\n /**\n * Handles assigning partitions.\n */\n private _partitionAssigner = new PartitionAssigner();\n\n /**\n * The known partitionIds that will be used when assigning events to partitions.\n */\n private _partitionIds: string[] = [];\n\n /**\n * The EventHubProducerClient to use when creating and sending batches to the Event Hub.\n */\n private _producer: EventHubProducerClient;\n\n /**\n * Mapping of partitionIds to `BatchingPartitionChannels`.\n * Each `BatchingPartitionChannel` handles buffering events and backpressure independently.\n */\n private _partitionChannels = new Map<string, BatchingPartitionChannel>();\n\n /**\n * The options passed by the user when creating the EventHubBufferedProducerClient instance.\n */\n private _clientOptions: EventHubBufferedProducerClientOptions;\n\n /**\n * The interval at which the background management operation should run.\n */\n private _backgroundManagementInterval = 10000; // 10 seconds\n\n /**\n * Indicates whether the background management loop is running.\n */\n private _isBackgroundManagementRunning = false;\n\n /**\n * @readonly\n * The name of the Event Hub instance for which this client is created.\n */\n get eventHubName(): string {\n return this._producer.eventHubName;\n }\n\n /**\n * @readonly\n * The fully qualified namespace of the Event Hub instance for which this client is created.\n * This is likely to be similar to <yournamespace>.servicebus.windows.net.\n */\n get fullyQualifiedNamespace(): string {\n return this._producer.fullyQualifiedNamespace;\n }\n\n /**\n * The name used to identify this EventHubBufferedProducerClient.\n * If not specified or empty, a random unique one will be generated.\n */\n public readonly identifier: string;\n\n /**\n * The `EventHubBufferedProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hub instance.\n * It is expected that the shared key properties and the Event Hub path are contained in this connection string.\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;EntityPath=my-event-hub-name'.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(connectionString: string, options: EventHubBufferedProducerClientOptions);\n /**\n * The `EventHubBufferedProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param connectionString - The connection string to use for connecting to the Event Hubs namespace.\n * It is expected that the shared key properties are contained in this connection string, but not the Event Hub path,\n * e.g. 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key;'.\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n connectionString: string,\n eventHubName: string,\n options: EventHubBufferedProducerClientOptions,\n );\n /**\n * The `EventHubBufferedProducerClient` class is used to send events to an Event Hub.\n * Use the `options` parmeter to configure retry policy or proxy settings.\n * @param fullyQualifiedNamespace - The full namespace which is likely to be similar to\n * <yournamespace>.servicebus.windows.net\n * @param eventHubName - The name of the specific Event Hub to connect the client to.\n * @param credential - An credential object used by the client to get the token to authenticate the connection\n * with the Azure Event Hubs service.\n * See &commat;azure/identity for creating credentials that support AAD auth.\n * Use the `AzureNamedKeyCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessKeyName`\n * and `SharedAccessKey` without using a connection string. These fields map to the `name` and `key` field respectively\n * in `AzureNamedKeyCredential`.\n * Use the `AzureSASCredential` from &commat;azure/core-auth if you want to pass in a `SharedAccessSignature`\n * without using a connection string. This field maps to `signature` in `AzureSASCredential`.\n * @param options - A set of options to apply when configuring the client.\n * - `retryOptions` : Configures the retry policy for all the operations on the client.\n * For example, `{ \"maxRetries\": 4 }` or `{ \"maxRetries\": 4, \"retryDelayInMs\": 30000 }`.\n * - `webSocketOptions`: Configures the channelling of the AMQP connection over Web Sockets.\n * - `userAgent` : A string to append to the built in user agent string that is passed to the service.\n */\n constructor(\n fullyQualifiedNamespace: string,\n eventHubName: string,\n credential: TokenCredential | NamedKeyCredential | SASCredential,\n options: EventHubBufferedProducerClientOptions,\n );\n constructor(\n fullyQualifiedNamespaceOrConnectionString1: string,\n eventHubNameOrOptions2: string | EventHubBufferedProducerClientOptions,\n credentialOrOptions3?:\n | TokenCredential\n | NamedKeyCredential\n | SASCredential\n | EventHubBufferedProducerClientOptions,\n options4?: EventHubBufferedProducerClientOptions,\n ) {\n if (typeof eventHubNameOrOptions2 !== \"string\") {\n this.identifier = eventHubNameOrOptions2.identifier ?? getRandomName();\n this._producer = new EventHubProducerClient(fullyQualifiedNamespaceOrConnectionString1, {\n ...eventHubNameOrOptions2,\n identifier: this.identifier,\n });\n this._clientOptions = { ...eventHubNameOrOptions2 };\n } else if (!isCredential(credentialOrOptions3)) {\n this.identifier = credentialOrOptions3?.identifier ?? getRandomName();\n this._producer = new EventHubProducerClient(\n fullyQualifiedNamespaceOrConnectionString1,\n eventHubNameOrOptions2,\n { ...credentialOrOptions3, identifier: this.identifier },\n );\n this._clientOptions = { ...credentialOrOptions3! };\n } else {\n this.identifier = options4?.identifier ?? getRandomName();\n this._producer = new EventHubProducerClient(\n fullyQualifiedNamespaceOrConnectionString1,\n eventHubNameOrOptions2,\n credentialOrOptions3,\n { ...options4, identifier: this.identifier },\n );\n this._clientOptions = { ...options4! };\n }\n // setting internal idempotent publishing option on the standard producer.\n (this._producer as any)._enableIdempotentRetries = this._clientOptions.enableIdempotentRetries;\n }\n\n /**\n * Closes the AMQP connection to the Event Hub instance,\n * returning a promise that will be resolved when disconnection is completed.\n *\n * This will wait for enqueued events to be flushed to the service before closing\n * the connection.\n * To close without flushing, set the `flush` option to `false`.\n *\n * @param options - The set of options to apply to the operation call.\n * @returns Promise<void>\n * @throws Error if the underlying connection encounters an error while closing.\n */\n async close(options: BufferedCloseOptions = {}): Promise<void> {\n logger.verbose(\"closing buffered producer client...\");\n if (!isDefined(options.flush) || options.flush === true) {\n await this.flush(options);\n }\n // Calling abort signals to the BatchingPartitionChannels that they\n // should stop reading/sending events, and to the background management\n // loop that it should stop periodic partition id updates.\n this._abortController.abort();\n await this._producer.close();\n this._isClosed = true;\n }\n\n /**\n * Enqueues an event into the buffer to be published to the Event Hub.\n * If there is no capacity in the buffer when this method is invoked,\n * it will wait for space to become available and ensure that the event\n * has been enqueued.\n *\n * When this call returns, the event has been accepted into the buffer,\n * but it may not have been published yet.\n * Publishing will take place at a nondeterministic point in the future as the buffer is processed.\n *\n * @param events - An {@link EventData} or `AmqpAnnotatedMessage`.\n * @param options - A set of options that can be specified to influence the way in which\n * the event is sent to the associated Event Hub.\n * - `abortSignal` : A signal used to cancel the enqueueEvent operation.\n * - `partitionId` : The partition this set of events will be sent to. If set, `partitionKey` can not be set.\n * - `partitionKey` : A value that is hashed to produce a partition assignment. If set, `partitionId` can not be set.\n * @returns The total number of events that are currently buffered and waiting to be published, across all partitions.\n */\n async enqueueEvent(\n event: EventData | AmqpAnnotatedMessage,\n options: EnqueueEventOptions = {},\n ): Promise<number> {\n if (this._isClosed) {\n throw new Error(\n `This EventHubBufferedProducerClient has already been closed. Create a new client to enqueue events.`,\n );\n }\n\n if (!this._partitionIds.length) {\n await this._updatePartitionIds();\n }\n if (!this._isBackgroundManagementRunning) {\n this._startPartitionIdsUpdateLoop().catch((e) => {\n logger.error(\n `The following error occured during batch creation or sending: ${JSON.stringify(\n e,\n undefined,\n \" \",\n )}`,\n );\n });\n this._isBackgroundManagementRunning = true;\n }\n\n const partitionId = this._partitionAssigner.assignPartition({\n partitionId: options.partitionId,\n partitionKey: options.partitionKey,\n });\n\n const partitionChannel = this._getPartitionChannel(partitionId);\n await partitionChannel.enqueueEvent(event);\n return this._getTotalBufferedEventsCount();\n }\n\n /**\n * Enqueues events into the buffer to be published to the Event Hub.\n * If there is no capacity in the buffer when this method is invoked,\n * it will wait for space to become available and ensure that the events\n * have been enqueued.\n *\n * When this call returns, the events have been accepted into the buffer,\n * but it may not have been published yet.\n * Publishing will take place at a nondeterministic point in the future as the buffer is processed.\n *\n * @param events - An array of {@link EventData} or `AmqpAnnotatedMessage`.\n * @param options - A set of options that can be specified to influence the way in which\n * events are sent to the associated Event Hub.\n * - `abortSignal` : A signal used to cancel the enqueueEvents operation.\n * - `partitionId` : The partition this set of events will be sent to. If set, `partitionKey` can not be set.\n * - `partitionKey` : A value that is hashed to produce a partition assignment. If set, `partitionId` can not be set.\n * @returns The total number of events that are currently buffered and waiting to be published, across all partitions.\n */\n async enqueueEvents(\n events: EventData[] | AmqpAnnotatedMessage[],\n options: EnqueueEventOptions = {},\n ): Promise<number> {\n for (const event of events) {\n await this.enqueueEvent(event, options);\n }\n\n return this._getTotalBufferedEventsCount();\n }\n\n /**\n * Attempts to publish all events in the buffer immediately.\n * This may result in multiple batches being published,\n * the outcome of each of which will be individually reported by\n * the `onSendEventsSuccessHandler` and `onSendEventsErrorHandler` handlers.\n *\n * @param options - The set of options to apply to the operation call.\n */\n async flush(options: BufferedFlushOptions = {}): Promise<void> {\n await Promise.all(\n Array.from(this._partitionChannels.values()).map((channel) => channel.flush(options)),\n );\n }\n\n /**\n * Provides the Event Hub runtime information.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the Event Hub instance.\n * @throws Error if the underlying connection has been closed, create a new EventHubBufferedProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getEventHubProperties(options: GetEventHubPropertiesOptions = {}): Promise<EventHubProperties> {\n return this._producer.getEventHubProperties(options);\n }\n\n /**\n * Provides the id for each partition associated with the Event Hub.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with an Array of strings representing the id for\n * each partition associated with the Event Hub.\n * @throws Error if the underlying connection has been closed, create a new EventHubBufferedProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionIds(options: GetPartitionIdsOptions = {}): Promise<Array<string>> {\n return this._producer.getPartitionIds(options);\n }\n\n /**\n * Provides information about the state of the specified partition.\n * @param partitionId - The id of the partition for which information is required.\n * @param options - The set of options to apply to the operation call.\n * @returns A promise that resolves with information about the state of the partition .\n * @throws Error if the underlying connection has been closed, create a new EventHubBufferedProducerClient.\n * @throws AbortError if the operation is cancelled via the abortSignal.\n */\n getPartitionProperties(\n partitionId: string,\n options: GetPartitionPropertiesOptions = {},\n ): Promise<PartitionProperties> {\n return this._producer.getPartitionProperties(partitionId, options);\n }\n\n /**\n * Gets the `BatchingPartitionChannel` associated with the partitionId.\n *\n * If one does not exist, it is created.\n */\n private _getPartitionChannel(partitionId: string): BatchingPartitionChannel {\n const partitionChannel =\n this._partitionChannels.get(partitionId) ??\n new BatchingPartitionChannel({\n loopAbortSignal: this._abortController.signal,\n maxBufferSize: this._clientOptions.maxEventBufferLengthPerPartition || 1500,\n maxWaitTimeInMs: this._clientOptions.maxWaitTimeInMs || 1000,\n onSendEventsErrorHandler: this._clientOptions.onSendEventsErrorHandler,\n onSendEventsSuccessHandler: this._clientOptions.onSendEventsSuccessHandler,\n partitionId,\n producer: this._producer,\n });\n this._partitionChannels.set(partitionId, partitionChannel);\n return partitionChannel;\n }\n\n /**\n * Returns the total number of buffered events across all partitions.\n */\n private _getTotalBufferedEventsCount(): number {\n let total = 0;\n for (const [_, channel] of this._partitionChannels) {\n total += channel.getCurrentBufferedCount();\n }\n\n return total;\n }\n\n private async _updatePartitionIds(): Promise<void> {\n logger.verbose(\"Checking for partition Id updates...\");\n const queriedPartitionIds = await this.getPartitionIds();\n\n if (this._partitionIds.length !== queriedPartitionIds.length) {\n logger.verbose(\"Applying partition Id updates\");\n this._partitionIds = queriedPartitionIds;\n this._partitionAssigner.setPartitionIds(this._partitionIds);\n }\n }\n\n private async _startPartitionIdsUpdateLoop(): Promise<void> {\n logger.verbose(\"Starting a background loop to check and apply partition id updates...\");\n while (!this._abortController.signal.aborted && !this._isClosed) {\n await delay<void>(this._backgroundManagementInterval);\n if (!this._isClosed) {\n await this._updatePartitionIds();\n }\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { EventData } from \"./eventData\";\n\n/**\n * A message with payload and content type fields\n *\n * This interface is hidden because it is already exported by `@azure/schema-registry-avro`\n *\n * @hidden\n */\nexport interface MessageContent {\n /**\n * The message's binary data\n */\n data: Uint8Array;\n /**\n * The message's content type\n */\n contentType: string;\n}\n\n/**\n * A message adapter interface that specifies methods for producing and consuming\n * messages with payloads and content type fields.\n *\n * This interface is hidden because it is already exported by `@azure/schema-registry-avro`\n *\n * @hidden\n */\nexport interface MessageAdapter<MessageT> {\n /**\n * defines how to create a message from a payload and a content type\n */\n produce: (MessageContent: MessageContent) => MessageT;\n /**\n * defines how to access the payload and the content type of a message\n */\n consume: (message: MessageT) => MessageContent;\n}\n\n// This type should always be equivalent to Omit<Omit<EventData, \"body\">, \"contentType\">\n/**\n * Parameters to the `createEventDataAdapter` function that creates an event data adapter.\n */\nexport interface EventDataAdapterParameters {\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 * A function that constructs an event data adapter. That adapter can be used\n * with `@azure/schema-registry-avro` to encode and decode body in event data.\n *\n * @param params - parameters to create the event data\n * @returns An event data adapter that can produce and consume event data\n */\nexport function createEventDataAdapter(\n params: EventDataAdapterParameters = {},\n): MessageAdapter<EventData> {\n return {\n produce: ({ data: body, contentType }: MessageContent) => {\n return {\n ...params,\n body,\n contentType,\n };\n },\n consume: (message: EventData): MessageContent => {\n const { body, contentType } = message;\n if (body === undefined) {\n throw new Error(\"Expected the body field to be defined\");\n }\n if (contentType === undefined) {\n throw new Error(\"Expected the contentType field to be defined\");\n }\n return {\n /**\n * If the raw response was parsed as JSON, we need to convert it to a Uint8Array,\n * otherwise, leave the payload as is.\n */\n data: typeof body === \"object\" ? Uint8Array.from(Object.values(body)) : body,\n contentType,\n };\n },\n };\n}\n"],"names":["createClientLogger","isObjectWithProperties","isDefined","Constants","translate","ErrorNameConditionMapper","objectHasProperty","CloseReason","message","Buffer","AmqpAnnotatedMessage","types","randomUUID","defaultCancellableLock","TokenType","isSasTokenProvider","logger","azureLogger","AbortError","StandardAbortMessage","retry","RetryOperationType","createAbortablePromise","AbortController","createTracingClient","delay","parseConnectionString","isMessagingError","isAmqpError","RequestResponseLink","SenderEvents","ReceiverEvents","ConnectionConfig","os","isTokenCredential","isNamedKeyCredential","isSASCredential","ConnectionContextBase","ConnectionEvents","createSasTokenProvider","cancelablePromiseRace"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAKA;;;AAGG;MACU,MAAM,GAAGA,2BAAkB,CAAC,YAAY,EAAE;AAEvD;;;;AAIG;AACG,SAAU,kBAAkB,CAAC,KAAc,EAAA;IAC/C,IAAIC,+BAAsB,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE;AAC5C,QAAA,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;KAC7B;AACH,CAAC;AAED;;AAEG;SACa,uBAAuB,CACrC,UAAkB,EAClB,YAAoB,EACpB,WAAmB,EAAA;AAEnB,IAAA,OAAO,IAAI,YAAY,CAAA,YAAA,EAAe,WAAW,CAAI,CAAA,EAAA,UAAU,EAAE,CAAC;AACpE,CAAC;AAED;;AAEG;AACa,SAAA,qBAAq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